1 // Copyright (C) 2007-2022 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_ViscousLayers.cxx
21 // Created : Wed Dec 1 15:15:34 2010
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers.hxx"
26 #include "ObjectPool.hxx"
27 #include "SMDS_EdgePosition.hxx"
28 #include "SMDS_FaceOfNodes.hxx"
29 #include "SMDS_FacePosition.hxx"
30 #include "SMDS_MeshNode.hxx"
31 #include "SMDS_PolygonalFaceOfNodes.hxx"
32 #include "SMDS_SetIterator.hxx"
33 #include "SMESHDS_Group.hxx"
34 #include "SMESHDS_Hypothesis.hxx"
35 #include "SMESHDS_Mesh.hxx"
36 #include "SMESH_Algo.hxx"
37 #include "SMESH_Block.hxx"
38 #include "SMESH_ComputeError.hxx"
39 #include "SMESH_ControlsDef.hxx"
40 #include "SMESH_Gen.hxx"
41 #include "SMESH_Group.hxx"
42 #include "SMESH_HypoFilter.hxx"
43 #include "SMESH_Mesh.hxx"
44 #include "SMESH_MeshAlgos.hxx"
45 #include "SMESH_MeshEditor.hxx"
46 #include "SMESH_MesherHelper.hxx"
47 #include "SMESH_ProxyMesh.hxx"
48 #include "SMESH_subMesh.hxx"
49 #include "SMESH_subMeshEventListener.hxx"
50 #include "StdMeshers_FaceSide.hxx"
51 #include "StdMeshers_ProjectionUtils.hxx"
52 #include "StdMeshers_Quadrangle_2D.hxx"
53 #include "StdMeshers_ViscousLayers2D.hxx"
55 #include <Basics_OCCTVersion.hxx>
57 #if OCC_VERSION_LARGE < 0x07070000
58 #include <Adaptor3d_HSurface.hxx>
60 #include <Adaptor3d_Surface.hxx>
63 #include <BRepAdaptor_Curve.hxx>
64 #include <BRepAdaptor_Curve2d.hxx>
65 #include <BRepAdaptor_Surface.hxx>
66 #include <BRepLProp_SLProps.hxx>
67 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
68 #include <BRep_Tool.hxx>
69 #include <Bnd_B2d.hxx>
70 #include <Bnd_B3d.hxx>
72 #include <GCPnts_AbscissaPoint.hxx>
73 #include <GCPnts_TangentialDeflection.hxx>
74 #include <Geom2d_Circle.hxx>
75 #include <Geom2d_Line.hxx>
76 #include <Geom2d_TrimmedCurve.hxx>
77 #include <GeomAdaptor_Curve.hxx>
78 #include <GeomLib.hxx>
79 #include <Geom_Circle.hxx>
80 #include <Geom_Curve.hxx>
81 #include <Geom_Line.hxx>
82 #include <Geom_TrimmedCurve.hxx>
83 #include <Precision.hxx>
84 #include <Standard_ErrorHandler.hxx>
85 #include <Standard_Failure.hxx>
86 #include <TColStd_Array1OfReal.hxx>
88 #include <TopExp_Explorer.hxx>
89 #include <TopTools_IndexedMapOfShape.hxx>
90 #include <TopTools_ListOfShape.hxx>
91 #include <TopTools_MapIteratorOfMapOfShape.hxx>
92 #include <TopTools_MapOfShape.hxx>
94 #include <TopoDS_Edge.hxx>
95 #include <TopoDS_Face.hxx>
96 #include <TopoDS_Vertex.hxx>
98 #include <gp_Cone.hxx>
99 #include <gp_Sphere.hxx>
100 #include <gp_Vec.hxx>
108 #include <unordered_map>
114 //#define __NOT_INVALIDATE_BAD_SMOOTH
115 //#define __NODES_AT_POS
118 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
119 #define BLOCK_INFLATION // of individual _LayerEdge's
120 #define OLD_NEF_POLYGON
124 //================================================================================
129 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
131 const double theMinSmoothCosin = 0.1;
132 const double theSmoothThickToElemSizeRatio = 0.6;
133 const double theMinSmoothTriaAngle = 30;
134 const double theMinSmoothQuadAngle = 45;
136 // what part of thickness is allowed till intersection
137 // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
138 const double theThickToIntersection = 1.5;
140 bool needSmoothing( double cosin, double tgtThick, double elemSize )
142 return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
144 double getSmoothingThickness( double cosin, double elemSize )
146 return theSmoothThickToElemSizeRatio * elemSize / cosin;
150 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
151 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
153 struct _MeshOfSolid : public SMESH_ProxyMesh,
154 public SMESH_subMeshEventListenerData
156 bool _n2nMapComputed;
157 SMESH_ComputeErrorPtr _warning;
159 _MeshOfSolid( SMESH_Mesh* mesh)
160 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
162 SMESH_ProxyMesh::setMesh( *mesh );
165 // returns submesh for a geom face
166 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
168 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
169 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
171 void setNode2Node(const SMDS_MeshNode* srcNode,
172 const SMDS_MeshNode* proxyNode,
173 const SMESH_ProxyMesh::SubMesh* subMesh)
175 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
178 //--------------------------------------------------------------------------------
180 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
181 * It is used to clear an inferior dim sub-meshes modified by viscous layers
183 class _ShrinkShapeListener : SMESH_subMeshEventListener
185 _ShrinkShapeListener()
186 : SMESH_subMeshEventListener(/*isDeletable=*/false,
187 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
189 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
190 virtual void ProcessEvent(const int event,
192 SMESH_subMesh* solidSM,
193 SMESH_subMeshEventListenerData* data,
194 const SMESH_Hypothesis* hyp)
196 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
198 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
202 //--------------------------------------------------------------------------------
204 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
205 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
206 * delete the data as soon as it has been used
208 class _ViscousListener : SMESH_subMeshEventListener
211 SMESH_subMeshEventListener(/*isDeletable=*/false,
212 "StdMeshers_ViscousLayers::_ViscousListener") {}
213 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
215 virtual void ProcessEvent(const int event,
217 SMESH_subMesh* subMesh,
218 SMESH_subMeshEventListenerData* /*data*/,
219 const SMESH_Hypothesis* /*hyp*/)
221 if (( SMESH_subMesh::COMPUTE_EVENT == eventType ) &&
222 ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
223 SMESH_subMesh::SUBMESH_COMPUTED != event ))
225 // delete SMESH_ProxyMesh containing temporary faces
226 subMesh->DeleteEventListener( this );
229 // Finds or creates proxy mesh of the solid
230 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
231 const TopoDS_Shape& solid,
234 if ( !mesh ) return 0;
235 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
236 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
237 if ( !data && toCreate )
239 data = new _MeshOfSolid(mesh);
240 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
241 sm->SetEventListener( Get(), data, sm );
245 // Removes proxy mesh of the solid
246 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
248 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
252 //================================================================================
254 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
255 * the main shape when sub-mesh of the main shape is cleared,
256 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
259 //================================================================================
261 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
263 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
264 SMESH_subMeshEventListenerData* data =
265 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
268 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
269 data->mySubMeshes.end())
270 data->mySubMeshes.push_back( sub );
274 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
275 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
279 //--------------------------------------------------------------------------------
281 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
282 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
283 * The class is used to check validity of face or volumes around a smoothed node;
284 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
288 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
289 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
290 _Simplex(const SMDS_MeshNode* nPrev=0,
291 const SMDS_MeshNode* nNext=0,
292 const SMDS_MeshNode* nOpp=0)
293 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
294 bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
296 const double M[3][3] =
297 {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
298 { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
299 { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
300 vol = ( + M[0][0] * M[1][1] * M[2][2]
301 + M[0][1] * M[1][2] * M[2][0]
302 + M[0][2] * M[1][0] * M[2][1]
303 - M[0][0] * M[1][2] * M[2][1]
304 - M[0][1] * M[1][0] * M[2][2]
305 - M[0][2] * M[1][1] * M[2][0]);
308 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
310 SMESH_TNodeXYZ pSrc( nSrc );
311 return IsForward( &pSrc, &pTgt, vol );
313 bool IsForward(const gp_XY& tgtUV,
314 const SMDS_MeshNode* smoothedNode,
315 const TopoDS_Face& face,
316 SMESH_MesherHelper& helper,
317 const double refSign) const
319 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
320 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
321 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
323 return d*refSign > 1e-100;
325 bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
327 SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
328 if ( !_nOpp ) // triangle
330 gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
331 double tp2 = tp.SquareMagnitude();
332 double pn2 = pn.SquareMagnitude();
333 double nt2 = nt.SquareMagnitude();
335 if ( tp2 < pn2 && tp2 < nt2 )
336 minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
337 else if ( pn2 < nt2 )
338 minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
340 minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
342 static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
343 Cos( theMinSmoothTriaAngle * M_PI / 180. ));
344 return minAngle < theMaxCos2;
348 SMESH_TNodeXYZ pOpp( _nOpp );
349 gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
350 double tp2 = tp.SquareMagnitude();
351 double po2 = po.SquareMagnitude();
352 double on2 = on.SquareMagnitude();
353 double nt2 = nt.SquareMagnitude();
354 minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
355 (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
356 Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
357 (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
359 static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
360 Cos( theMinSmoothQuadAngle * M_PI / 180. ));
361 return minAngle < theMaxCos2;
364 bool IsNeighbour(const _Simplex& other) const
366 return _nPrev == other._nNext || _nNext == other._nPrev;
368 bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
369 static void GetSimplices( const SMDS_MeshNode* node,
370 vector<_Simplex>& simplices,
371 const set<TGeomID>& ingnoreShapes,
372 const _SolidData* dataToCheckOri = 0,
373 const bool toSort = false);
374 static void SortSimplices(vector<_Simplex>& simplices);
376 //--------------------------------------------------------------------------------
378 * Structure used to take into account surface curvature while smoothing
383 double _k; // factor to correct node smoothed position
384 double _h2lenRatio; // avgNormProj / (2*avgDist)
385 gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
387 static _Curvature* New( double avgNormProj, double avgDist );
388 double lenDelta(double len) const { return _k * ( _r + len ); }
389 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
391 //--------------------------------------------------------------------------------
395 struct _EdgesOnShape;
398 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
400 //--------------------------------------------------------------------------------
402 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
403 * and a node of the most internal layer (_nodes.back())
407 typedef gp_XYZ (_LayerEdge::*PSmooFun)();
409 vector< const SMDS_MeshNode*> _nodes;
411 gp_XYZ _normal; // to boundary of solid
412 vector<gp_XYZ> _pos; // points computed during inflation
413 double _len; // length achieved with the last inflation step
414 double _maxLen; // maximal possible length
415 double _cosin; // of angle (_normal ^ surface)
416 double _minAngle; // of _simplices
417 double _lenFactor; // to compute _len taking _cosin into account
420 // simplices connected to the source node (_nodes[0]);
421 // used for smoothing and quality check of _LayerEdge's based on the FACE
422 vector<_Simplex> _simplices;
423 vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
424 PSmooFun _smooFunction; // smoothing function
425 _Curvature* _curvature;
426 // data for smoothing of _LayerEdge's based on the EDGE
427 _2NearEdges* _2neibors;
429 enum EFlags { TO_SMOOTH = 0x0000001,
430 MOVED = 0x0000002, // set by _neibors[i]->SetNewLength()
431 SMOOTHED = 0x0000004, // set by _LayerEdge::Smooth()
432 DIFFICULT = 0x0000008, // near concave VERTEX
433 ON_CONCAVE_FACE = 0x0000010,
434 BLOCKED = 0x0000020, // not to inflate any more
435 INTERSECTED = 0x0000040, // close intersection with a face found
436 NORMAL_UPDATED = 0x0000080,
437 UPD_NORMAL_CONV = 0x0000100, // to update normal on boundary of concave FACE
438 MARKED = 0x0000200, // local usage
439 MULTI_NORMAL = 0x0000400, // a normal is invisible by some of surrounding faces
440 NEAR_BOUNDARY = 0x0000800, // is near FACE boundary forcing smooth
441 SMOOTHED_C1 = 0x0001000, // is on _eosC1
442 DISTORTED = 0x0002000, // was bad before smoothing
443 RISKY_SWOL = 0x0004000, // SWOL is parallel to a source FACE
444 SHRUNK = 0x0008000, // target node reached a tgt position while shrink()
445 UNUSED_FLAG = 0x0100000 // to add user flags after
447 bool Is ( int flag ) const { return _flags & flag; }
448 void Set ( int flag ) { _flags |= flag; }
449 void Unset( int flag ) { _flags &= ~flag; }
450 std::string DumpFlags() const; // debug
452 void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
453 bool SetNewLength2d( Handle(Geom_Surface)& surface,
454 const TopoDS_Face& F,
456 SMESH_MesherHelper& helper );
457 bool UpdatePositionOnSWOL( SMDS_MeshNode* n,
460 SMESH_MesherHelper& helper );
461 void SetDataByNeighbors( const SMDS_MeshNode* n1,
462 const SMDS_MeshNode* n2,
463 const _EdgesOnShape& eos,
464 SMESH_MesherHelper& helper);
465 void Block( _SolidData& data );
466 void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
467 void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
468 const TNode2Edge& n2eMap);
469 void SmoothPos( const vector< double >& segLen, const double tol );
470 int GetSmoothedPos( const double tol );
471 int Smooth(const int step, const bool isConcaveFace, bool findBest);
472 int Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
473 int CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
474 void SmoothWoCheck();
475 bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
476 const TopoDS_Face& F,
477 SMESH_MesherHelper& helper);
478 void MoveNearConcaVer( const _EdgesOnShape* eov,
479 const _EdgesOnShape* eos,
481 vector< _LayerEdge* > & badSmooEdges);
482 bool FindIntersection( SMESH_ElementSearcher& searcher,
484 const double& epsilon,
486 const SMDS_MeshElement** face = 0);
487 bool SegTriaInter( const gp_Ax1& lastSegment,
492 const double& epsilon) const;
493 bool SegTriaInter( const gp_Ax1& lastSegment,
494 const SMDS_MeshNode* n0,
495 const SMDS_MeshNode* n1,
496 const SMDS_MeshNode* n2,
498 const double& epsilon) const
499 { return SegTriaInter( lastSegment,
500 SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
503 const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
504 gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
505 gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
506 gp_XY LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which=-1 ) const;
507 bool IsOnEdge() const { return _2neibors; }
508 bool IsOnFace() const { return ( _nodes[0]->GetPosition()->GetDim() == 2 ); }
509 int BaseShapeDim() const { return _nodes[0]->GetPosition()->GetDim(); }
510 gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
511 double SetCosin( double cosin );
512 void SetNormal( const gp_XYZ& n ) { _normal = n; }
513 void SetMaxLen( double l ) { _maxLen = l; }
514 int NbSteps() const { return _pos.size() - 1; } // nb inlation steps
515 bool IsNeiborOnEdge( const _LayerEdge* edge ) const;
516 void SetSmooLen( double len ) { // set _len at which smoothing is needed
517 _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
519 double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
521 gp_XYZ smoothLaplacian();
522 gp_XYZ smoothAngular();
523 gp_XYZ smoothLengthWeighted();
524 gp_XYZ smoothCentroidal();
525 gp_XYZ smoothNefPolygon();
527 enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
528 static const int theNbSmooFuns = FUN_NB;
529 static PSmooFun _funs[theNbSmooFuns];
530 static const char* _funNames[theNbSmooFuns+1];
531 int smooFunID( PSmooFun fun=0) const;
533 _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
534 &_LayerEdge::smoothLengthWeighted,
535 &_LayerEdge::smoothCentroidal,
536 &_LayerEdge::smoothNefPolygon,
537 &_LayerEdge::smoothAngular };
538 const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
546 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
548 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
549 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
552 //--------------------------------------------------------------------------------
554 * A 2D half plane used by _LayerEdge::smoothNefPolygon()
558 gp_XY _pos, _dir, _inNorm;
559 bool IsOut( const gp_XY p, const double tol ) const
561 return _inNorm * ( p - _pos ) < -tol;
563 bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
565 //const double eps = 1e-10;
566 double D = _dir.Crossed( hp._dir );
567 if ( fabs(D) < std::numeric_limits<double>::min())
569 gp_XY vec21 = _pos - hp._pos;
570 double u = hp._dir.Crossed( vec21 ) / D;
571 intPnt = _pos + _dir * u;
575 //--------------------------------------------------------------------------------
577 * Structure used to smooth a _LayerEdge based on an EDGE.
581 double _wgt [2]; // weights of _nodes
582 _LayerEdge* _edges[2];
584 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
587 _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
588 ~_2NearEdges(){ delete _plnNorm; }
589 const SMDS_MeshNode* tgtNode(bool is2nd) {
590 return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
592 const SMDS_MeshNode* srcNode(bool is2nd) {
593 return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
596 std::swap( _wgt [0], _wgt [1] );
597 std::swap( _edges[0], _edges[1] );
599 void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
600 _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
602 bool include( const _LayerEdge* e ) {
603 return ( _edges[0] == e || _edges[1] == e );
608 //--------------------------------------------------------------------------------
610 * \brief Layers parameters got by averaging several hypotheses
614 AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
615 :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
619 void Add( const StdMeshers_ViscousLayers* hyp )
624 _nbLayers = hyp->GetNumberLayers();
625 //_thickness += hyp->GetTotalThickness();
626 _thickness = Max( _thickness, hyp->GetTotalThickness() );
627 _stretchFactor += hyp->GetStretchFactor();
628 _method = hyp->GetMethod();
629 if ( _groupName.empty() )
630 _groupName = hyp->GetGroupName();
633 double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
634 double GetStretchFactor() const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
635 int GetNumberLayers() const { return _nbLayers; }
636 int GetMethod() const { return _method; }
637 bool ToCreateGroup() const { return !_groupName.empty(); }
638 const std::string& GetGroupName() const { return _groupName; }
640 double Get1stLayerThickness( double realThickness = 0.) const
642 const double T = ( realThickness > 0 ) ? realThickness : GetTotalThickness();
643 const double f = GetStretchFactor();
644 const int N = GetNumberLayers();
645 return StdMeshers_ViscousLayers::Get1stLayerThickness( T, f, N );
648 bool UseSurfaceNormal() const
649 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
650 bool ToSmooth() const
651 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
652 bool IsOffsetMethod() const
653 { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
655 bool operator==( const AverageHyp& other ) const
657 return ( _nbLayers == other._nbLayers &&
658 _method == other._method &&
659 Equals( GetTotalThickness(), other.GetTotalThickness() ) &&
660 Equals( GetStretchFactor(), other.GetStretchFactor() ));
662 static bool Equals( double v1, double v2 ) { return Abs( v1 - v2 ) < 0.01 * ( v1 + v2 ); }
665 int _nbLayers, _nbHyps, _method;
666 double _thickness, _stretchFactor;
667 std::string _groupName;
670 //--------------------------------------------------------------------------------
672 * \brief _LayerEdge's on a shape and other shape data
676 vector< _LayerEdge* > _edges;
680 SMESH_subMesh * _subMesh;
681 // face or edge w/o layer along or near which _edges are inflated
683 bool _isRegularSWOL; // w/o singularities
684 // averaged StdMeshers_ViscousLayers parameters
687 _Smoother1D* _edgeSmoother;
688 vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
689 vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
691 typedef std::unordered_map< const SMDS_MeshElement*, gp_XYZ > TFace2NormMap;
692 TFace2NormMap _faceNormals; // if _shape is FACE
693 vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
695 Handle(ShapeAnalysis_Surface) _offsetSurf;
696 _LayerEdge* _edgeForOffset;
698 _Mapper2D* _mapper2D;
700 _SolidData* _data; // parent SOLID
702 _LayerEdge* operator[](size_t i) const { return (_LayerEdge*) _edges[i]; }
703 size_t size() const { return _edges.size(); }
704 TopAbs_ShapeEnum ShapeType() const
705 { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
706 TopAbs_ShapeEnum SWOLType() const
707 { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
708 bool HasC1( const _EdgesOnShape* other ) const
709 { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
710 bool GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
711 _SolidData& GetData() const { return *_data; }
712 char ShapeTypeLetter() const
713 { switch ( ShapeType() ) { case TopAbs_FACE: return 'F'; case TopAbs_EDGE: return 'E';
714 case TopAbs_VERTEX: return 'V'; default: return 'S'; }}
716 _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0), _mapper2D(0) {}
720 //--------------------------------------------------------------------------------
722 * \brief Convex FACE whose radius of curvature is less than the thickness of
723 * layers. It is used to detect distortion of prisms based on a convex
724 * FACE and to update normals to enable further increasing the thickness
730 // edges whose _simplices are used to detect prism distortion
731 vector< _LayerEdge* > _simplexTestEdges;
733 // map a sub-shape to _SolidData::_edgesOnShape
734 map< TGeomID, _EdgesOnShape* > _subIdToEOS;
738 bool _normalsFixedOnBorders; // used in putOnOffsetSurface()
740 double GetMaxCurvature( _SolidData& data,
742 BRepLProp_SLProps& surfProp,
743 SMESH_MesherHelper& helper);
745 bool GetCenterOfCurvature( _LayerEdge* ledge,
746 BRepLProp_SLProps& surfProp,
747 SMESH_MesherHelper& helper,
748 gp_Pnt & center ) const;
749 bool CheckPrisms() const;
752 //--------------------------------------------------------------------------------
754 * \brief Structure holding _LayerEdge's based on EDGEs that will collide
755 * at inflation up to the full thickness. A detected collision
756 * is fixed in updateNormals()
758 struct _CollisionEdges
761 vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
762 const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
763 const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
766 //--------------------------------------------------------------------------------
768 * \brief Data of a SOLID
772 typedef const StdMeshers_ViscousLayers* THyp;
774 TopTools_MapOfShape _before; // SOLIDs to be computed before _solid
775 TGeomID _index; // SOLID id
776 _MeshOfSolid* _proxyMesh;
779 list< TopoDS_Shape > _hypShapes;
780 map< TGeomID, THyp > _face2hyp; // filled if _hyps.size() > 1
781 set< TGeomID > _reversedFaceIds;
782 set< TGeomID > _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
784 double _stepSize, _stepSizeCoeff, _geomSize;
785 const SMDS_MeshNode* _stepSizeNodes[2];
787 TNode2Edge _n2eMap; // nodes and _LayerEdge's based on them
789 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
790 map< TGeomID, TNode2Edge* > _s2neMap;
791 // _LayerEdge's with underlying shapes
792 vector< _EdgesOnShape > _edgesOnShape;
794 // key: an ID of shape (EDGE or VERTEX) shared by a FACE with
795 // layers and a FACE w/o layers
796 // value: the shape (FACE or EDGE) to shrink mesh on.
797 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
798 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
800 // Convex FACEs whose radius of curvature is less than the thickness of layers
801 map< TGeomID, _ConvexFace > _convexFaces;
803 // shapes (EDGEs and VERTEXes) shrink from which is forbidden due to collisions with
804 // the adjacent SOLID
805 set< TGeomID > _noShrinkShapes;
807 int _nbShapesToSmooth;
809 vector< _CollisionEdges > _collisionEdges;
810 set< TGeomID > _concaveFaces;
812 double _maxThickness; // of all _hyps
813 double _minThickness; // of all _hyps
815 double _epsilon; // precision for SegTriaInter()
817 SMESH_MesherHelper* _helper;
819 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
821 :_solid(s), _proxyMesh(m), _done(false),_helper(0) {}
822 ~_SolidData() { delete _helper; _helper = 0; }
824 void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
825 void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
827 _ConvexFace* GetConvexFace( const TGeomID faceID ) {
828 map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
829 return id2face == _convexFaces.end() ? 0 : & id2face->second;
831 _EdgesOnShape* GetShapeEdges(const TGeomID shapeID );
832 _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
833 _EdgesOnShape* GetShapeEdges(const _LayerEdge* edge )
834 { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
836 SMESH_MesherHelper& GetHelper() const { return *_helper; }
838 void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
839 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
840 for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
841 _edgesOnShape[i]._edges[j]->Unset( flag );
843 void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
844 const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
846 void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
848 //--------------------------------------------------------------------------------
850 * \brief Offset plane used in getNormalByOffset()
856 int _faceIndexNext[2];
857 gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
860 _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
862 void ComputeIntersectionLine( _OffsetPlane& pln,
863 const TopoDS_Edge& E,
864 const TopoDS_Vertex& V );
865 gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
866 int NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
868 //--------------------------------------------------------------------------------
870 * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
872 struct _CentralCurveOnEdge
875 vector< gp_Pnt > _curvaCenters;
876 vector< _LayerEdge* > _ledges;
877 vector< gp_XYZ > _normals; // new normal for each of _ledges
878 vector< double > _segLength2;
881 TopoDS_Face _adjFace;
882 bool _adjFaceToSmooth;
884 void Append( const gp_Pnt& center, _LayerEdge* ledge )
886 if ( ledge->Is( _LayerEdge::MULTI_NORMAL ))
888 if ( _curvaCenters.size() > 0 )
889 _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
890 _curvaCenters.push_back( center );
891 _ledges.push_back( ledge );
892 _normals.push_back( ledge->_normal );
894 bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
895 void SetShapes( const TopoDS_Edge& edge,
896 const _ConvexFace& convFace,
898 SMESH_MesherHelper& helper);
900 //--------------------------------------------------------------------------------
902 * \brief Data of node on a shrinked FACE
906 const SMDS_MeshNode* _node;
907 vector<_Simplex> _simplices; // for quality check
909 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
911 bool Smooth(int& badNb,
912 Handle(Geom_Surface)& surface,
913 SMESH_MesherHelper& helper,
914 const double refSign,
918 gp_XY computeAngularPos(vector<gp_XY>& uv,
919 const gp_XY& uvToFix,
920 const double refSign );
924 //--------------------------------------------------------------------------------
926 * \brief Builder of viscous layers
928 class _ViscousBuilder
933 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
934 const TopoDS_Shape& shape);
935 // check validity of hypotheses
936 SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh& mesh,
937 const TopoDS_Shape& shape );
939 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
940 void RestoreListeners();
942 // computes SMESH_ProxyMesh::SubMesh::_n2n;
943 bool MakeN2NMap( _MeshOfSolid* pm );
947 bool findSolidsWithLayers(const bool checkFaceMesh=true);
948 bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
949 bool findFacesWithLayers(const bool onlyWith=false);
950 void findPeriodicFaces();
951 void getIgnoreFaces(const TopoDS_Shape& solid,
952 const StdMeshers_ViscousLayers* hyp,
953 const TopoDS_Shape& hypShape,
954 set<TGeomID>& ignoreFaces);
955 int makeEdgesOnShape();
956 bool makeLayer(_SolidData& data);
957 void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
958 bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
959 SMESH_MesherHelper& helper, _SolidData& data);
960 gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
961 const TopoDS_Face& face,
962 SMESH_MesherHelper& helper,
964 bool shiftInside=false);
965 bool getFaceNormalAtSingularity(const gp_XY& uv,
966 const TopoDS_Face& face,
967 SMESH_MesherHelper& helper,
969 gp_XYZ getWeigthedNormal( const _LayerEdge* edge );
970 gp_XYZ getNormalByOffset( _LayerEdge* edge,
971 std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
973 bool lastNoOffset = false);
974 bool findNeiborsOnEdge(const _LayerEdge* edge,
975 const SMDS_MeshNode*& n1,
976 const SMDS_MeshNode*& n2,
979 void findSimplexTestEdges( _SolidData& data,
980 vector< vector<_LayerEdge*> >& edgesByGeom);
981 void computeGeomSize( _SolidData& data );
982 bool findShapesToSmooth( _SolidData& data);
983 void limitStepSizeByCurvature( _SolidData& data );
984 void limitStepSize( _SolidData& data,
985 const SMDS_MeshElement* face,
986 const _LayerEdge* maxCosinEdge );
987 void limitStepSize( _SolidData& data, const double minSize);
988 bool inflate(_SolidData& data);
989 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
990 int invalidateBadSmooth( _SolidData& data,
991 SMESH_MesherHelper& helper,
992 vector< _LayerEdge* >& badSmooEdges,
993 vector< _EdgesOnShape* >& eosC1,
995 void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
996 void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
997 vector< _EdgesOnShape* >& eosC1,
998 int smooStep=0, int moveAll=false );
999 void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
1000 void findEdgesToUpdateNormalNearConvexFace( _ConvexFace & convFace,
1002 SMESH_MesherHelper& helper );
1003 void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
1004 void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
1005 _EdgesOnShape& eos1, _EdgesOnShape& eos2,
1006 const bool isSmoothable );
1007 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
1008 bool updateNormalsOfConvexFaces( _SolidData& data,
1009 SMESH_MesherHelper& helper,
1011 void updateNormalsOfC1Vertices( _SolidData& data );
1012 bool updateNormalsOfSmoothed( _SolidData& data,
1013 SMESH_MesherHelper& helper,
1015 const double stepSize );
1016 bool isNewNormalOk( _SolidData& data,
1018 const gp_XYZ& newNormal);
1019 bool refine(_SolidData& data);
1020 bool shrink(_SolidData& data);
1021 bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
1022 SMESH_MesherHelper& helper,
1023 const SMESHDS_SubMesh* faceSubMesh );
1024 void restoreNoShrink( _LayerEdge& edge ) const;
1025 void fixBadFaces(const TopoDS_Face& F,
1026 SMESH_MesherHelper& helper,
1029 set<const SMDS_MeshNode*> * involvedNodes=NULL);
1030 bool addBoundaryElements(_SolidData& data);
1032 bool error( const string& text, int solidID=-1 );
1033 SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
1036 void makeGroupOfLE();
1039 SMESH_ComputeErrorPtr _error;
1041 vector< _SolidData > _sdVec;
1042 TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
1043 TopTools_MapOfShape _shrunkFaces;
1044 std::unique_ptr<Periodicity> _periodicity;
1049 //--------------------------------------------------------------------------------
1051 * \brief Shrinker of nodes on the EDGE
1055 TopoDS_Edge _geomEdge;
1056 vector<double> _initU;
1057 vector<double> _normPar;
1058 vector<const SMDS_MeshNode*> _nodes;
1059 const _LayerEdge* _edges[2];
1062 void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1063 void Compute(bool set3D, SMESH_MesherHelper& helper);
1064 void RestoreParams();
1065 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1066 const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1067 const SMDS_MeshNode* TgtNode( bool is2nd ) const
1068 { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1069 const SMDS_MeshNode* SrcNode( bool is2nd ) const
1070 { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1072 //--------------------------------------------------------------------------------
1074 * \brief Smoother of _LayerEdge's on EDGE.
1078 struct OffPnt // point of the offsetted EDGE
1080 gp_XYZ _xyz; // coord of a point inflated from EDGE w/o smooth
1081 double _len; // length reached at previous inflation step
1082 double _param; // on EDGE
1083 _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1084 gp_XYZ _edgeDir;// EDGE tangent at _param
1085 double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1087 vector< OffPnt > _offPoints;
1088 vector< double > _leParams; // normalized param of _eos._edges on EDGE
1089 Handle(Geom_Curve) _anaCurve; // for analytic smooth
1090 _LayerEdge _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1091 gp_XYZ _edgeDir[2]; // tangent at VERTEXes
1092 size_t _iSeg[2]; // index of segment where extreme tgt node is projected
1093 _EdgesOnShape& _eos;
1094 double _curveLen; // length of the EDGE
1095 std::pair<int,int> _eToSmooth[2]; // <from,to> indices of _LayerEdge's in _eos
1097 static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
1099 SMESH_MesherHelper& helper);
1101 _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1102 _EdgesOnShape& eos )
1103 : _anaCurve( curveForSmooth ), _eos( eos )
1106 bool Perform(_SolidData& data,
1107 Handle(ShapeAnalysis_Surface)& surface,
1108 const TopoDS_Face& F,
1109 SMESH_MesherHelper& helper );
1111 void prepare(_SolidData& data );
1113 void findEdgesToSmooth();
1115 bool isToSmooth( int iE );
1117 bool smoothAnalyticEdge( _SolidData& data,
1118 Handle(ShapeAnalysis_Surface)& surface,
1119 const TopoDS_Face& F,
1120 SMESH_MesherHelper& helper);
1121 bool smoothComplexEdge( _SolidData& data,
1122 Handle(ShapeAnalysis_Surface)& surface,
1123 const TopoDS_Face& F,
1124 SMESH_MesherHelper& helper);
1125 gp_XYZ getNormalNormal( const gp_XYZ & normal,
1126 const gp_XYZ& edgeDir);
1127 _LayerEdge* getLEdgeOnV( bool is2nd )
1129 return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1131 bool isAnalytic() const { return !_anaCurve.IsNull(); }
1133 void offPointsToPython() const; // debug
1136 //--------------------------------------------------------------------------------
1138 * \brief Compute positions of nodes of 2D structured mesh using TFI
1142 FaceQuadStruct _quadPoints;
1144 UVPtStruct& uvPnt( size_t i, size_t j ) { return _quadPoints.UVPt( i, j ); }
1147 _Mapper2D( const TParam2ColumnMap & param2ColumnMap, const TNode2Edge& n2eMap );
1148 bool ComputeNodePositions();
1151 //--------------------------------------------------------------------------------
1153 * \brief Class of temporary mesh face.
1154 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1155 * needed because SMESH_ElementSearcher internally uses set of elements sorted by ID
1157 struct _TmpMeshFace : public SMDS_PolygonalFaceOfNodes
1159 const SMDS_MeshElement* _srcFace;
1161 _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1164 const SMDS_MeshElement* srcFace=0 ):
1165 SMDS_PolygonalFaceOfNodes(nodes), _srcFace( srcFace ) { setID( ID ); setShapeID( faceID ); }
1166 virtual SMDSAbs_EntityType GetEntityType() const
1167 { return _srcFace ? _srcFace->GetEntityType() : SMDSEntity_Quadrangle; }
1168 virtual SMDSAbs_GeometryType GetGeomType() const
1169 { return _srcFace ? _srcFace->GetGeomType() : SMDSGeom_QUADRANGLE; }
1171 //--------------------------------------------------------------------------------
1173 * \brief Class of temporary mesh quadrangle face storing _LayerEdge it's based on
1175 struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1177 _LayerEdge *_le1, *_le2;
1178 _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1179 _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1181 myNodes[0]=_le1->_nodes[0];
1182 myNodes[1]=_le1->_nodes.back();
1183 myNodes[2]=_le2->_nodes.back();
1184 myNodes[3]=_le2->_nodes[0];
1186 const SMDS_MeshNode* n( size_t i ) const
1188 return myNodes[ i ];
1190 gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1192 SMESH_TNodeXYZ p0s( myNodes[0] );
1193 SMESH_TNodeXYZ p0t( myNodes[1] );
1194 SMESH_TNodeXYZ p1t( myNodes[2] );
1195 SMESH_TNodeXYZ p1s( myNodes[3] );
1196 gp_XYZ v0 = p0t - p0s;
1197 gp_XYZ v1 = p1t - p1s;
1198 gp_XYZ v01 = p1s - p0s;
1199 gp_XYZ n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1204 gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1206 myNodes[0]=le1->_nodes[0];
1207 myNodes[1]=le1->_nodes.back();
1208 myNodes[2]=le2->_nodes.back();
1209 myNodes[3]=le2->_nodes[0];
1213 //--------------------------------------------------------------------------------
1215 * \brief Retriever of node coordinates either directly or from a surface by node UV.
1216 * \warning Location of a surface is ignored
1218 struct _NodeCoordHelper
1220 SMESH_MesherHelper& _helper;
1221 const TopoDS_Face& _face;
1222 Handle(Geom_Surface) _surface;
1223 gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1225 _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1226 : _helper( helper ), _face( F )
1230 TopLoc_Location loc;
1231 _surface = BRep_Tool::Surface( _face, loc );
1233 if ( _surface.IsNull() )
1234 _fun = & _NodeCoordHelper::direct;
1236 _fun = & _NodeCoordHelper::byUV;
1238 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1241 gp_XYZ direct(const SMDS_MeshNode* n) const
1243 return SMESH_TNodeXYZ( n );
1245 gp_XYZ byUV (const SMDS_MeshNode* n) const
1247 gp_XY uv = _helper.GetNodeUV( _face, n );
1248 return _surface->Value( uv.X(), uv.Y() ).XYZ();
1252 //================================================================================
1254 * \brief Check angle between vectors
1256 //================================================================================
1258 inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1260 double dot = v1 * v2; // cos * |v1| * |v2|
1261 double l1 = v1.SquareMagnitude();
1262 double l2 = v2.SquareMagnitude();
1263 return (( dot * cos >= 0 ) &&
1264 ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1269 ObjectPool< _LayerEdge > _edgePool;
1270 ObjectPool< _Curvature > _curvaturePool;
1271 ObjectPool< _2NearEdges > _nearEdgesPool;
1273 static _Factory* & me()
1275 static _Factory* theFactory = 0;
1280 _Factory() { me() = this; }
1281 ~_Factory() { me() = 0; }
1283 static _LayerEdge* NewLayerEdge() { return me()->_edgePool.getNew(); }
1284 static _Curvature * NewCurvature() { return me()->_curvaturePool.getNew(); }
1285 static _2NearEdges* NewNearEdges() { return me()->_nearEdgesPool.getNew(); }
1288 } // namespace VISCOUS_3D
1292 //================================================================================
1293 // StdMeshers_ViscousLayers hypothesis
1295 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, SMESH_Gen* gen)
1296 :SMESH_Hypothesis(hypId, gen),
1297 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1298 _method( SURF_OFFSET_SMOOTH ),
1301 _name = StdMeshers_ViscousLayers::GetHypType();
1302 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1303 } // --------------------------------------------------------------------------------
1304 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1306 if ( faceIds != _shapeIds )
1307 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1308 if ( _isToIgnoreShapes != toIgnore )
1309 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1310 } // --------------------------------------------------------------------------------
1311 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1313 if ( thickness != _thickness )
1314 _thickness = thickness, NotifySubMeshesHypothesisModification();
1315 } // --------------------------------------------------------------------------------
1316 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1318 if ( _nbLayers != nb )
1319 _nbLayers = nb, NotifySubMeshesHypothesisModification();
1320 } // --------------------------------------------------------------------------------
1321 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1323 if ( _stretchFactor != factor )
1324 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1325 } // --------------------------------------------------------------------------------
1326 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1328 if ( _method != method )
1329 _method = method, NotifySubMeshesHypothesisModification();
1330 } // --------------------------------------------------------------------------------
1331 void StdMeshers_ViscousLayers::SetGroupName(const std::string& name)
1333 if ( _groupName != name )
1336 if ( !_groupName.empty() )
1337 NotifySubMeshesHypothesisModification();
1339 } // --------------------------------------------------------------------------------
1340 SMESH_ProxyMesh::Ptr
1341 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
1342 const TopoDS_Shape& theShape,
1343 const bool toMakeN2NMap) const
1345 using namespace VISCOUS_3D;
1346 _ViscousBuilder builder;
1347 SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1348 if ( err && !err->IsOK() )
1349 return SMESH_ProxyMesh::Ptr();
1351 vector<SMESH_ProxyMesh::Ptr> components;
1352 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1353 for ( ; exp.More(); exp.Next() )
1355 if ( _MeshOfSolid* pm =
1356 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1358 if ( toMakeN2NMap && !pm->_n2nMapComputed )
1359 if ( !builder.MakeN2NMap( pm ))
1360 return SMESH_ProxyMesh::Ptr();
1361 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1362 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1364 if ( pm->_warning && !pm->_warning->IsOK() )
1366 SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1367 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1368 if ( !smError || smError->IsOK() )
1369 smError = pm->_warning;
1372 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1374 switch ( components.size() )
1378 case 1: return components[0];
1380 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1382 return SMESH_ProxyMesh::Ptr();
1383 } // --------------------------------------------------------------------------------
1384 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1386 save << " " << _nbLayers
1387 << " " << _thickness
1388 << " " << _stretchFactor
1389 << " " << _shapeIds.size();
1390 for ( size_t i = 0; i < _shapeIds.size(); ++i )
1391 save << " " << _shapeIds[i];
1392 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1393 save << " " << _method;
1394 save << " " << _groupName.size();
1395 if ( !_groupName.empty() )
1396 save << " " << _groupName;
1398 } // --------------------------------------------------------------------------------
1399 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1401 int nbFaces, faceID, shapeToTreat, method;
1402 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1403 while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1404 _shapeIds.push_back( faceID );
1405 if ( load >> shapeToTreat ) {
1406 _isToIgnoreShapes = !shapeToTreat;
1407 if ( load >> method )
1408 _method = (ExtrusionMethod) method;
1410 if ( load >> nameSize && nameSize > 0 )
1412 _groupName.resize( nameSize );
1413 load.get( _groupName[0] ); // remove a white-space
1414 load.getline( &_groupName[0], nameSize + 1 );
1418 _isToIgnoreShapes = true; // old behavior
1421 } // --------------------------------------------------------------------------------
1422 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* /*theMesh*/,
1423 const TopoDS_Shape& /*theShape*/)
1427 } // --------------------------------------------------------------------------------
1428 SMESH_ComputeErrorPtr
1429 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh& theMesh,
1430 const TopoDS_Shape& theShape,
1431 SMESH_Hypothesis::Hypothesis_Status& theStatus)
1433 VISCOUS_3D::_ViscousBuilder builder;
1434 SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1435 if ( err && !err->IsOK() )
1436 theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1438 theStatus = SMESH_Hypothesis::HYP_OK;
1442 // --------------------------------------------------------------------------------
1443 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1446 ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1447 return IsToIgnoreShapes() ? !isIn : isIn;
1449 // --------------------------------------------------------------------------------
1450 double StdMeshers_ViscousLayers::Get1stLayerThickness( double T, double f, int N )
1452 const double fPowN = pow( f, N );
1454 if ( fPowN - 1 <= numeric_limits<double>::min() )
1457 h0 = T * ( f - 1 )/( fPowN - 1 );
1460 // --------------------------------------------------------------------------------
1461 SMDS_MeshGroup* StdMeshers_ViscousLayers::CreateGroup( const std::string& theName,
1462 SMESH_Mesh& theMesh,
1463 SMDSAbs_ElementType theType)
1465 SMESH_Group* group = 0;
1466 SMDS_MeshGroup* groupDS = 0;
1468 if ( theName.empty() )
1471 if ( SMESH_Mesh::GroupIteratorPtr grIt = theMesh.GetGroups() )
1472 while( grIt->more() && !group )
1474 group = grIt->next();
1476 group->GetGroupDS()->GetType() != theType ||
1477 group->GetName() != theName ||
1478 !dynamic_cast< SMESHDS_Group* >( group->GetGroupDS() ))
1482 group = theMesh.AddGroup( theType, theName.c_str() );
1484 groupDS = & dynamic_cast< SMESHDS_Group* >( group->GetGroupDS() )->SMDSGroup();
1489 // END StdMeshers_ViscousLayers hypothesis
1490 //================================================================================
1492 namespace VISCOUS_3D
1494 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV,
1495 const double h0, bool* isRegularEdge = nullptr )
1499 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1500 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1501 gp_Pnt p = BRep_Tool::Pnt( fromV );
1502 gp_Pnt pf = c->Value( f ), pl = c->Value( l );
1503 double distF = p.SquareDistance( pf );
1504 double distL = p.SquareDistance( pl );
1505 c->D1(( distF < distL ? f : l), p, dir );
1506 if ( distL < distF ) dir.Reverse();
1507 bool isDifficult = false;
1508 if ( dir.SquareMagnitude() < h0 * h0 ) // check dir orientation
1510 gp_Pnt& pClose = distF < distL ? pf : pl;
1511 gp_Pnt& pFar = distF < distL ? pl : pf;
1512 gp_Pnt pMid = 0.9 * pClose.XYZ() + 0.1 * pFar.XYZ();
1513 gp_Vec vMid( p, pMid );
1514 double dot = vMid * dir;
1515 double cos2 = dot * dot / dir.SquareMagnitude() / vMid.SquareMagnitude();
1516 if ( cos2 < 0.7 * 0.7 || dot < 0 ) // large angle between dir and vMid
1518 double uClose = distF < distL ? f : l;
1519 double uFar = distF < distL ? l : f;
1520 double r = h0 / SMESH_Algo::EdgeLength( E );
1521 double uMid = ( 1 - r ) * uClose + r * uFar;
1522 pMid = c->Value( uMid );
1523 dir = gp_Vec( p, pMid );
1527 if ( isRegularEdge )
1528 *isRegularEdge = !isDifficult;
1532 //--------------------------------------------------------------------------------
1533 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1534 SMESH_MesherHelper& helper)
1537 double f,l; gp_Pnt p;
1538 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1539 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1540 double u = helper.GetNodeU( E, atNode );
1544 //--------------------------------------------------------------------------------
1545 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1546 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok/*,
1548 //--------------------------------------------------------------------------------
1549 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1550 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1553 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1556 TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1557 return getFaceDir( F, v, node, helper, ok );
1559 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1560 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1561 gp_Pnt p; gp_Vec du, dv, norm;
1562 surface->D1( uv.X(),uv.Y(), p, du,dv );
1565 double u = helper.GetNodeU( fromE, node, 0, &ok );
1567 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1568 if ( o == TopAbs_REVERSED )
1571 gp_Vec dir = norm ^ du;
1573 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1574 helper.IsClosedEdge( fromE ))
1576 if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1577 else c->D1( f, p, dv );
1578 if ( o == TopAbs_REVERSED )
1580 gp_Vec dir2 = norm ^ dv;
1581 dir = dir.Normalized() + dir2.Normalized();
1585 //--------------------------------------------------------------------------------
1586 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1587 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1588 bool& ok/*, double* cosin*/)
1590 TopoDS_Face faceFrw = F;
1591 faceFrw.Orientation( TopAbs_FORWARD );
1592 //double f,l; TopLoc_Location loc;
1593 TopoDS_Edge edges[2]; // sharing a vertex
1596 TopoDS_Vertex VV[2];
1597 TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1598 for ( ; exp.More() && nbEdges < 2; exp.Next() )
1600 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1601 if ( SMESH_Algo::isDegenerated( e )) continue;
1602 TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1603 if ( VV[1].IsSame( fromV )) {
1604 nbEdges += edges[ 0 ].IsNull();
1607 else if ( VV[0].IsSame( fromV )) {
1608 nbEdges += edges[ 1 ].IsNull();
1613 gp_XYZ dir(0,0,0), edgeDir[2];
1616 // get dirs of edges going fromV
1618 for ( size_t i = 0; i < nbEdges && ok; ++i )
1620 edgeDir[i] = getEdgeDir( edges[i], fromV, 0.1 * SMESH_Algo::EdgeLength( edges[i] ));
1621 double size2 = edgeDir[i].SquareModulus();
1622 if (( ok = size2 > numeric_limits<double>::min() ))
1623 edgeDir[i] /= sqrt( size2 );
1625 if ( !ok ) return dir;
1627 // get angle between the 2 edges
1629 double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1630 if ( Abs( angle ) < 5 * M_PI/180 )
1632 dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1636 dir = edgeDir[0] + edgeDir[1];
1641 // double angle = faceNormal.Angle( dir );
1642 // *cosin = Cos( angle );
1645 else if ( nbEdges == 1 )
1647 dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1648 //if ( cosin ) *cosin = 1.;
1658 //================================================================================
1660 * \brief Finds concave VERTEXes of a FACE
1662 //================================================================================
1664 bool getConcaveVertices( const TopoDS_Face& F,
1665 SMESH_MesherHelper& helper,
1666 set< TGeomID >* vertices = 0)
1668 // check angles at VERTEXes
1670 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1671 for ( size_t iW = 0; iW < wires.size(); ++iW )
1673 const int nbEdges = wires[iW]->NbEdges();
1674 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1676 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1678 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1679 int iE2 = ( iE1 + 1 ) % nbEdges;
1680 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1681 iE2 = ( iE2 + 1 ) % nbEdges;
1682 TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1683 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1684 wires[iW]->Edge( iE2 ), F, V );
1685 if ( angle < -5. * M_PI / 180. )
1689 vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1693 return vertices ? !vertices->empty() : false;
1696 //================================================================================
1698 * \brief Returns true if a FACE is bound by a concave EDGE
1700 //================================================================================
1702 bool isConcave( const TopoDS_Face& F,
1703 SMESH_MesherHelper& helper,
1704 set< TGeomID >* vertices = 0 )
1706 bool isConcv = false;
1707 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1709 gp_Vec2d drv1, drv2;
1711 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1712 for ( ; eExp.More(); eExp.Next() )
1714 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1715 if ( SMESH_Algo::isDegenerated( E )) continue;
1716 // check if 2D curve is concave
1717 BRepAdaptor_Curve2d curve( E, F );
1718 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1719 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1720 curve.Intervals( intervals, GeomAbs_C2 );
1721 bool isConvex = true;
1722 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1724 double u1 = intervals( i );
1725 double u2 = intervals( i+1 );
1726 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1727 double cross = drv1 ^ drv2;
1728 if ( E.Orientation() == TopAbs_REVERSED )
1730 isConvex = ( cross > -1e-9 ); // 0.1 );
1734 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1743 // check angles at VERTEXes
1744 if ( getConcaveVertices( F, helper, vertices ))
1750 //================================================================================
1752 * \brief Computes minimal distance of face in-FACE nodes from an EDGE
1753 * \param [in] face - the mesh face to treat
1754 * \param [in] nodeOnEdge - a node on the EDGE
1755 * \param [out] faceSize - the computed distance
1756 * \return bool - true if faceSize computed
1758 //================================================================================
1760 bool getDistFromEdge( const SMDS_MeshElement* face,
1761 const SMDS_MeshNode* nodeOnEdge,
1764 faceSize = Precision::Infinite();
1767 int nbN = face->NbCornerNodes();
1768 int iOnE = face->GetNodeIndex( nodeOnEdge );
1769 int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1770 SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1771 const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1772 face->GetNode( iNext[1] ) };
1773 gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1774 double segLen = -1.;
1775 // look for two neighbor not in-FACE nodes of face
1776 for ( int i = 0; i < 2; ++i )
1778 if (( nNext[i]->GetPosition()->GetDim() != 2 ) &&
1779 ( nodeOnEdge->GetPosition()->GetDim() == 0 || nNext[i]->GetID() < nodeOnEdge->GetID() ))
1781 // look for an in-FACE node
1782 for ( int iN = 0; iN < nbN; ++iN )
1784 if ( iN == iOnE || iN == iNext[i] )
1786 SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1787 gp_XYZ v = pInFace - segEnd;
1790 segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1791 segLen = segVec.Modulus();
1793 double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1794 faceSize = Min( faceSize, distToSeg );
1802 //================================================================================
1804 * \brief Return direction of axis or revolution of a surface
1806 //================================================================================
1808 bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1811 switch ( surface.GetType() ) {
1814 gp_Cone cone = surface.Cone();
1815 axis = cone.Axis().Direction();
1818 case GeomAbs_Sphere:
1820 gp_Sphere sphere = surface.Sphere();
1821 axis = sphere.Position().Direction();
1824 case GeomAbs_SurfaceOfRevolution:
1826 axis = surface.AxeOfRevolution().Direction();
1829 //case GeomAbs_SurfaceOfExtrusion:
1830 case GeomAbs_OffsetSurface:
1832 #if OCC_VERSION_LARGE < 0x07070000
1833 Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1834 return getRovolutionAxis( base->Surface(), axis );
1836 Handle(Adaptor3d_Surface) base = surface.BasisSurface();
1837 return getRovolutionAxis( *base, axis );
1840 default: return false;
1845 //--------------------------------------------------------------------------------
1846 // DEBUG. Dump intermediate node positions into a python script
1847 // HOWTO use: run python commands written in a console and defined in /tmp/viscous.py
1848 // to see construction steps of viscous layers
1854 PyDump(SMESH_Mesh& m) {
1855 int tag = 3 + m.GetId();
1856 const char* fname = "/tmp/viscous.py";
1857 cout << "exec(open('"<<fname<<"','rb').read() )"<<endl;
1858 py = _pyStream = new ofstream(fname);
1859 *py << "import SMESH" << endl
1860 << "from salome.smesh import smeshBuilder" << endl
1861 << "smesh = smeshBuilder.New()" << endl
1862 << "meshSO = salome.myStudy.FindObjectID('0:1:2:" << tag <<"')" << endl
1863 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
1868 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1869 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1870 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1871 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1875 ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1876 struct MyStream : public ostream
1878 template <class T> ostream & operator<<( const T &anything ) { return *this ; }
1880 void Pause() { py = &_mystream; }
1881 void Resume() { py = _pyStream; }
1885 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1886 #define dumpMove(n) { _dumpMove(n, __LINE__);}
1887 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1888 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
1889 void _dumpFunction(const string& fun, int ln)
1890 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1891 void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1892 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1893 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1894 void _dumpCmd(const string& txt, int ln)
1895 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
1896 void dumpFunctionEnd()
1897 { if (py) *py<< " return"<< endl; }
1898 void dumpChangeNodes( const SMDS_MeshElement* f )
1899 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
1900 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1901 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1902 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1906 struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} void Pause() {} void Resume() {} };
1907 #define dumpFunction(f) f
1909 #define dumpMoveComm(n,txt)
1910 #define dumpCmd(txt)
1911 #define dumpFunctionEnd()
1912 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1913 #define debugMsg( txt ) {}
1918 using namespace VISCOUS_3D;
1920 //================================================================================
1922 * \brief Constructor of _ViscousBuilder
1924 //================================================================================
1926 _ViscousBuilder::_ViscousBuilder()
1928 _error = SMESH_ComputeError::New(COMPERR_OK);
1932 //================================================================================
1934 * \brief Stores error description and returns false
1936 //================================================================================
1938 bool _ViscousBuilder::error(const string& text, int solidId )
1940 const string prefix = string("Viscous layers builder: ");
1941 _error->myName = COMPERR_ALGO_FAILED;
1942 _error->myComment = prefix + text;
1945 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1946 if ( !sm && !_sdVec.empty() )
1947 sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1948 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1950 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1951 if ( smError && smError->myAlgo )
1952 _error->myAlgo = smError->myAlgo;
1954 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1956 // set KO to all solids
1957 for ( size_t i = 0; i < _sdVec.size(); ++i )
1959 if ( _sdVec[i]._index == solidId )
1961 sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1962 if ( !sm->IsEmpty() )
1964 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1965 if ( !smError || smError->IsOK() )
1967 smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1968 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1972 makeGroupOfLE(); // debug
1977 //================================================================================
1979 * \brief At study restoration, restore event listeners used to clear an inferior
1980 * dim sub-mesh modified by viscous layers
1982 //================================================================================
1984 void _ViscousBuilder::RestoreListeners()
1989 //================================================================================
1991 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1993 //================================================================================
1995 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1997 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1998 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1999 for ( ; fExp.More(); fExp.Next() )
2001 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
2002 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
2004 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
2006 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
2009 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
2010 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
2012 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
2013 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
2014 while( prxIt->more() )
2016 const SMDS_MeshElement* fSrc = srcIt->next();
2017 const SMDS_MeshElement* fPrx = prxIt->next();
2018 if ( fSrc->NbNodes() != fPrx->NbNodes())
2019 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
2020 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
2021 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
2024 pm->_n2nMapComputed = true;
2028 //================================================================================
2030 * \brief Does its job
2032 //================================================================================
2034 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
2035 const TopoDS_Shape& theShape)
2041 // check if proxy mesh already computed
2042 TopExp_Explorer exp( theShape, TopAbs_SOLID );
2044 return error("No SOLID's in theShape"), _error;
2046 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
2047 return SMESH_ComputeErrorPtr(); // everything already computed
2049 // TODO: ignore already computed SOLIDs
2050 if ( !findSolidsWithLayers())
2053 if ( !findFacesWithLayers() )
2056 if ( !makeEdgesOnShape() )
2059 findPeriodicFaces();
2061 PyDump debugDump( theMesh );
2062 _pyDump = &debugDump;
2065 for ( size_t i = 0; i < _sdVec.size(); ++i )
2068 for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
2069 if ( _sdVec[iSD]._before.IsEmpty() &&
2070 !_sdVec[iSD]._solid.IsNull() &&
2071 !_sdVec[iSD]._done )
2073 if ( iSD == _sdVec.size() )
2076 if ( ! makeLayer(_sdVec[iSD]) ) // create _LayerEdge's
2079 if ( _sdVec[iSD]._n2eMap.size() == 0 ) // no layers in a SOLID
2081 _sdVec[iSD]._solid.Nullify();
2085 if ( ! inflate(_sdVec[iSD]) ) // increase length of _LayerEdge's
2088 if ( ! refine(_sdVec[iSD]) ) // create nodes and prisms
2091 if ( ! shrink(_sdVec[iSD]) ) // shrink 2D mesh on FACEs w/o layer
2094 addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
2096 _sdVec[iSD]._done = true;
2098 const TopoDS_Shape& solid = _sdVec[iSD]._solid;
2099 for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
2100 _sdVec[iSD]._before.Remove( solid );
2103 makeGroupOfLE(); // debug
2109 //================================================================================
2111 * \brief Check validity of hypotheses
2113 //================================================================================
2115 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh& mesh,
2116 const TopoDS_Shape& shape )
2120 if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
2121 return SMESH_ComputeErrorPtr(); // everything already computed
2124 findSolidsWithLayers( /*checkFaceMesh=*/false );
2125 bool ok = findFacesWithLayers( true );
2127 // remove _MeshOfSolid's of _SolidData's
2128 for ( size_t i = 0; i < _sdVec.size(); ++i )
2129 _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
2134 return SMESH_ComputeErrorPtr();
2137 //================================================================================
2139 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
2141 //================================================================================
2143 bool _ViscousBuilder::findSolidsWithLayers(const bool checkFaceMesh)
2146 TopTools_IndexedMapOfShape allSolids;
2147 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
2148 _sdVec.reserve( allSolids.Extent());
2150 SMESH_HypoFilter filter;
2151 for ( int i = 1; i <= allSolids.Extent(); ++i )
2153 SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
2154 if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
2155 continue; // solid is already meshed
2156 // TODO: check if algo is hidden
2157 SMESH_Algo* algo = sm->GetAlgo();
2158 if ( !algo ) continue;
2159 // check if all FACEs are meshed, which can be false if Compute() a sub-shape
2160 if ( checkFaceMesh )
2162 bool facesMeshed = true;
2163 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,true);
2164 while ( smIt->more() && facesMeshed )
2166 SMESH_subMesh * faceSM = smIt->next();
2167 if ( faceSM->GetSubShape().ShapeType() != TopAbs_FACE )
2169 facesMeshed = faceSM->IsMeshComputed();
2174 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
2175 const list <const SMESHDS_Hypothesis *> & allHyps =
2176 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
2177 _SolidData* soData = 0;
2178 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
2179 const StdMeshers_ViscousLayers* viscHyp = 0;
2180 for ( ; hyp != allHyps.end(); ++hyp )
2181 if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
2183 TopoDS_Shape hypShape;
2184 filter.Init( filter.Is( viscHyp ));
2185 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
2189 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
2192 _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
2193 soData = & _sdVec.back();
2194 soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
2195 soData->_helper = new SMESH_MesherHelper( *_mesh );
2196 soData->_helper->SetSubShape( allSolids(i) );
2197 _solids.Add( allSolids(i) );
2199 soData->_hyps.push_back( viscHyp );
2200 soData->_hypShapes.push_back( hypShape );
2203 if ( _sdVec.empty() )
2205 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
2210 //================================================================================
2212 * \brief Set a _SolidData to be computed before another
2214 //================================================================================
2216 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
2218 // check possibility to set this order; get all solids before solidBefore
2219 TopTools_IndexedMapOfShape allSolidsBefore;
2220 allSolidsBefore.Add( solidBefore._solid );
2221 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2223 int iSD = _solids.FindIndex( allSolidsBefore(i) );
2226 TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2227 for ( ; soIt.More(); soIt.Next() )
2228 allSolidsBefore.Add( soIt.Value() );
2231 if ( allSolidsBefore.Contains( solidAfter._solid ))
2234 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2235 solidAfter._before.Add( allSolidsBefore(i) );
2240 //================================================================================
2244 //================================================================================
2246 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2248 SMESH_MesherHelper helper( *_mesh );
2249 TopExp_Explorer exp;
2251 // collect all faces-to-ignore defined by hyp
2252 for ( size_t i = 0; i < _sdVec.size(); ++i )
2254 // get faces-to-ignore defined by each hyp
2255 typedef const StdMeshers_ViscousLayers* THyp;
2256 typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2257 list< TFacesOfHyp > ignoreFacesOfHyps;
2258 list< THyp >::iterator hyp = _sdVec[i]._hyps.begin();
2259 list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2260 for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2262 ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2263 getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2266 // fill _SolidData::_face2hyp and check compatibility of hypotheses
2267 const int nbHyps = _sdVec[i]._hyps.size();
2270 // check if two hypotheses define different parameters for the same FACE
2271 list< TFacesOfHyp >::iterator igFacesOfHyp;
2272 for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2274 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2276 igFacesOfHyp = ignoreFacesOfHyps.begin();
2277 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2278 if ( ! igFacesOfHyp->first.count( faceID ))
2281 return error(SMESH_Comment("Several hypotheses define "
2282 "Viscous Layers on the face #") << faceID );
2283 hyp = igFacesOfHyp->second;
2286 _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2288 _sdVec[i]._ignoreFaceIds.insert( faceID );
2291 // check if two hypotheses define different number of viscous layers for
2292 // adjacent faces of a solid
2293 set< int > nbLayersSet;
2294 igFacesOfHyp = ignoreFacesOfHyps.begin();
2295 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2297 nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2299 if ( nbLayersSet.size() > 1 )
2301 for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2303 PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2304 THyp hyp1 = 0, hyp2 = 0;
2305 while( const TopoDS_Shape* face = fIt->next() )
2307 const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2308 map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2309 if ( f2h != _sdVec[i]._face2hyp.end() )
2311 ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2314 if ( hyp1 && hyp2 &&
2315 hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2317 return error("Two hypotheses define different number of "
2318 "viscous layers on adjacent faces");
2322 } // if ( nbHyps > 1 )
2325 _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2329 if ( onlyWith ) // is called to check hypotheses compatibility only
2332 // fill _SolidData::_reversedFaceIds
2333 for ( size_t i = 0; i < _sdVec.size(); ++i )
2335 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2336 for ( ; exp.More(); exp.Next() )
2338 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2339 const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2340 if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2341 helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2342 helper.IsReversedSubMesh( face ))
2344 _sdVec[i]._reversedFaceIds.insert( faceID );
2349 // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2350 TopTools_IndexedMapOfShape shapes;
2351 std::string structAlgoName = "Hexa_3D";
2352 for ( size_t i = 0; i < _sdVec.size(); ++i )
2355 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2356 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2358 const TopoDS_Shape& edge = shapes(iE);
2359 // find 2 FACEs sharing an EDGE
2361 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2362 while ( fIt->more())
2364 const TopoDS_Shape* f = fIt->next();
2365 FF[ int( !FF[0].IsNull()) ] = *f;
2367 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2369 // check presence of layers on them
2371 for ( int j = 0; j < 2; ++j )
2372 ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2373 if ( ignore[0] == ignore[1] )
2374 continue; // nothing interesting
2375 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ]; // FACE w/o layers
2378 if ( !fWOL.IsNull())
2380 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2381 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2386 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2388 for ( size_t i = 0; i < _sdVec.size(); ++i )
2391 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2392 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2394 const TopoDS_Shape& vertex = shapes(iV);
2395 // find faces WOL sharing the vertex
2396 vector< TopoDS_Shape > facesWOL;
2397 size_t totalNbFaces = 0;
2398 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2399 while ( fIt->more())
2401 const TopoDS_Shape* f = fIt->next();
2403 const int fID = getMeshDS()->ShapeToIndex( *f );
2404 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2405 facesWOL.push_back( *f );
2407 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2408 continue; // no layers at this vertex or no WOL
2409 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2410 switch ( facesWOL.size() )
2414 helper.SetSubShape( facesWOL[0] );
2415 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2417 TopoDS_Shape seamEdge;
2418 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2419 while ( eIt->more() && seamEdge.IsNull() )
2421 const TopoDS_Shape* e = eIt->next();
2422 if ( helper.IsRealSeam( *e ) )
2425 if ( !seamEdge.IsNull() )
2427 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2431 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2436 // find an edge shared by 2 faces
2437 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2438 while ( eIt->more())
2440 const TopoDS_Shape* e = eIt->next();
2441 if ( helper.IsSubShape( *e, facesWOL[0]) &&
2442 helper.IsSubShape( *e, facesWOL[1]))
2444 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2450 std::ostringstream msg;
2451 msg << "Not yet supported case: vertex bounded by ";
2452 msg << facesWOL.size();
2453 msg << " faces without layer at coordinates (";
2454 TopoDS_Vertex v = TopoDS::Vertex(vertex);
2455 gp_Pnt p = BRep_Tool::Pnt(v);
2456 msg << p.X() << ", " << p.Y() << ", " << p.Z() << ")";
2457 return error(msg.str().c_str(), _sdVec[i]._index);
2462 // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrunk since
2463 // the algo of the SOLID sharing the FACE does not support it or for other reasons
2464 set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2465 for ( size_t i = 0; i < _sdVec.size(); ++i )
2467 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2468 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2470 const TopoDS_Shape& fWOL = e2f->second;
2471 const TGeomID edgeID = e2f->first;
2472 TGeomID faceID = getMeshDS()->ShapeToIndex( fWOL );
2473 TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2474 if ( edge.ShapeType() != TopAbs_EDGE )
2475 continue; // shrink shape is VERTEX
2478 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2479 while ( soIt->more() && solid.IsNull() )
2481 const TopoDS_Shape* so = soIt->next();
2482 if ( !so->IsSame( _sdVec[i]._solid ))
2485 if ( solid.IsNull() )
2488 bool noShrinkE = false;
2489 SMESH_Algo* algo = _mesh->GetSubMesh( solid )->GetAlgo();
2490 bool isStructured = ( algo && algo->GetName() == structAlgoName );
2491 size_t iSolid = _solids.FindIndex( solid ) - 1;
2492 if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2494 // the adjacent SOLID has NO layers on fWOL;
2495 // shrink allowed if
2496 // - there are layers on the EDGE in the adjacent SOLID
2497 // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2498 bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2499 bool shrinkAllowed = (( hasWLAdj ) ||
2500 ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2501 noShrinkE = !shrinkAllowed;
2503 else if ( iSolid < _sdVec.size() )
2505 // the adjacent SOLID has layers on fWOL;
2506 // check if SOLID's mesh is unstructured and then try to set it
2507 // to be computed after the i-th solid
2508 if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2509 noShrinkE = true; // don't shrink fWOL
2513 // the adjacent SOLID has NO layers at all
2514 noShrinkE = isStructured;
2519 _sdVec[i]._noShrinkShapes.insert( edgeID );
2521 // check if there is a collision with to-shrink-from EDGEs in iSolid
2522 // if ( iSolid < _sdVec.size() )
2525 // TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2526 // for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2528 // const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2529 // const TGeomID eID = getMeshDS()->ShapeToIndex( E );
2530 // if ( eID == edgeID ||
2531 // !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2532 // _sdVec[i]._noShrinkShapes.count( eID ))
2534 // for ( int is1st = 0; is1st < 2; ++is1st )
2536 // TopoDS_Vertex V = helper.IthVertex( is1st, E );
2537 // if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2539 // return error("No way to make a conformal mesh with "
2540 // "the given set of faces with layers", _sdVec[i]._index);
2547 // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2548 // _shrinkShape2Shape is different in the adjacent SOLID
2549 for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2551 TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2552 bool noShrinkV = false, noShrinkIfAdjMeshed = false;
2554 if ( iSolid < _sdVec.size() )
2556 if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2558 map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2559 i2S = _sdVec[i ]._shrinkShape2Shape.find( vID );
2560 i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2561 if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2562 noShrinkV = (( isStructured ) ||
2563 ( noShrinkIfAdjMeshed = i2S->second.ShapeType() == TopAbs_EDGE ));
2565 noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2569 noShrinkV = noShrinkE;
2574 // the adjacent SOLID has NO layers at all
2581 noShrinkV = noShrinkIfAdjMeshed =
2582 ( _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2586 if ( noShrinkV && noShrinkIfAdjMeshed )
2588 // noShrinkV if FACEs in the adjacent SOLID are meshed
2589 PShapeIteratorPtr fIt = helper.GetAncestors( _sdVec[i]._shrinkShape2Shape[ vID ],
2590 *_mesh, TopAbs_FACE, &solid );
2591 while ( fIt->more() )
2593 const TopoDS_Shape* f = fIt->next();
2594 if ( !f->IsSame( fWOL ))
2596 noShrinkV = ! _mesh->GetSubMesh( *f )->IsEmpty();
2602 _sdVec[i]._noShrinkShapes.insert( vID );
2605 } // loop on _sdVec[i]._shrinkShape2Shape
2606 } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2609 // add FACEs of other SOLIDs to _ignoreFaceIds
2610 for ( size_t i = 0; i < _sdVec.size(); ++i )
2613 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2615 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2617 if ( !shapes.Contains( exp.Current() ))
2618 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2625 //================================================================================
2627 * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2629 //================================================================================
2631 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape& solid,
2632 const StdMeshers_ViscousLayers* hyp,
2633 const TopoDS_Shape& hypShape,
2634 set<TGeomID>& ignoreFaceIds)
2636 TopExp_Explorer exp;
2638 vector<TGeomID> ids = hyp->GetBndShapes();
2639 if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2641 for ( size_t ii = 0; ii < ids.size(); ++ii )
2643 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2644 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2645 ignoreFaceIds.insert( ids[ii] );
2648 else // FACEs with layers are given
2650 exp.Init( solid, TopAbs_FACE );
2651 for ( ; exp.More(); exp.Next() )
2653 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2654 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2655 ignoreFaceIds.insert( faceInd );
2659 // ignore internal FACEs if inlets and outlets are specified
2660 if ( hyp->IsToIgnoreShapes() )
2662 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2663 TopExp::MapShapesAndAncestors( hypShape,
2664 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2666 for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2668 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2669 if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2672 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2674 ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2679 //================================================================================
2681 * \brief Create the inner surface of the viscous layer and prepare data for infation
2683 //================================================================================
2685 bool _ViscousBuilder::makeLayer(_SolidData& data)
2687 // make a map to find new nodes on sub-shapes shared with other SOLID
2688 map< TGeomID, TNode2Edge* >::iterator s2ne;
2689 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2690 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2692 TGeomID shapeInd = s2s->first;
2693 for ( size_t i = 0; i < _sdVec.size(); ++i )
2695 if ( _sdVec[i]._index == data._index ) continue;
2696 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2697 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2698 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2700 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2706 // Create temporary faces and _LayerEdge's
2708 debugMsg( "######################" );
2709 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2711 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2713 data._stepSize = Precision::Infinite();
2714 data._stepSizeNodes[0] = 0;
2716 SMESH_MesherHelper helper( *_mesh );
2717 helper.SetSubShape( data._solid );
2718 helper.SetElementsOnShape( true );
2720 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2721 TNode2Edge::iterator n2e2;
2723 // make _LayerEdge's
2724 for ( TopExp_Explorer exp( data._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2726 const TopoDS_Face& F = TopoDS::Face( exp.Current() );
2727 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2728 const TGeomID id = sm->GetId();
2729 if ( edgesByGeom[ id ]._shape.IsNull() )
2730 continue; // no layers
2731 SMESH_ProxyMesh::SubMesh* proxySub =
2732 data._proxyMesh->getFaceSubM( F, /*create=*/true);
2734 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2735 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << id, data._index );
2737 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2738 while ( eIt->more() )
2740 const SMDS_MeshElement* face = eIt->next();
2741 double faceMaxCosin = -1;
2742 _LayerEdge* maxCosinEdge = 0;
2743 int nbDegenNodes = 0;
2745 newNodes.resize( face->NbCornerNodes() );
2746 for ( size_t i = 0 ; i < newNodes.size(); ++i )
2748 const SMDS_MeshNode* n = face->GetNode( i );
2749 const int shapeID = n->getshapeId();
2750 const bool onDegenShap = helper.IsDegenShape( shapeID );
2751 const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2756 // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2757 const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2758 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2759 if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2769 TNode2Edge::iterator n2e = data._n2eMap.insert({ n, nullptr }).first;
2770 if ( !(*n2e).second )
2773 _LayerEdge* edge = _Factory::NewLayerEdge();
2774 edge->_nodes.push_back( n );
2776 edgesByGeom[ shapeID ]._edges.push_back( edge );
2777 const bool noShrink = data._noShrinkShapes.count( shapeID );
2779 SMESH_TNodeXYZ xyz( n );
2781 // set edge data or find already refined _LayerEdge and get data from it
2782 if (( !noShrink ) &&
2783 ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE ) &&
2784 (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2785 (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end() ))
2787 _LayerEdge* foundEdge = (*n2e2).second;
2788 gp_XYZ lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2789 foundEdge->_pos.push_back( lastPos );
2790 // location of the last node is modified and we restore it by foundEdge->_pos.back()
2791 const_cast< SMDS_MeshNode* >
2792 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2798 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2800 if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2803 if ( edge->_nodes.size() < 2 && !noShrink )
2804 edge->Block( data ); // a sole node is moved only if noShrink
2806 dumpMove(edge->_nodes.back());
2808 if ( edge->_cosin > faceMaxCosin && edge->_nodes.size() > 1 )
2810 faceMaxCosin = edge->_cosin;
2811 maxCosinEdge = edge;
2814 newNodes[ i ] = n2e->second->_nodes.back();
2817 data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2819 if ( newNodes.size() - nbDegenNodes < 2 )
2822 // create a temporary face
2823 const SMDS_MeshElement* newFace =
2824 new _TmpMeshFace( newNodes, --_tmpFaceID, face->GetShapeID(), face );
2825 proxySub->AddElement( newFace );
2827 // compute inflation step size by min size of element on a convex surface
2828 if ( faceMaxCosin > theMinSmoothCosin )
2829 limitStepSize( data, face, maxCosinEdge );
2831 } // loop on 2D elements on a FACE
2832 } // loop on FACEs of a SOLID to create _LayerEdge's
2835 // Set _LayerEdge::_neibors
2836 TNode2Edge::iterator n2e;
2837 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2839 _EdgesOnShape& eos = data._edgesOnShape[iS];
2840 for ( size_t i = 0; i < eos._edges.size(); ++i )
2842 _LayerEdge* edge = eos._edges[i];
2843 TIDSortedNodeSet nearNodes;
2844 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2845 while ( fIt->more() )
2847 const SMDS_MeshElement* f = fIt->next();
2848 if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2849 nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2851 nearNodes.erase( edge->_nodes[0] );
2852 edge->_neibors.reserve( nearNodes.size() );
2853 TIDSortedNodeSet::iterator node = nearNodes.begin();
2854 for ( ; node != nearNodes.end(); ++node )
2855 if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2856 edge->_neibors.push_back( n2e->second );
2859 // Fix uv of nodes on periodic FACEs (bos #20643)
2861 if ( eos.ShapeType() != TopAbs_EDGE ||
2862 eos.SWOLType() != TopAbs_FACE ||
2866 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
2867 SMESH_MesherHelper faceHelper( *_mesh );
2868 faceHelper.SetSubShape( F );
2869 faceHelper.ToFixNodeParameters( true );
2870 if ( faceHelper.GetPeriodicIndex() == 0 )
2873 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( F );
2874 if ( !smDS || smDS->GetNodes() == 0 )
2877 bool toCheck = true;
2878 const double tol = 2 * helper.MaxTolerance( F );
2879 for ( SMDS_NodeIteratorPtr nIt = smDS->GetNodes(); nIt->more(); )
2881 const SMDS_MeshNode* node = nIt->next();
2882 gp_XY uvNew( Precision::Infinite(), 0 );
2886 gp_XY uv = faceHelper.GetNodeUV( F, node );
2887 if ( ! faceHelper.CheckNodeUV( F, node, uvNew, tol, /*force=*/true ))
2888 break; // projection on F failed
2889 if (( uv - uvNew ).Modulus() < Precision::Confusion() )
2890 break; // current uv is OK
2892 faceHelper.CheckNodeUV( F, node, uvNew, tol, /*force=*/true );
2896 data._epsilon = 1e-7;
2897 if ( data._stepSize < 1. )
2898 data._epsilon *= data._stepSize;
2900 if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2903 // limit data._stepSize depending on surface curvature and fill data._convexFaces
2904 limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2906 // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2907 const SMDS_MeshNode* nn[2];
2908 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2910 _EdgesOnShape& eos = data._edgesOnShape[iS];
2911 for ( size_t i = 0; i < eos._edges.size(); ++i )
2913 _LayerEdge* edge = eos._edges[i];
2914 if ( edge->IsOnEdge() )
2916 // get neighbor nodes
2917 bool hasData = ( edge->_2neibors->_edges[0] );
2918 if ( hasData ) // _LayerEdge is a copy of another one
2920 nn[0] = edge->_2neibors->srcNode(0);
2921 nn[1] = edge->_2neibors->srcNode(1);
2923 else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2927 // set neighbor _LayerEdge's
2928 for ( int j = 0; j < 2; ++j )
2930 if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2931 return error("_LayerEdge not found by src node", data._index);
2932 edge->_2neibors->_edges[j] = n2e->second;
2935 edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2938 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2940 _Simplex& s = edge->_simplices[j];
2941 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2942 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2945 // For an _LayerEdge on a degenerated EDGE, copy some data from
2946 // a corresponding _LayerEdge on a VERTEX
2947 // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2948 if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2950 // Generally we should not get here
2951 if ( eos.ShapeType() != TopAbs_EDGE )
2953 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2954 const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2955 if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2957 const _LayerEdge* vEdge = n2e->second;
2958 edge->_normal = vEdge->_normal;
2959 edge->_lenFactor = vEdge->_lenFactor;
2960 edge->_cosin = vEdge->_cosin;
2963 } // loop on data._edgesOnShape._edges
2964 } // loop on data._edgesOnShape
2966 // fix _LayerEdge::_2neibors on EDGEs to smooth
2967 // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2968 // for ( ; e2c != data._edge2curve.end(); ++e2c )
2969 // if ( !e2c->second.IsNull() )
2971 // if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2972 // data.Sort2NeiborsOnEdge( eos->_edges );
2979 //================================================================================
2981 * \brief Compute inflation step size by min size of element on a convex surface
2983 //================================================================================
2985 void _ViscousBuilder::limitStepSize( _SolidData& data,
2986 const SMDS_MeshElement* face,
2987 const _LayerEdge* maxCosinEdge )
2990 double minSize = 10 * data._stepSize;
2991 const int nbNodes = face->NbCornerNodes();
2992 for ( int i = 0; i < nbNodes; ++i )
2994 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2995 const SMDS_MeshNode* curN = face->GetNode( i );
2996 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2997 curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2999 double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
3000 if ( dist < minSize )
3001 minSize = dist, iN = i;
3004 double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
3005 if ( newStep < data._stepSize )
3007 data._stepSize = newStep;
3008 data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
3009 data._stepSizeNodes[0] = face->GetNode( iN );
3010 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
3014 //================================================================================
3016 * \brief Compute inflation step size by min size of element on a convex surface
3018 //================================================================================
3020 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
3022 if ( minSize < data._stepSize )
3024 data._stepSize = minSize;
3025 if ( data._stepSizeNodes[0] )
3028 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
3029 data._stepSizeCoeff = data._stepSize / dist;
3034 //================================================================================
3036 * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
3038 //================================================================================
3040 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
3042 SMESH_MesherHelper helper( *_mesh );
3044 BRepLProp_SLProps surfProp( 2, 1e-6 );
3045 data._convexFaces.clear();
3047 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
3049 _EdgesOnShape& eof = data._edgesOnShape[iS];
3050 if ( eof.ShapeType() != TopAbs_FACE ||
3051 data._ignoreFaceIds.count( eof._shapeID ))
3054 TopoDS_Face F = TopoDS::Face( eof._shape );
3055 const TGeomID faceID = eof._shapeID;
3057 BRepAdaptor_Surface surface( F, false );
3058 surfProp.SetSurface( surface );
3060 _ConvexFace cnvFace;
3062 cnvFace._normalsFixed = false;
3063 cnvFace._isTooCurved = false;
3064 cnvFace._normalsFixedOnBorders = false;
3066 double maxCurvature = cnvFace.GetMaxCurvature( data, eof, surfProp, helper );
3067 if ( maxCurvature > 0 )
3069 limitStepSize( data, 0.9 / maxCurvature );
3070 findEdgesToUpdateNormalNearConvexFace( cnvFace, data, helper );
3072 if ( !cnvFace._isTooCurved ) continue;
3074 _ConvexFace & convFace =
3075 data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
3077 // skip a closed surface (data._convexFaces is useful anyway)
3078 bool isClosedF = false;
3079 helper.SetSubShape( F );
3080 if ( helper.HasRealSeam() )
3082 // in the closed surface there must be a closed EDGE
3083 for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
3084 isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
3088 // limit _LayerEdge::_maxLen on the FACE
3089 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
3090 const double minCurvature =
3091 1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
3092 map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
3093 if ( id2eos != cnvFace._subIdToEOS.end() )
3095 _EdgesOnShape& eos = * id2eos->second;
3096 for ( size_t i = 0; i < eos._edges.size(); ++i )
3098 _LayerEdge* ledge = eos._edges[ i ];
3099 gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
3100 surfProp.SetParameters( uv.X(), uv.Y() );
3101 if ( surfProp.IsCurvatureDefined() )
3103 double curvature = Max( surfProp.MaxCurvature() * oriFactor,
3104 surfProp.MinCurvature() * oriFactor );
3105 if ( curvature > minCurvature )
3106 ledge->SetMaxLen( Min( ledge->_maxLen, 1. / curvature ));
3113 // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
3114 // prism distortion.
3115 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
3116 if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
3118 // there are _LayerEdge's on the FACE it-self;
3119 // select _LayerEdge's near EDGEs
3120 _EdgesOnShape& eos = * id2eos->second;
3121 for ( size_t i = 0; i < eos._edges.size(); ++i )
3123 _LayerEdge* ledge = eos._edges[ i ];
3124 for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
3125 if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
3127 // do not select _LayerEdge's neighboring sharp EDGEs
3128 bool sharpNbr = false;
3129 for ( size_t iN = 0; iN < ledge->_neibors.size() && !sharpNbr; ++iN )
3130 sharpNbr = ( ledge->_neibors[iN]->_cosin > theMinSmoothCosin );
3132 convFace._simplexTestEdges.push_back( ledge );
3139 // where there are no _LayerEdge's on a _ConvexFace,
3140 // as e.g. on a fillet surface with no internal nodes - issue 22580,
3141 // so that collision of viscous internal faces is not detected by check of
3142 // intersection of _LayerEdge's with the viscous internal faces.
3144 set< const SMDS_MeshNode* > usedNodes;
3146 // look for _LayerEdge's with null _sWOL
3147 id2eos = convFace._subIdToEOS.begin();
3148 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
3150 _EdgesOnShape& eos = * id2eos->second;
3151 if ( !eos._sWOL.IsNull() )
3153 for ( size_t i = 0; i < eos._edges.size(); ++i )
3155 _LayerEdge* ledge = eos._edges[ i ];
3156 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
3157 if ( !usedNodes.insert( srcNode ).second ) continue;
3159 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
3161 usedNodes.insert( ledge->_simplices[i]._nPrev );
3162 usedNodes.insert( ledge->_simplices[i]._nNext );
3164 convFace._simplexTestEdges.push_back( ledge );
3168 } // loop on FACEs of data._solid
3171 //================================================================================
3173 * \brief Detect shapes (and _LayerEdge's on them) to smooth
3175 //================================================================================
3177 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
3179 // define allowed thickness
3180 computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
3183 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
3184 // boundary inclined to the shape at a sharp angle
3186 TopTools_MapOfShape edgesOfSmooFaces;
3187 SMESH_MesherHelper helper( *_mesh );
3190 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
3191 data._nbShapesToSmooth = 0;
3193 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3195 _EdgesOnShape& eos = edgesByGeom[iS];
3196 eos._toSmooth = false;
3197 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
3200 double tgtThick = eos._hyp.GetTotalThickness();
3201 SMESH_subMeshIteratorPtr subIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false );
3202 while ( subIt->more() && !eos._toSmooth )
3204 TGeomID iSub = subIt->next()->GetId();
3205 const vector<_LayerEdge*>& eSub = edgesByGeom[ iSub ]._edges;
3206 if ( eSub.empty() ) continue;
3209 for ( size_t i = 0; i < eSub.size() && !eos._toSmooth; ++i )
3210 if ( eSub[i]->_cosin > theMinSmoothCosin )
3212 SMDS_ElemIteratorPtr fIt = eSub[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3213 while ( fIt->more() && !eos._toSmooth )
3215 const SMDS_MeshElement* face = fIt->next();
3216 if ( face->getshapeId() == eos._shapeID &&
3217 getDistFromEdge( face, eSub[i]->_nodes[0], faceSize ))
3219 eos._toSmooth = needSmoothing( eSub[i]->_cosin,
3220 tgtThick * eSub[i]->_lenFactor,
3226 if ( eos._toSmooth )
3228 for ( TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
3229 edgesOfSmooFaces.Add( eExp.Current() );
3231 data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3233 data._nbShapesToSmooth += eos._toSmooth;
3237 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3239 _EdgesOnShape& eos = edgesByGeom[iS];
3240 eos._edgeSmoother = NULL;
3241 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3242 if ( !eos._hyp.ToSmooth() ) continue;
3244 const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3245 if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3248 double tgtThick = eos._hyp.GetTotalThickness(), h0 = eos._hyp.Get1stLayerThickness();
3249 for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3251 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3252 vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3253 if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3254 gp_Vec eDir = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ), h0 );
3255 double angle = eDir.Angle( eV[0]->_normal );
3256 double cosin = Cos( angle );
3257 double cosinAbs = Abs( cosin );
3258 if ( cosinAbs > theMinSmoothCosin )
3260 // always smooth analytic EDGEs
3261 Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3262 eos._toSmooth = ! curve.IsNull();
3264 // compare tgtThick with the length of an end segment
3265 SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3266 while ( eIt->more() && !eos._toSmooth )
3268 const SMDS_MeshElement* endSeg = eIt->next();
3269 if ( endSeg->getshapeId() == (int) iS )
3272 SMESH_TNodeXYZ( endSeg->GetNode( 0 )).Distance( endSeg->GetNode( 1 ));
3273 eos._toSmooth = needSmoothing( cosinAbs, tgtThick * eV[0]->_lenFactor, segLen );
3276 if ( eos._toSmooth )
3278 eos._edgeSmoother = new _Smoother1D( curve, eos );
3280 // for ( size_t i = 0; i < eos._edges.size(); ++i )
3281 // eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3285 data._nbShapesToSmooth += eos._toSmooth;
3289 // Reset _cosin if no smooth is allowed by the user
3290 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3292 _EdgesOnShape& eos = edgesByGeom[iS];
3293 if ( eos._edges.empty() ) continue;
3295 if ( !eos._hyp.ToSmooth() )
3296 for ( size_t i = 0; i < eos._edges.size(); ++i )
3297 //eos._edges[i]->SetCosin( 0 ); // keep _cosin to use in limitMaxLenByCurvature()
3298 eos._edges[i]->_lenFactor = 1;
3302 // Fill _eosC1 to make that C1 FACEs and EDGEs between them to be smoothed as a whole
3304 TopTools_MapOfShape c1VV;
3306 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3308 _EdgesOnShape& eos = edgesByGeom[iS];
3309 if ( eos._edges.empty() ||
3310 eos.ShapeType() != TopAbs_FACE ||
3314 // check EDGEs of a FACE
3315 TopTools_MapOfShape checkedEE, allVV;
3316 list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3317 while ( !smQueue.empty() )
3319 SMESH_subMesh* sm = smQueue.front();
3320 smQueue.pop_front();
3321 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3322 while ( smIt->more() )
3325 if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3326 allVV.Add( sm->GetSubShape() );
3327 if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3328 !checkedEE.Add( sm->GetSubShape() ))
3331 _EdgesOnShape* eoe = data.GetShapeEdges( sm->GetId() );
3332 vector<_LayerEdge*>& eE = eoe->_edges;
3333 if ( eE.empty() || !eoe->_sWOL.IsNull() )
3336 bool isC1 = true; // check continuity along an EDGE
3337 for ( size_t i = 0; i < eE.size() && isC1; ++i )
3338 isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3342 // check that mesh faces are C1 as well
3344 gp_XYZ norm1, norm2;
3345 const SMDS_MeshNode* n = eE[ eE.size() / 2 ]->_nodes[0];
3346 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3347 if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3349 while ( fIt->more() && isC1 )
3350 isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3351 Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3356 // add the EDGE and an adjacent FACE to _eosC1
3357 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3358 while ( const TopoDS_Shape* face = fIt->next() )
3360 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3361 if ( !eof ) continue; // other solid
3362 if ( eos._shapeID == eof->_shapeID ) continue;
3363 if ( !eos.HasC1( eof ))
3366 eos._eosC1.push_back( eof );
3367 eof->_toSmooth = false;
3368 data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3369 smQueue.push_back( eof->_subMesh );
3371 if ( !eos.HasC1( eoe ))
3373 eos._eosC1.push_back( eoe );
3374 eoe->_toSmooth = false;
3375 data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3380 if ( eos._eosC1.empty() )
3383 // check VERTEXes of C1 FACEs
3384 TopTools_MapIteratorOfMapOfShape vIt( allVV );
3385 for ( ; vIt.More(); vIt.Next() )
3387 _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3388 if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3391 bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3392 PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3393 while ( const TopoDS_Shape* face = fIt->next() )
3395 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3396 if ( !eof ) continue; // other solid
3397 isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3403 eos._eosC1.push_back( eov );
3404 data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3405 c1VV.Add( eov->_shape );
3409 } // fill _eosC1 of FACEs
3414 vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3416 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3418 _EdgesOnShape& eov = edgesByGeom[iS];
3419 if ( eov._edges.empty() ||
3420 eov.ShapeType() != TopAbs_VERTEX ||
3421 c1VV.Contains( eov._shape ))
3423 const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3425 // get directions of surrounding EDGEs
3427 PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3428 while ( const TopoDS_Shape* e = fIt->next() )
3430 _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3431 if ( !eoe ) continue; // other solid
3432 gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V, eoe->_hyp.Get1stLayerThickness() );
3433 if ( !Precision::IsInfinite( eDir.X() ))
3434 dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3437 // find EDGEs with C1 directions
3438 for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3439 for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3440 if ( dirOfEdges[i].first && dirOfEdges[j].first )
3442 double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3443 bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3446 double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3447 for ( int isJ = 0; isJ < 2; ++isJ ) // loop on [i,j]
3449 size_t k = isJ ? j : i;
3450 const TopoDS_Edge& e = TopoDS::Edge( dirOfEdges[k].first->_shape );
3451 double eLen = SMESH_Algo::EdgeLength( e );
3452 if ( eLen < maxEdgeLen )
3454 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
3455 if ( oppV.IsSame( V ))
3456 oppV = SMESH_MesherHelper::IthVertex( 1, e );
3457 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
3458 if ( dirOfEdges[k].second * eovOpp->_edges[0]->_normal < 0 )
3459 eov._eosC1.push_back( dirOfEdges[k].first );
3461 dirOfEdges[k].first = 0;
3465 } // fill _eosC1 of VERTEXes
3472 //================================================================================
3474 * \brief Set up _SolidData::_edgesOnShape
3476 //================================================================================
3478 int _ViscousBuilder::makeEdgesOnShape()
3480 const int nbShapes = getMeshDS()->MaxShapeIndex();
3483 for ( size_t i = 0; i < _sdVec.size(); ++i )
3485 _SolidData& data = _sdVec[ i ];
3486 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
3487 edgesByGeom.resize( nbShapes+1 );
3489 // set data of _EdgesOnShape's
3491 if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
3493 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3494 while ( smIt->more() )
3497 if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
3498 data._ignoreFaceIds.count( sm->GetId() ))
3501 setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
3503 nbShapesWL += ( sm->GetSubShape().ShapeType() == TopAbs_FACE );
3506 if ( nbShapesWL == 0 ) // no shapes with layers in a SOLID
3509 SMESHUtils::FreeVector( edgesByGeom );
3519 //================================================================================
3521 * \brief initialize data of _EdgesOnShape
3523 //================================================================================
3525 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3529 if ( !eos._shape.IsNull() ||
3530 sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3533 SMESH_MesherHelper helper( *_mesh );
3536 eos._shapeID = sm->GetId();
3537 eos._shape = sm->GetSubShape();
3538 if ( eos.ShapeType() == TopAbs_FACE )
3539 eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3540 eos._toSmooth = false;
3542 eos._mapper2D = nullptr;
3545 map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3546 data._shrinkShape2Shape.find( eos._shapeID );
3547 if ( s2s != data._shrinkShape2Shape.end() )
3548 eos._sWOL = s2s->second;
3550 eos._isRegularSWOL = true;
3551 if ( eos.SWOLType() == TopAbs_FACE )
3553 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3554 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3555 eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3559 if ( data._hyps.size() == 1 )
3561 eos._hyp = data._hyps.back();
3565 // compute average StdMeshers_ViscousLayers parameters
3566 map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3567 if ( eos.ShapeType() == TopAbs_FACE )
3569 if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3570 eos._hyp = f2hyp->second;
3574 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3575 while ( const TopoDS_Shape* face = fIt->next() )
3577 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3578 if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3579 eos._hyp.Add( f2hyp->second );
3585 if ( ! eos._hyp.UseSurfaceNormal() )
3587 if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3589 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3590 if ( !smDS ) return;
3591 eos._faceNormals.reserve( smDS->NbElements() );
3593 double oriFactor = helper.IsReversedSubMesh( TopoDS::Face( eos._shape )) ? 1.: -1.;
3594 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3595 for ( ; eIt->more(); )
3597 const SMDS_MeshElement* face = eIt->next();
3598 gp_XYZ& norm = eos._faceNormals[face];
3599 if ( !SMESH_MeshAlgos::FaceNormal( face, norm, /*normalized=*/true ))
3600 norm.SetCoord( 0,0,0 );
3604 else // find EOS of adjacent FACEs
3606 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3607 while ( const TopoDS_Shape* face = fIt->next() )
3609 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3610 eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3611 if ( eos._faceEOS.back()->_shape.IsNull() )
3612 // avoid using uninitialised _shapeID in GetNormal()
3613 eos._faceEOS.back()->_shapeID = faceID;
3619 //================================================================================
3621 * \brief Returns normal of a face
3623 //================================================================================
3625 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3628 _EdgesOnShape* eos = 0;
3630 if ( face->getshapeId() == _shapeID )
3636 for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3637 if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3638 eos = _faceEOS[ iF ];
3642 ( ok = ( eos->_faceNormals.count( face ) )))
3644 norm = eos->_faceNormals[ face ];
3648 debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3649 << " on _shape #" << _shapeID );
3654 //================================================================================
3656 * \brief EdgesOnShape destructor
3658 //================================================================================
3660 _EdgesOnShape::~_EdgesOnShape()
3662 delete _edgeSmoother;
3666 //================================================================================
3668 * \brief Set data of _LayerEdge needed for smoothing
3670 //================================================================================
3672 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
3674 SMESH_MesherHelper& helper,
3677 const SMDS_MeshNode* node = edge._nodes[0]; // source node
3680 edge._maxLen = Precision::Infinite();
3683 edge._curvature = 0;
3685 edge._smooFunction = 0;
3687 // --------------------------
3688 // Compute _normal and _cosin
3689 // --------------------------
3692 edge._lenFactor = 1.;
3693 edge._normal.SetCoord(0,0,0);
3694 _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3696 int totalNbFaces = 0;
3698 std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3702 const bool onShrinkShape = !eos._sWOL.IsNull();
3703 const bool useGeometry = (( eos._hyp.UseSurfaceNormal() ) ||
3704 ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3706 // get geom FACEs the node lies on
3707 //if ( useGeometry )
3709 set<TGeomID> faceIds;
3710 if ( eos.ShapeType() == TopAbs_FACE )
3712 faceIds.insert( eos._shapeID );
3716 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3717 while ( fIt->more() )
3718 faceIds.insert( fIt->next()->getshapeId() );
3720 set<TGeomID>::iterator id = faceIds.begin();
3721 for ( ; id != faceIds.end(); ++id )
3723 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3724 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3726 F = TopoDS::Face( s );
3727 face2Norm[ totalNbFaces ].first = F;
3733 bool fromVonF = false;
3736 fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3737 eos.SWOLType() == TopAbs_FACE &&
3740 if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3742 if ( eos.SWOLType() == TopAbs_EDGE )
3744 // inflate from VERTEX along EDGE
3745 edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3746 eos._hyp.Get1stLayerThickness(), &eos._isRegularSWOL );
3748 else if ( eos.ShapeType() == TopAbs_VERTEX )
3750 // inflate from VERTEX along FACE
3751 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3752 node, helper, normOK/*, &edge._cosin*/);
3756 // inflate from EDGE along FACE
3757 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3758 node, helper, normOK);
3761 else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3764 face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3767 for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3769 F = face2Norm[ iF ].first;
3770 geomNorm = getFaceNormal( node, F, helper, normOK );
3771 if ( !normOK ) continue;
3774 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3776 face2Norm[ iF ].second = geomNorm.XYZ();
3777 edge._normal += geomNorm.XYZ();
3779 if ( nbOkNorms == 0 )
3780 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3782 if ( totalNbFaces >= 3 )
3784 edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3787 if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3789 // opposite normals, re-get normals at shifted positions (IPAL 52426)
3790 edge._normal.SetCoord( 0,0,0 );
3791 for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3793 const TopoDS_Face& F = face2Norm[iF].first;
3794 geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3795 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3798 face2Norm[ iF ].second = geomNorm.XYZ();
3799 edge._normal += face2Norm[ iF ].second;
3804 else // !useGeometry - get _normal using surrounding mesh faces
3806 edge._normal = getWeigthedNormal( &edge );
3808 // set<TGeomID> faceIds;
3810 // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3811 // while ( fIt->more() )
3813 // const SMDS_MeshElement* face = fIt->next();
3814 // if ( eos.GetNormal( face, geomNorm ))
3816 // if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3817 // continue; // use only one mesh face on FACE
3818 // edge._normal += geomNorm.XYZ();
3825 //if ( eos._hyp.UseSurfaceNormal() )
3827 switch ( eos.ShapeType() )
3834 TopoDS_Edge E = TopoDS::Edge( eos._shape );
3835 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3836 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3837 edge._cosin = Cos( angle );
3840 case TopAbs_VERTEX: {
3841 TopoDS_Vertex V = TopoDS::Vertex( eos._shape );
3842 gp_Vec inFaceDir = getFaceDir( face2Norm[0].first , V, node, helper, normOK );
3843 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3844 edge._cosin = Cos( angle );
3847 if ( totalNbFaces > 1 || helper.IsSeamShape( node->getshapeId() ))
3848 for ( int iF = 1; iF < totalNbFaces; ++iF )
3850 F = face2Norm[ iF ].first;
3851 inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3853 if ( onShrinkShape )
3855 gp_Vec faceNorm = getFaceNormal( node, F, helper, normOK );
3856 if ( !normOK ) continue;
3857 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3859 angle = 0.5 * M_PI - faceNorm.Angle( edge._normal );
3860 if ( inFaceDir * edge._normal < 0 )
3861 angle = M_PI - angle;
3865 angle = inFaceDir.Angle( edge._normal );
3867 double cosin = Cos( angle );
3868 if ( Abs( cosin ) > Abs( edge._cosin ))
3869 edge._cosin = cosin;
3875 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3879 double normSize = edge._normal.SquareModulus();
3880 if ( normSize < numeric_limits<double>::min() )
3881 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3883 edge._normal /= sqrt( normSize );
3885 if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3887 getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3888 edge._nodes.resize( 1 );
3889 edge._normal.SetCoord( 0,0,0 );
3890 edge.SetMaxLen( 0 );
3893 // Set the rest data
3894 // --------------------
3896 double realLenFactor = edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3897 // if ( realLenFactor > 3 )
3900 // if ( onShrinkShape )
3902 // edge.Set( _LayerEdge::RISKY_SWOL );
3903 // edge._lenFactor = 2;
3907 // edge._lenFactor = 1;
3911 if ( onShrinkShape )
3913 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3914 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3915 sm->RemoveNode( tgtNode );
3917 // set initial position which is parameters on _sWOL in this case
3918 if ( eos.SWOLType() == TopAbs_EDGE )
3920 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3921 edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3922 if ( edge._nodes.size() > 1 )
3923 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3925 else // eos.SWOLType() == TopAbs_FACE
3927 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3928 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3929 if ( edge._nodes.size() > 1 )
3930 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3933 //if ( edge._nodes.size() > 1 ) -- allow RISKY_SWOL on noShrink shape
3935 // check if an angle between a FACE with layers and SWOL is sharp,
3936 // else the edge should not inflate
3938 for ( int iF = 0; iF < totalNbFaces && F.IsNull(); ++iF ) // find a FACE with VL
3939 if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3940 F = face2Norm[iF].first;
3943 geomNorm = getFaceNormal( node, F, helper, normOK );
3944 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3945 geomNorm.Reverse(); // inside the SOLID
3946 if ( geomNorm * edge._normal < -0.001 )
3948 if ( edge._nodes.size() > 1 )
3950 getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3951 edge._nodes.resize( 1 );
3954 else if ( realLenFactor > 3 ) /// -- moved to SetCosin()
3955 //else if ( edge._lenFactor > 3 )
3957 edge._lenFactor = 2;
3958 edge.Set( _LayerEdge::RISKY_SWOL );
3965 edge._pos.push_back( SMESH_TNodeXYZ( node ));
3967 if ( eos.ShapeType() == TopAbs_FACE )
3970 for ( size_t i = 0; i < edge._simplices.size(); ++i )
3972 edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3973 edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3978 // Set neighbor nodes for a _LayerEdge based on EDGE
3980 if ( eos.ShapeType() == TopAbs_EDGE /*||
3981 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3983 edge._2neibors = _Factory::NewNearEdges();
3984 // target nodes instead of source ones will be set later
3990 //================================================================================
3992 * \brief Return normal to a FACE at a node
3993 * \param [in] n - node
3994 * \param [in] face - FACE
3995 * \param [in] helper - helper
3996 * \param [out] isOK - true or false
3997 * \param [in] shiftInside - to find normal at a position shifted inside the face
3998 * \return gp_XYZ - normal
4000 //================================================================================
4002 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
4003 const TopoDS_Face& face,
4004 SMESH_MesherHelper& helper,
4011 // get a shifted position
4012 gp_Pnt p = SMESH_TNodeXYZ( node );
4013 gp_XYZ shift( 0,0,0 );
4014 TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
4015 switch ( S.ShapeType() ) {
4018 shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
4023 shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
4031 p.Translate( shift * 1e-5 );
4033 TopLoc_Location loc;
4034 GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
4036 if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
4038 projector.Perform( p );
4039 if ( !projector.IsDone() || projector.NbPoints() < 1 )
4045 projector.LowerDistanceParameters(U,V);
4050 uv = helper.GetNodeUV( face, node, 0, &isOK );
4056 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
4058 if ( !shiftInside &&
4059 helper.IsDegenShape( node->getshapeId() ) &&
4060 getFaceNormalAtSingularity( uv, face, helper, normal ))
4063 return normal.XYZ();
4066 int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
4067 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
4069 if ( pointKind == IMPOSSIBLE &&
4070 node->GetPosition()->GetDim() == 2 ) // node inside the FACE
4072 // probably NormEstim() failed due to a too high tolerance
4073 pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
4074 isOK = ( pointKind < IMPOSSIBLE );
4076 if ( pointKind < IMPOSSIBLE )
4078 if ( pointKind != REGULAR &&
4080 node->GetPosition()->GetDim() < 2 ) // FACE boundary
4082 gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
4083 if ( normShift * normal.XYZ() < 0. )
4089 if ( !isOK ) // hard singularity, to call with shiftInside=true ?
4091 const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
4093 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4094 while ( fIt->more() )
4096 const SMDS_MeshElement* f = fIt->next();
4097 if ( f->getshapeId() == faceID )
4099 isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
4102 TopoDS_Face ff = face;
4103 ff.Orientation( TopAbs_FORWARD );
4104 if ( helper.IsReversedSubMesh( ff ))
4111 return normal.XYZ();
4114 //================================================================================
4116 * \brief Try to get normal at a singularity of a surface basing on it's nature
4118 //================================================================================
4120 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY& uv,
4121 const TopoDS_Face& face,
4122 SMESH_MesherHelper& /*helper*/,
4125 BRepAdaptor_Surface surface( face );
4127 if ( !getRovolutionAxis( surface, axis ))
4130 double f,l, d, du, dv;
4131 f = surface.FirstUParameter();
4132 l = surface.LastUParameter();
4133 d = ( uv.X() - f ) / ( l - f );
4134 du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
4135 f = surface.FirstVParameter();
4136 l = surface.LastVParameter();
4137 d = ( uv.Y() - f ) / ( l - f );
4138 dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
4141 gp_Pnt2d testUV = uv;
4142 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
4144 Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
4145 for ( int iLoop = 0; true ; ++iLoop )
4147 testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
4148 if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
4155 if ( axis * refDir < 0. )
4163 //================================================================================
4165 * \brief Return a normal at a node weighted with angles taken by faces
4167 //================================================================================
4169 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
4171 const SMDS_MeshNode* n = edge->_nodes[0];
4173 gp_XYZ resNorm(0,0,0);
4174 SMESH_TNodeXYZ p0( n ), pP, pN;
4175 for ( size_t i = 0; i < edge->_simplices.size(); ++i )
4177 pP.Set( edge->_simplices[i]._nPrev );
4178 pN.Set( edge->_simplices[i]._nNext );
4179 gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
4180 double l0P = v0P.SquareMagnitude();
4181 double l0N = v0N.SquareMagnitude();
4182 double lPN = vPN.SquareMagnitude();
4183 if ( l0P < std::numeric_limits<double>::min() ||
4184 l0N < std::numeric_limits<double>::min() ||
4185 lPN < std::numeric_limits<double>::min() )
4187 double lNorm = norm.SquareMagnitude();
4188 double sin2 = lNorm / l0P / l0N;
4189 double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
4191 double weight = sin2 * angle / lPN;
4192 resNorm += weight * norm.XYZ() / Sqrt( lNorm );
4198 //================================================================================
4200 * \brief Return a normal at a node by getting a common point of offset planes
4201 * defined by the FACE normals
4203 //================================================================================
4205 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge* edge,
4206 std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
4210 SMESH_TNodeXYZ p0 = edge->_nodes[0];
4212 gp_XYZ resNorm(0,0,0);
4213 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
4214 if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
4216 for ( int i = 0; i < nbFaces; ++i )
4217 resNorm += f2Normal[i].second;
4221 // prepare _OffsetPlane's
4222 vector< _OffsetPlane > pln( nbFaces );
4223 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
4225 pln[i]._faceIndex = i;
4226 pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
4230 pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
4231 pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
4234 // intersect neighboring OffsetPlane's
4235 PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
4236 while ( const TopoDS_Shape* edge = edgeIt->next() )
4238 int f1 = -1, f2 = -1;
4239 for ( int i = 0; i < nbFaces && f2 < 0; ++i )
4240 if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
4241 (( f1 < 0 ) ? f1 : f2 ) = i;
4244 pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
4247 // get a common point
4248 gp_XYZ commonPnt( 0, 0, 0 );
4251 for ( int i = 0; i < nbFaces; ++i )
4253 commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
4254 nbPoints += isPointFound;
4256 gp_XYZ wgtNorm = getWeigthedNormal( edge );
4257 if ( nbPoints == 0 )
4260 commonPnt /= nbPoints;
4261 resNorm = commonPnt - p0;
4265 // choose the best among resNorm and wgtNorm
4266 resNorm.Normalize();
4267 wgtNorm.Normalize();
4268 double resMinDot = std::numeric_limits<double>::max();
4269 double wgtMinDot = std::numeric_limits<double>::max();
4270 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
4272 resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
4273 wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
4276 if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
4278 edge->Set( _LayerEdge::MULTI_NORMAL );
4281 return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
4284 //================================================================================
4286 * \brief Compute line of intersection of 2 planes
4288 //================================================================================
4290 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane& pln,
4291 const TopoDS_Edge& E,
4292 const TopoDS_Vertex& V )
4294 int iNext = bool( _faceIndexNext[0] >= 0 );
4295 _faceIndexNext[ iNext ] = pln._faceIndex;
4297 gp_XYZ n1 = _plane.Axis().Direction().XYZ();
4298 gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
4300 gp_XYZ lineDir = n1 ^ n2;
4302 double x = Abs( lineDir.X() );
4303 double y = Abs( lineDir.Y() );
4304 double z = Abs( lineDir.Z() );
4306 int cooMax; // max coordinate
4308 if (x > z) cooMax = 1;
4312 if (y > z) cooMax = 2;
4317 if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
4319 // parallel planes - intersection is an offset of the common EDGE
4320 gp_Pnt p = BRep_Tool::Pnt( V );
4321 linePos = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
4322 lineDir = getEdgeDir( E, V, 0.1 * SMESH_Algo::EdgeLength( E ));
4326 // the constants in the 2 plane equations
4327 double d1 = - ( _plane.Axis().Direction().XYZ() * _plane.Location().XYZ() );
4328 double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
4333 linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
4334 linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
4337 linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4339 linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4342 linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4343 linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4347 gp_Lin& line = _lines[ iNext ];
4348 line.SetDirection( lineDir );
4349 line.SetLocation ( linePos );
4351 _isLineOK[ iNext ] = true;
4354 iNext = bool( pln._faceIndexNext[0] >= 0 );
4355 pln._lines [ iNext ] = line;
4356 pln._faceIndexNext[ iNext ] = this->_faceIndex;
4357 pln._isLineOK [ iNext ] = true;
4360 //================================================================================
4362 * \brief Computes intersection point of two _lines
4364 //================================================================================
4366 gp_XYZ _OffsetPlane::GetCommonPoint(bool& isFound,
4367 const TopoDS_Vertex & V) const
4372 if ( NbLines() == 2 )
4374 gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4375 double dot01 = lPerp0 * _lines[1].Direction().XYZ();
4376 if ( Abs( dot01 ) > 0.05 )
4378 gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4379 double u1 = - ( lPerp0 * l0l1 ) / dot01;
4380 p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4385 gp_Pnt pV ( BRep_Tool::Pnt( V ));
4386 gp_Vec lv0( _lines[0].Location(), pV ), lv1(_lines[1].Location(), pV );
4387 double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4388 p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4389 p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4397 //================================================================================
4399 * \brief Find 2 neighbor nodes of a node on EDGE
4401 //================================================================================
4403 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
4404 const SMDS_MeshNode*& n1,
4405 const SMDS_MeshNode*& n2,
4409 const SMDS_MeshNode* node = edge->_nodes[0];
4410 const int shapeInd = eos._shapeID;
4411 SMESHDS_SubMesh* edgeSM = 0;
4412 if ( eos.ShapeType() == TopAbs_EDGE )
4414 edgeSM = eos._subMesh->GetSubMeshDS();
4415 if ( !edgeSM || edgeSM->NbElements() == 0 )
4416 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4420 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4421 while ( eIt->more() && !n2 )
4423 const SMDS_MeshElement* e = eIt->next();
4424 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
4425 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4428 if (!edgeSM->Contains(e)) continue;
4432 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4433 if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4435 ( iN++ ? n2 : n1 ) = nNeibor;
4438 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4442 //================================================================================
4444 * \brief Create _Curvature
4446 //================================================================================
4448 _Curvature* _Curvature::New( double avgNormProj, double avgDist )
4450 // double _r; // radius
4451 // double _k; // factor to correct node smoothed position
4452 // double _h2lenRatio; // avgNormProj / (2*avgDist)
4453 // gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
4456 if ( fabs( avgNormProj / avgDist ) > 1./200 )
4458 c = _Factory::NewCurvature();
4459 c->_r = avgDist * avgDist / avgNormProj;
4460 c->_k = avgDist * avgDist / c->_r / c->_r;
4461 //c->_k = avgNormProj / c->_r;
4462 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
4463 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
4465 c->_uv.SetCoord( 0., 0. );
4470 //================================================================================
4472 * \brief Set _curvature and _2neibors->_plnNorm by 2 neighbor nodes residing the same EDGE
4474 //================================================================================
4476 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4477 const SMDS_MeshNode* n2,
4478 const _EdgesOnShape& eos,
4479 SMESH_MesherHelper& helper)
4481 if ( eos.ShapeType() != TopAbs_EDGE )
4483 if ( _curvature && Is( SMOOTHED_C1 ))
4486 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
4487 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4488 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4492 double sumLen = vec1.Modulus() + vec2.Modulus();
4493 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4494 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4495 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4496 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4497 _curvature = _Curvature::New( avgNormProj, avgLen );
4498 // if ( _curvature )
4499 // debugMsg( _nodes[0]->GetID()
4500 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4501 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4502 // << _curvature->lenDelta(0) );
4506 if ( eos._sWOL.IsNull() )
4508 TopoDS_Edge E = TopoDS::Edge( eos._shape );
4509 // if ( SMESH_Algo::isDegenerated( E ))
4511 gp_XYZ dirE = getEdgeDir( E, _nodes[0], helper );
4512 gp_XYZ plnNorm = dirE ^ _normal;
4513 double proj0 = plnNorm * vec1;
4514 double proj1 = plnNorm * vec2;
4515 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4517 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4518 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4523 //================================================================================
4525 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4526 * this and the other _LayerEdge are inflated along a FACE or an EDGE
4528 //================================================================================
4530 gp_XYZ _LayerEdge::Copy( _LayerEdge& other,
4532 SMESH_MesherHelper& helper )
4534 _nodes = other._nodes;
4535 _normal = other._normal;
4537 _lenFactor = other._lenFactor;
4538 _cosin = other._cosin;
4539 _2neibors = other._2neibors;
4540 _curvature = other._curvature;
4541 _2neibors = other._2neibors;
4542 _maxLen = Precision::Infinite();//other._maxLen;
4546 gp_XYZ lastPos( 0,0,0 );
4547 if ( eos.SWOLType() == TopAbs_EDGE )
4549 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4550 _pos.push_back( gp_XYZ( u, 0, 0));
4552 u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4557 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4558 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4560 uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4561 lastPos.SetX( uv.X() );
4562 lastPos.SetY( uv.Y() );
4567 //================================================================================
4569 * \brief Set _cosin and _lenFactor
4571 //================================================================================
4573 double _LayerEdge::SetCosin( double cosin )
4576 cosin = Abs( _cosin );
4577 //_lenFactor = ( cosin < 1.-1e-12 ) ? 1./sqrt(1-cosin*cosin ) : 1.0;
4578 double realLenFactor;
4579 if ( cosin < 1.-1e-12 )
4581 _lenFactor = realLenFactor = 1./sqrt(1-cosin*cosin );
4586 realLenFactor = Precision::Infinite();
4589 return realLenFactor;
4592 //================================================================================
4594 * \brief Check if another _LayerEdge is a neighbor on EDGE
4596 //================================================================================
4598 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4600 return (( this->_2neibors && this->_2neibors->include( edge )) ||
4601 ( edge->_2neibors && edge->_2neibors->include( this )));
4604 //================================================================================
4606 * \brief Fills a vector<_Simplex >
4608 //================================================================================
4610 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4611 vector<_Simplex>& simplices,
4612 const set<TGeomID>& ingnoreShapes,
4613 const _SolidData* dataToCheckOri,
4617 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4618 while ( fIt->more() )
4620 const SMDS_MeshElement* f = fIt->next();
4621 const TGeomID shapeInd = f->getshapeId();
4622 if ( ingnoreShapes.count( shapeInd )) continue;
4623 const int nbNodes = f->NbCornerNodes();
4624 const int srcInd = f->GetNodeIndex( node );
4625 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4626 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4627 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4628 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4629 std::swap( nPrev, nNext );
4630 simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4634 SortSimplices( simplices );
4637 //================================================================================
4639 * \brief Set neighbor simplices side by side
4641 //================================================================================
4643 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4645 vector<_Simplex> sortedSimplices( simplices.size() );
4646 sortedSimplices[0] = simplices[0];
4648 for ( size_t i = 1; i < simplices.size(); ++i )
4650 for ( size_t j = 1; j < simplices.size(); ++j )
4651 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4653 sortedSimplices[i] = simplices[j];
4658 if ( nbFound == simplices.size() - 1 )
4659 simplices.swap( sortedSimplices );
4662 //================================================================================
4664 * \brief DEBUG. Create groups containing temporary data of _LayerEdge's
4666 //================================================================================
4668 void _ViscousBuilder::makeGroupOfLE()
4670 if (!SALOME::VerbosityActivated())
4673 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4675 if ( _sdVec[i]._n2eMap.empty() ) continue;
4677 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4678 TNode2Edge::iterator n2e;
4679 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4681 _LayerEdge* le = n2e->second;
4682 // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4683 // dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4684 // << ", " << le->_nodes[iN]->GetID() <<"])");
4686 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4687 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4692 dumpFunction( SMESH_Comment("makeNormals") << i );
4693 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4695 _LayerEdge* edge = n2e->second;
4696 SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4697 nXYZ += edge->_normal * _sdVec[i]._stepSize;
4698 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4699 << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4703 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4704 dumpCmd( "faceId1 = mesh.NbElements()" );
4705 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4706 for ( ; fExp.More(); fExp.Next() )
4708 if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4710 if ( sm->NbElements() == 0 ) continue;
4711 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4712 while ( fIt->more())
4714 const SMDS_MeshElement* e = fIt->next();
4715 SMESH_Comment cmd("mesh.AddFace([");
4716 for ( int j = 0; j < e->NbCornerNodes(); ++j )
4717 cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4722 dumpCmd( "faceId2 = mesh.NbElements()" );
4723 dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4724 << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4725 << "'%s-%s' % (faceId1+1, faceId2))");
4730 //================================================================================
4732 * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4734 //================================================================================
4736 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4738 data._geomSize = Precision::Infinite();
4739 double intersecDist;
4740 const SMDS_MeshElement* face;
4741 SMESH_MesherHelper helper( *_mesh );
4743 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4744 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4745 data._proxyMesh->GetFaces( data._solid )));
4747 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4749 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4750 if ( eos._edges.empty() )
4752 // get neighbor faces, intersection with which should not be considered since
4753 // collisions are avoided by means of smoothing
4754 set< TGeomID > neighborFaces;
4755 if ( eos._hyp.ToSmooth() )
4757 SMESH_subMeshIteratorPtr subIt =
4758 eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4759 while ( subIt->more() )
4761 SMESH_subMesh* sm = subIt->next();
4762 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4763 while ( const TopoDS_Shape* face = fIt->next() )
4764 neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4767 // find intersections
4768 double thinkness = eos._hyp.GetTotalThickness();
4769 for ( size_t i = 0; i < eos._edges.size(); ++i )
4771 if ( eos._edges[i]->_nodes.size() < 2 ) continue;
4772 eos._edges[i]->SetMaxLen( thinkness );
4773 eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4774 if ( intersecDist > 0 && face )
4776 data._geomSize = Min( data._geomSize, intersecDist );
4777 if ( !neighborFaces.count( face->getshapeId() ))
4778 eos[i]->SetMaxLen( Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. )));
4783 data._maxThickness = 0;
4784 data._minThickness = 1e100;
4785 list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
4786 for ( ; hyp != data._hyps.end(); ++hyp )
4788 data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
4789 data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
4792 // Limit inflation step size by geometry size found by intersecting
4793 // normals of _LayerEdge's with mesh faces
4794 if ( data._stepSize > 0.3 * data._geomSize )
4795 limitStepSize( data, 0.3 * data._geomSize );
4797 if ( data._stepSize > data._minThickness )
4798 limitStepSize( data, data._minThickness );
4801 // -------------------------------------------------------------------------
4802 // Detect _LayerEdge which can't intersect with opposite or neighbor layer,
4803 // so no need in detecting intersection at each inflation step
4804 // -------------------------------------------------------------------------
4806 int nbSteps = data._maxThickness / data._stepSize;
4807 if ( nbSteps < 3 || nbSteps * data._n2eMap.size() < 100000 )
4810 vector< const SMDS_MeshElement* > closeFaces;
4813 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4815 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4816 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
4819 for ( size_t i = 0; i < eos.size(); ++i )
4821 SMESH_NodeXYZ p( eos[i]->_nodes[0] );
4822 double radius = data._maxThickness + 2 * eos[i]->_maxLen;
4824 searcher->GetElementsInSphere( p, radius, SMDSAbs_Face, closeFaces );
4826 bool toIgnore = true;
4827 for ( size_t iF = 0; iF < closeFaces.size() && toIgnore; ++iF )
4828 if ( !( toIgnore = ( closeFaces[ iF ]->getshapeId() == eos._shapeID ||
4829 data._ignoreFaceIds.count( closeFaces[ iF ]->getshapeId() ))))
4831 // check if a _LayerEdge will inflate in a direction opposite to a direction
4832 // toward a close face
4833 bool allBehind = true;
4834 for ( int iN = 0; iN < closeFaces[ iF ]->NbCornerNodes() && allBehind; ++iN )
4836 SMESH_NodeXYZ pi( closeFaces[ iF ]->GetNode( iN ));
4837 allBehind = (( pi - p ) * eos[i]->_normal < 0.1 * data._stepSize );
4839 toIgnore = allBehind;
4843 if ( toIgnore ) // no need to detect intersection
4845 eos[i]->Set( _LayerEdge::INTERSECTED );
4851 debugMsg( "Nb LE to intersect " << data._n2eMap.size()-nbDetected << ", ignore " << nbDetected );
4856 //================================================================================
4858 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4860 //================================================================================
4862 bool _ViscousBuilder::inflate(_SolidData& data)
4864 SMESH_MesherHelper helper( *_mesh );
4866 const double tgtThick = data._maxThickness;
4868 if ( data._stepSize < 1. )
4869 data._epsilon = data._stepSize * 1e-7;
4871 debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4874 findCollisionEdges( data, helper );
4876 limitMaxLenByCurvature( data, helper );
4880 // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4881 for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4882 if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4883 data._edgesOnShape[i]._edges.size() > 0 &&
4884 data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4886 data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4887 data._edgesOnShape[i]._edges[0]->Block( data );
4890 const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4892 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4893 int nbSteps = 0, nbRepeats = 0;
4894 while ( avgThick < 0.99 )
4896 // new target length
4897 double prevThick = curThick;
4898 curThick += data._stepSize;
4899 if ( curThick > tgtThick )
4901 curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4905 double stepSize = curThick - prevThick;
4906 updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4908 // Elongate _LayerEdge's
4909 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4910 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4912 _EdgesOnShape& eos = data._edgesOnShape[iS];
4913 if ( eos._edges.empty() ) continue;
4915 const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4916 for ( size_t i = 0; i < eos._edges.size(); ++i )
4918 eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4923 if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4926 // Improve and check quality
4927 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4931 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4932 debugMsg("NOT INVALIDATED STEP!");
4933 return error("Smoothing failed", data._index);
4935 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4936 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4938 _EdgesOnShape& eos = data._edgesOnShape[iS];
4939 for ( size_t i = 0; i < eos._edges.size(); ++i )
4940 eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4944 break; // no more inflating possible
4948 // Evaluate achieved thickness
4950 int nbActiveEdges = 0;
4951 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4953 _EdgesOnShape& eos = data._edgesOnShape[iS];
4954 if ( eos._edges.empty() ) continue;
4956 const double shapeTgtThick = eos._hyp.GetTotalThickness();
4957 for ( size_t i = 0; i < eos._edges.size(); ++i )
4959 if ( eos._edges[i]->_nodes.size() > 1 )
4960 avgThick += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4963 nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4966 avgThick /= data._n2eMap.size();
4967 debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4969 #ifdef BLOCK_INFLATION
4970 if ( nbActiveEdges == 0 )
4972 debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4976 if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4978 debugMsg( "-- Stop inflation since "
4979 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4980 << tgtThick * avgThick << " ) * " << safeFactor );
4986 limitStepSize( data, 0.25 * distToIntersection );
4987 if ( data._stepSizeNodes[0] )
4988 data._stepSize = data._stepSizeCoeff *
4989 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4991 } // while ( avgThick < 0.99 )
4994 return error("failed at the very first inflation step", data._index);
4996 if ( avgThick < 0.99 )
4998 if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
5000 data._proxyMesh->_warning.reset
5001 ( new SMESH_ComputeError (COMPERR_WARNING,
5002 SMESH_Comment("Thickness ") << tgtThick <<
5003 " of viscous layers not reached,"
5004 " average reached thickness is " << avgThick*tgtThick));
5008 // Restore position of src nodes moved by inflation on _noShrinkShapes
5009 dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
5010 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5012 _EdgesOnShape& eos = data._edgesOnShape[iS];
5013 if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
5014 for ( size_t i = 0; i < eos._edges.size(); ++i )
5016 restoreNoShrink( *eos._edges[ i ] );
5021 return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
5024 //================================================================================
5026 * \brief Improve quality of layer inner surface and check intersection
5028 //================================================================================
5030 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
5032 double & distToIntersection)
5034 if ( data._nbShapesToSmooth == 0 )
5035 return true; // no shapes needing smoothing
5037 bool moved, improved;
5039 vector< _LayerEdge* > movedEdges, badEdges;
5040 vector< _EdgesOnShape* > eosC1; // C1 continues shapes
5041 vector< bool > isConcaveFace;
5043 SMESH_MesherHelper helper(*_mesh);
5044 Handle(ShapeAnalysis_Surface) surface;
5047 for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
5049 const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
5051 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5053 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5054 if ( !eos._toSmooth ||
5055 eos.ShapeType() != shapeType ||
5056 eos._edges.empty() )
5059 // already smoothed?
5060 // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
5061 // if ( !toSmooth ) continue;
5063 if ( !eos._hyp.ToSmooth() )
5065 // smooth disabled by the user; check validy only
5066 if ( !isFace ) continue;
5068 for ( size_t i = 0; i < eos._edges.size(); ++i )
5070 _LayerEdge* edge = eos._edges[i];
5071 for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
5072 if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
5074 // debugMsg( "-- Stop inflation. Bad simplex ("
5075 // << " "<< edge->_nodes[0]->GetID()
5076 // << " "<< edge->_nodes.back()->GetID()
5077 // << " "<< edge->_simplices[iF]._nPrev->GetID()
5078 // << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
5080 badEdges.push_back( edge );
5083 if ( !badEdges.empty() )
5087 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5091 continue; // goto the next EDGE or FACE
5095 if ( eos.SWOLType() == TopAbs_FACE )
5097 if ( !F.IsSame( eos._sWOL )) {
5098 F = TopoDS::Face( eos._sWOL );
5099 helper.SetSubShape( F );
5100 surface = helper.GetSurface( F );
5105 F.Nullify(); surface.Nullify();
5107 const TGeomID sInd = eos._shapeID;
5109 // perform smoothing
5111 if ( eos.ShapeType() == TopAbs_EDGE )
5113 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
5115 if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
5117 // smooth on EDGE's (normally we should not get here)
5121 for ( size_t i = 0; i < eos._edges.size(); ++i )
5123 moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
5125 dumpCmd( SMESH_Comment("# end step ")<<step);
5127 while ( moved && step++ < 5 );
5132 else // smooth on FACE
5135 eosC1.push_back( & eos );
5136 eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
5139 isConcaveFace.resize( eosC1.size() );
5140 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5142 isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID );
5144 if ( eosC1[ iEOS ]->_mapper2D )
5146 // compute node position by boundary node position in structured mesh
5147 dumpFunction(SMESH_Comment("map2dS")<<data._index<<"_Fa"<<eos._shapeID
5148 <<"_InfStep"<<infStep);
5150 eosC1[ iEOS ]->_mapper2D->ComputeNodePositions();
5152 for ( _LayerEdge* le : eosC1[ iEOS ]->_edges )
5153 le->_pos.back() = SMESH_NodeXYZ( le->_nodes.back() );
5159 for ( _LayerEdge* le : eosC1[ iEOS ]->_edges )
5160 if ( le->Is( _LayerEdge::MOVED ) ||
5161 le->Is( _LayerEdge::NEAR_BOUNDARY ))
5162 movedEdges.push_back( le );
5164 makeOffsetSurface( *eosC1[ iEOS ], helper );
5167 int step = 0, stepLimit = 5, nbBad = 0;
5168 while (( ++step <= stepLimit ) || improved )
5170 int oldBadNb = nbBad;
5173 #ifdef INCREMENTAL_SMOOTH
5174 // smooth moved only
5175 if ( !movedEdges.empty() )
5176 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
5177 <<"_InfStep"<<infStep<<"_"<<step); // debug
5178 bool findBest = false; // ( step == stepLimit );
5179 for ( size_t i = 0; i < movedEdges.size(); ++i )
5181 movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
5182 if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
5183 badEdges.push_back( movedEdges[i] );
5187 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
5188 <<"_InfStep"<<infStep<<"_"<<step); // debug
5189 bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
5190 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5192 if ( eosC1[ iEOS ]->_mapper2D )
5194 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
5195 for ( size_t i = 0; i < edges.size(); ++i )
5197 edges[i]->Unset( _LayerEdge::SMOOTHED );
5198 if ( edges[i]->Smooth( step, findBest, false ) > 0 )
5199 badEdges.push_back( eos._edges[i] );
5203 nbBad = badEdges.size();
5206 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
5208 if ( !badEdges.empty() && step >= stepLimit / 2 )
5210 if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
5213 // resolve hard smoothing situation around concave VERTEXes
5214 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5216 vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
5217 for ( size_t i = 0; i < eosCoVe.size(); ++i )
5218 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
5221 // look for the best smooth of _LayerEdge's neighboring badEdges
5223 for ( size_t i = 0; i < badEdges.size(); ++i )
5225 _LayerEdge* ledge = badEdges[i];
5226 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
5228 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
5229 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
5231 ledge->Unset( _LayerEdge::SMOOTHED );
5232 nbBad += ledge->Smooth( step, true, /*findBest=*/true );
5234 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
5237 if ( nbBad == oldBadNb &&
5239 step < stepLimit ) // smooth w/o check of validity
5242 dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
5243 <<"_InfStep"<<infStep<<"_"<<step); // debug
5244 for ( size_t i = 0; i < movedEdges.size(); ++i )
5246 movedEdges[i]->SmoothWoCheck();
5248 if ( stepLimit < 9 )
5252 improved = ( nbBad < oldBadNb );
5256 if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
5257 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5259 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
5262 } // smoothing steps
5264 // project -- to prevent intersections or to fix bad simplices
5265 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5267 if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
5268 putOnOffsetSurface( *eosC1[ iEOS ], -infStep, eosC1 );
5271 //if ( !badEdges.empty() )
5274 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5276 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5278 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5280 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5281 edge->CheckNeiborsOnBoundary( & badEdges );
5282 if (( nbBad > 0 ) ||
5283 ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
5285 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5286 gp_XYZ prevXYZ = edge->PrevCheckPos();
5287 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5288 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5290 debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
5291 << " "<< tgtXYZ._node->GetID()
5292 << " "<< edge->_simplices[j]._nPrev->GetID()
5293 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5294 badEdges.push_back( edge );
5301 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5302 nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5308 } // // smooth on FACE's
5310 } // smooth on [ EDGEs, FACEs ]
5312 // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
5314 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5316 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5317 if ( eos.ShapeType() == TopAbs_FACE ||
5318 eos._edges.empty() ||
5319 !eos._sWOL.IsNull() )
5323 for ( size_t i = 0; i < eos._edges.size(); ++i )
5325 _LayerEdge* edge = eos._edges[i];
5326 if ( edge->_nodes.size() < 2 ) continue;
5327 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5328 //SMESH_TNodeXYZ prevXYZ = edge->_nodes[0];
5329 gp_XYZ prevXYZ = edge->PrevCheckPos( &eos );
5330 //const gp_XYZ& prevXYZ = edge->PrevPos();
5331 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5332 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5334 debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
5335 << " "<< tgtXYZ._node->GetID()
5336 << " "<< edge->_simplices[j]._nPrev->GetID()
5337 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5338 badEdges.push_back( edge );
5343 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5345 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5351 // Check if the last segments of _LayerEdge intersects 2D elements;
5352 // checked elements are either temporary faces or faces on surfaces w/o the layers
5354 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
5355 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
5356 data._proxyMesh->GetFaces( data._solid )) );
5358 #ifdef BLOCK_INFLATION
5359 const bool toBlockInfaltion = true;
5361 const bool toBlockInfaltion = false;
5363 distToIntersection = Precision::Infinite();
5365 const SMDS_MeshElement* intFace = 0;
5366 const SMDS_MeshElement* closestFace = 0;
5368 bool is1stBlocked = true; // dbg
5369 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5371 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5372 if ( eos._edges.empty() || !eos._sWOL.IsNull() )
5374 for ( size_t i = 0; i < eos._edges.size(); ++i )
5376 if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
5377 eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
5379 if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5382 // commented due to "Illegal hash-positionPosition" error in NETGEN
5383 // on Debian60 on viscous_layers_01/B2 case
5384 // Collision; try to deflate _LayerEdge's causing it
5385 // badEdges.clear();
5386 // badEdges.push_back( eos._edges[i] );
5387 // eosC1[0] = & eos;
5388 // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5392 // badEdges.clear();
5393 // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5395 // if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5397 // const SMDS_MeshElement* srcFace =
5398 // eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5399 // SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5400 // while ( nIt->more() )
5402 // const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5403 // TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5404 // if ( n2e != data._n2eMap.end() )
5405 // badEdges.push_back( n2e->second );
5408 // nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5413 // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5420 SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
5425 const bool isShorterDist = ( distToIntersection > dist );
5426 if ( toBlockInfaltion || isShorterDist )
5428 // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
5429 // lying on this _ConvexFace
5430 if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
5431 if ( convFace->_isTooCurved && convFace->_subIdToEOS.count ( eos._shapeID ))
5434 // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
5435 // ( avoid limiting the thickness on the case of issue 22576)
5436 if ( intFace->getshapeId() == eos._shapeID )
5439 // ignore intersection with intFace of an adjacent FACE
5440 if ( dist > 0.01 * eos._edges[i]->_len )
5442 bool toIgnore = false;
5443 if ( eos._toSmooth )
5445 const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
5446 if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
5448 TopExp_Explorer sub( eos._shape,
5449 eos.ShapeType() == TopAbs_FACE ? TopAbs_EDGE : TopAbs_VERTEX );
5450 for ( ; !toIgnore && sub.More(); sub.Next() )
5451 // is adjacent - has a common EDGE or VERTEX
5452 toIgnore = ( helper.IsSubShape( sub.Current(), S ));
5454 if ( toIgnore ) // check angle between normals
5457 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
5458 toIgnore = ( normal * eos._edges[i]->_normal > -0.5 );
5462 if ( !toIgnore ) // check if the edge is a neighbor of intFace
5464 for ( size_t iN = 0; !toIgnore && iN < eos._edges[i]->_neibors.size(); ++iN )
5466 int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
5467 toIgnore = ( nInd >= 0 );
5474 // intersection not ignored
5477 if ( eos._edges[i]->_maxLen < 0.99 * eos._hyp.GetTotalThickness() ) // limited length
5478 minDist = eos._edges[i]->_len * theThickToIntersection;
5480 if ( toBlockInfaltion && dist < minDist )
5482 if ( is1stBlocked ) { is1stBlocked = false; // debug
5483 dumpFunction(SMESH_Comment("blockIntersected") <<data._index<<"_InfStep"<<infStep);
5485 eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5486 eos._edges[i]->Block( data ); // not to inflate
5488 //if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5490 // block _LayerEdge's, on top of which intFace is
5491 if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5493 const SMDS_MeshElement* srcFace = f->_srcFace;
5494 SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5495 while ( nIt->more() )
5497 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5498 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5499 if ( n2e != data._n2eMap.end() )
5500 n2e->second->Block( data );
5506 if ( isShorterDist )
5508 distToIntersection = dist;
5510 closestFace = intFace;
5513 } // if ( toBlockInfaltion || isShorterDist )
5514 } // loop on eos._edges
5515 } // loop on data._edgesOnShape
5517 if ( !is1stBlocked )
5522 if ( closestFace && le )
5525 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5526 cout << "#Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5527 << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5528 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5529 << ") distance = " << distToIntersection<< endl;
5536 //================================================================================
5538 * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5539 * \param [in,out] badSmooEdges - _LayerEdge's to fix
5540 * \return int - resulting nb of bad _LayerEdge's
5542 //================================================================================
5544 int _ViscousBuilder::invalidateBadSmooth( _SolidData& data,
5545 SMESH_MesherHelper& helper,
5546 vector< _LayerEdge* >& badSmooEdges,
5547 vector< _EdgesOnShape* >& eosC1,
5550 if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5552 dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5555 INVALIDATED = _LayerEdge::UNUSED_FLAG,
5556 TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5557 ADDED = _LayerEdge::UNUSED_FLAG * 4
5559 data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5562 bool haveInvalidated = true;
5563 while ( haveInvalidated )
5565 haveInvalidated = false;
5566 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5568 _LayerEdge* edge = badSmooEdges[i];
5569 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5571 bool invalidated = false;
5572 if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5574 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5575 edge->Block( data );
5576 edge->Set( INVALIDATED );
5577 edge->Unset( TO_INVALIDATE );
5579 haveInvalidated = true;
5582 // look for _LayerEdge's of bad _simplices
5584 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5585 gp_XYZ prevXYZ1 = edge->PrevCheckPos( eos );
5586 //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5587 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5589 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5590 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5594 _LayerEdge* ee[2] = { 0,0 };
5595 for ( size_t iN = 0; iN < edge->_neibors.size() && !ee[1] ; ++iN )
5596 if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5597 ee[ ee[0] != 0 ] = edge->_neibors[iN];
5599 int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5600 while ( maxNbSteps > edge->NbSteps() && isBad )
5603 for ( int iE = 0; iE < 2; ++iE )
5605 if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5606 ee[ iE ]->NbSteps() > 1 )
5608 _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5609 ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5610 ee[ iE ]->Block( data );
5611 ee[ iE ]->Set( INVALIDATED );
5612 haveInvalidated = true;
5615 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5616 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5620 if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5621 if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5622 ee[0]->Set( ADDED );
5623 ee[1]->Set( ADDED );
5626 ee[0]->Set( TO_INVALIDATE );
5627 ee[1]->Set( TO_INVALIDATE );
5631 if ( !invalidated && nbBad > 0 && edge->NbSteps() > 1 )
5633 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5634 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5635 edge->Block( data );
5636 edge->Set( INVALIDATED );
5637 edge->Unset( TO_INVALIDATE );
5638 haveInvalidated = true;
5640 } // loop on badSmooEdges
5641 } // while ( haveInvalidated )
5643 // re-smooth on analytical EDGEs
5644 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5646 _LayerEdge* edge = badSmooEdges[i];
5647 if ( !edge->Is( INVALIDATED )) continue;
5649 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5650 if ( eos->ShapeType() == TopAbs_VERTEX )
5652 PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5653 while ( const TopoDS_Shape* e = eIt->next() )
5654 if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5655 if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5657 // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5658 // if ( eoe->SWOLType() == TopAbs_FACE ) {
5659 // F = TopoDS::Face( eoe->_sWOL );
5660 // surface = helper.GetSurface( F );
5662 // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5663 eoe->_edgeSmoother->_anaCurve.Nullify();
5669 // check result of invalidation
5672 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5674 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5676 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5677 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5678 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5679 gp_XYZ prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5680 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5681 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5684 debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5685 << " "<< tgtXYZ._node->GetID()
5686 << " "<< edge->_simplices[j]._nPrev->GetID()
5687 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5696 //================================================================================
5698 * \brief Create an offset surface
5700 //================================================================================
5702 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5704 if ( eos._offsetSurf.IsNull() ||
5705 eos._edgeForOffset == 0 ||
5706 eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5709 Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5712 gp_Pnt tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5713 /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5714 eos._offsetValue = baseSurface->Gap();
5716 eos._offsetSurf.Nullify();
5720 BRepOffsetAPI_MakeOffsetShape offsetMaker;
5721 offsetMaker.PerformByJoin( eos._shape, -eos._offsetValue, Precision::Confusion() );
5722 if ( !offsetMaker.IsDone() ) return;
5724 TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5725 if ( !fExp.More() ) return;
5727 TopoDS_Face F = TopoDS::Face( fExp.Current() );
5728 Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5729 if ( surf.IsNull() ) return;
5731 eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5733 catch ( Standard_Failure& )
5738 //================================================================================
5740 * \brief Put nodes of a curved FACE to its offset surface
5742 //================================================================================
5744 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape& eos,
5746 vector< _EdgesOnShape* >& eosC1,
5750 _EdgesOnShape * eof = & eos;
5751 if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5754 for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5756 if ( eosC1[i]->_offsetSurf.IsNull() ||
5757 eosC1[i]->ShapeType() != TopAbs_FACE ||
5758 eosC1[i]->_edgeForOffset == 0 ||
5759 eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5761 if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5766 eof->_offsetSurf.IsNull() ||
5767 eof->ShapeType() != TopAbs_FACE ||
5768 eof->_edgeForOffset == 0 ||
5769 eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5772 double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5773 bool neighborHasRiskySWOL = false;
5774 for ( size_t i = 0; i < eos._edges.size(); ++i )
5776 _LayerEdge* edge = eos._edges[i];
5777 edge->Unset( _LayerEdge::MARKED );
5778 if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5780 if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5782 if ( !edge->Is( _LayerEdge::UPD_NORMAL_CONV ))
5785 else if ( moveAll == _LayerEdge::RISKY_SWOL )
5787 if ( !edge->Is( _LayerEdge::RISKY_SWOL ) ||
5791 else if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5794 int nbBlockedAround = 0;
5795 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5797 nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5798 if ( edge->_neibors[iN]->Is( _LayerEdge::RISKY_SWOL ) &&
5799 edge->_neibors[iN]->_cosin > 0 )
5800 neighborHasRiskySWOL = true;
5802 if ( nbBlockedAround > 1 )
5805 gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5806 gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5807 if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5808 edge->_curvature->_uv = uv;
5809 if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5811 gp_XYZ newP = eof->_offsetSurf->Value( uv ).XYZ();
5812 gp_XYZ prevP = edge->PrevCheckPos();
5815 for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5817 ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5821 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5822 n->setXYZ( newP.X(), newP.Y(), newP.Z());
5823 edge->_pos.back() = newP;
5825 edge->Set( _LayerEdge::MARKED );
5826 if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5828 edge->_normal = ( newP - prevP ).Normalized();
5830 // if ( edge->_len < eof->_offsetValue )
5831 // edge->_len = eof->_offsetValue;
5833 if ( !eos._sWOL.IsNull() ) // RISKY_SWOL
5835 double change = eof->_offsetSurf->Gap() / eof->_offsetValue;
5836 if (( newP - tgtP.XYZ() ) * edge->_normal < 0 )
5837 change = 1 - change;
5839 change = 1 + change;
5840 gp_XYZ shitfVec = tgtP.XYZ() - SMESH_NodeXYZ( edge->_nodes[0] );
5841 gp_XYZ newShiftVec = shitfVec * change;
5842 double shift = edge->_normal * shitfVec;
5843 double newShift = edge->_normal * newShiftVec;
5844 newP = tgtP.XYZ() + edge->_normal * ( newShift - shift );
5846 uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, newP, preci );
5847 if ( eof->_offsetSurf->Gap() < edge->_len )
5849 edge->_curvature->_uv = uv;
5850 newP = eof->_offsetSurf->Value( uv ).XYZ();
5852 n->setXYZ( newP.X(), newP.Y(), newP.Z());
5853 if ( !edge->UpdatePositionOnSWOL( n, /*tol=*/10 * edge->_len / ( edge->NbSteps() + 1 ),
5854 eos, eos.GetData().GetHelper() ))
5856 debugMsg("UpdatePositionOnSWOL fails in putOnOffsetSurface()" );
5862 if (SALOME::VerbosityActivated())
5864 // dumpMove() for debug
5866 for ( ; i < eos._edges.size(); ++i )
5867 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5869 if ( i < eos._edges.size() )
5871 dumpFunction(SMESH_Comment("putOnOffsetSurface_") << eos.ShapeTypeLetter() << eos._shapeID
5872 << "_InfStep" << infStep << "_" << Abs( smooStep ));
5873 for ( ; i < eos._edges.size(); ++i )
5875 if ( eos._edges[i]->Is( _LayerEdge::MARKED )) {
5876 dumpMove( eos._edges[i]->_nodes.back() );
5883 _ConvexFace* cnvFace;
5884 if ( moveAll != _LayerEdge::UPD_NORMAL_CONV &&
5885 eos.ShapeType() == TopAbs_FACE &&
5886 (cnvFace = eos.GetData().GetConvexFace( eos._shapeID )) &&
5887 !cnvFace->_normalsFixedOnBorders )
5889 // put on the surface nodes built on FACE boundaries
5890 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5891 while ( smIt->more() )
5893 SMESH_subMesh* sm = smIt->next();
5894 _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5895 if ( !subEOS->_sWOL.IsNull() ) continue;
5896 if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5898 putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::UPD_NORMAL_CONV );
5900 cnvFace->_normalsFixedOnBorders = true;
5905 // negative smooStep means "final step", where we don't treat RISKY_SWOL edges
5906 // as edges based on FACE are a bit late comparing with them
5907 if ( smooStep >= 0 &&
5908 neighborHasRiskySWOL &&
5909 moveAll != _LayerEdge::RISKY_SWOL &&
5910 eos.ShapeType() == TopAbs_FACE )
5912 // put on the surface nodes built on FACE boundaries
5913 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5914 while ( smIt->more() )
5916 SMESH_subMesh* sm = smIt->next();
5917 _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5918 if ( subEOS->_sWOL.IsNull() ) continue;
5919 if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5921 putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::RISKY_SWOL );
5926 //================================================================================
5928 * \brief Return a curve of the EDGE to be used for smoothing and arrange
5929 * _LayerEdge's to be in a consequent order
5931 //================================================================================
5933 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge& E,
5935 SMESH_MesherHelper& helper)
5937 SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5939 TopLoc_Location loc; double f,l;
5941 Handle(Geom_Line) line;
5942 Handle(Geom_Circle) circle;
5943 bool isLine, isCirc;
5944 if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5946 // check if the EDGE is a line
5947 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5948 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5949 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5951 line = Handle(Geom_Line)::DownCast( curve );
5952 circle = Handle(Geom_Circle)::DownCast( curve );
5953 isLine = (!line.IsNull());
5954 isCirc = (!circle.IsNull());
5956 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5958 isLine = SMESH_Algo::IsStraight( E );
5961 line = new Geom_Line( gp::OX() ); // only type does matter
5963 if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5968 else //////////////////////////////////////////////////////////////////////// 2D case
5970 if ( !eos._isRegularSWOL ) // 23190
5973 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5975 // check if the EDGE is a line
5976 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5977 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5978 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5980 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
5981 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5982 isLine = (!line2d.IsNull());
5983 isCirc = (!circle2d.IsNull());
5985 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5988 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5989 while ( nIt->more() )
5990 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5991 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5993 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5994 for ( int i = 0; i < 2 && !isLine; ++i )
5995 isLine = ( size.Coord( i+1 ) <= lineTol );
5997 if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
6003 line = new Geom_Line( gp::OX() ); // only type does matter
6007 gp_Pnt2d p = circle2d->Location();
6008 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
6009 circle = new Geom_Circle( ax, 1.); // only center position does matter
6018 return Handle(Geom_Curve)();
6021 //================================================================================
6023 * \brief Smooth edges on EDGE
6025 //================================================================================
6027 bool _Smoother1D::Perform(_SolidData& data,
6028 Handle(ShapeAnalysis_Surface)& surface,
6029 const TopoDS_Face& F,
6030 SMESH_MesherHelper& helper )
6032 if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
6035 findEdgesToSmooth();
6037 return smoothAnalyticEdge( data, surface, F, helper );
6039 return smoothComplexEdge ( data, surface, F, helper );
6042 //================================================================================
6044 * \brief Find edges to smooth
6046 //================================================================================
6048 void _Smoother1D::findEdgesToSmooth()
6050 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6051 for ( int iEnd = 0; iEnd < 2; ++iEnd )
6052 if ( leOnV[iEnd]->Is( _LayerEdge::NORMAL_UPDATED ))
6053 _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6055 _eToSmooth[0].first = _eToSmooth[0].second = 0;
6057 for ( size_t i = 0; i < _eos.size(); ++i )
6059 if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
6061 if ( needSmoothing( _leOnV[0]._cosin,
6062 _eos[i]->_len * leOnV[0]->_lenFactor, _curveLen * _leParams[i] ) ||
6065 _eos[i]->Set( _LayerEdge::TO_SMOOTH );
6069 _eToSmooth[0].second = i+1;
6072 _eToSmooth[1].first = _eToSmooth[1].second = _eos.size();
6074 for ( int i = _eos.size() - 1; i >= _eToSmooth[0].second; --i )
6076 if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
6078 if ( needSmoothing( _leOnV[1]._cosin,
6079 _eos[i]->_len * leOnV[1]->_lenFactor, _curveLen * ( 1.-_leParams[i] )) ||
6081 _eos[i]->Set( _LayerEdge::TO_SMOOTH );
6085 _eToSmooth[1].first = i;
6089 //================================================================================
6091 * \brief Check if iE-th _LayerEdge needs smoothing
6093 //================================================================================
6095 bool _Smoother1D::isToSmooth( int iE )
6097 SMESH_NodeXYZ pi( _eos[iE]->_nodes[0] );
6098 SMESH_NodeXYZ p0( _eos[iE]->_2neibors->srcNode(0) );
6099 SMESH_NodeXYZ p1( _eos[iE]->_2neibors->srcNode(1) );
6100 gp_XYZ seg0 = pi - p0;
6101 gp_XYZ seg1 = p1 - pi;
6102 gp_XYZ tangent = seg0 + seg1;
6103 double tangentLen = tangent.Modulus();
6104 double segMinLen = Min( seg0.Modulus(), seg1.Modulus() );
6105 if ( tangentLen < std::numeric_limits<double>::min() )
6107 tangent /= tangentLen;
6109 for ( size_t i = 0; i < _eos[iE]->_neibors.size(); ++i )
6111 _LayerEdge* ne = _eos[iE]->_neibors[i];
6112 if ( !ne->Is( _LayerEdge::TO_SMOOTH ) ||
6113 ne->_nodes.size() < 2 ||
6114 ne->_nodes[0]->GetPosition()->GetDim() != 2 )
6116 gp_XYZ edgeVec = SMESH_NodeXYZ( ne->_nodes.back() ) - SMESH_NodeXYZ( ne->_nodes[0] );
6117 double proj = edgeVec * tangent;
6118 if ( needSmoothing( 1., proj, segMinLen ))
6124 //================================================================================
6126 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
6128 //================================================================================
6130 bool _Smoother1D::smoothAnalyticEdge( _SolidData& data,
6131 Handle(ShapeAnalysis_Surface)& surface,
6132 const TopoDS_Face& F,
6133 SMESH_MesherHelper& helper)
6135 if ( !isAnalytic() ) return false;
6137 size_t iFrom = 0, iTo = _eos._edges.size();
6139 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
6141 if ( F.IsNull() ) // 3D
6143 SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
6144 SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
6145 //const gp_XYZ lineDir = pSrc1 - pSrc0;
6146 //_LayerEdge* vLE0 = getLEdgeOnV( 0 );
6147 //_LayerEdge* vLE1 = getLEdgeOnV( 1 );
6148 // bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
6149 // vLE0->Is( _LayerEdge::BLOCKED ) ||
6150 // vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
6151 // vLE1->Is( _LayerEdge::BLOCKED ));
6152 for ( int iEnd = 0; iEnd < 2; ++iEnd )
6154 iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
6155 if ( iFrom >= iTo ) continue;
6156 SMESH_TNodeXYZ p0( _eos[iFrom]->_2neibors->tgtNode(0) );
6157 SMESH_TNodeXYZ p1( _eos[iTo-1]->_2neibors->tgtNode(1) );
6158 double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
6159 double param1 = _leParams[ iTo ];
6160 for ( size_t i = iFrom; i < iTo; ++i )
6162 _LayerEdge* edge = _eos[i];
6163 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
6164 double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
6165 gp_XYZ newPos = p0 * ( 1. - param ) + p1 * param;
6167 // if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
6169 // gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
6170 // double shift = ( lineDir * ( newPos - pSrc0 ) -
6171 // lineDir * ( curPos - pSrc0 ));
6172 // newPos = curPos + lineDir * shift / lineDir.SquareModulus();
6174 if ( edge->Is( _LayerEdge::BLOCKED ))
6176 SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
6177 double curThick = pSrc.SquareDistance( tgtNode );
6178 double newThink = ( pSrc - newPos ).SquareModulus();
6179 if ( newThink > curThick )
6182 edge->_pos.back() = newPos;
6183 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
6184 dumpMove( tgtNode );
6190 _LayerEdge* eV0 = getLEdgeOnV( 0 );
6191 _LayerEdge* eV1 = getLEdgeOnV( 1 );
6192 gp_XY uvV0 = eV0->LastUV( F, *data.GetShapeEdges( eV0 ));
6193 gp_XY uvV1 = eV1->LastUV( F, *data.GetShapeEdges( eV1 ));
6194 if ( eV0->_nodes.back() == eV1->_nodes.back() ) // closed edge
6196 int iPeriodic = helper.GetPeriodicIndex();
6197 if ( iPeriodic == 1 || iPeriodic == 2 )
6199 uvV1.SetCoord( iPeriodic, helper.GetOtherParam( uvV1.Coord( iPeriodic )));
6200 if ( uvV0.Coord( iPeriodic ) > uvV1.Coord( iPeriodic ))
6201 std::swap( uvV0, uvV1 );
6204 for ( int iEnd = 0; iEnd < 2; ++iEnd )
6206 iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
6207 if ( iFrom >= iTo ) continue;
6208 _LayerEdge* e0 = _eos[iFrom]->_2neibors->_edges[0];
6209 _LayerEdge* e1 = _eos[iTo-1]->_2neibors->_edges[1];
6210 gp_XY uv0 = ( e0 == eV0 ) ? uvV0 : e0->LastUV( F, _eos );
6211 gp_XY uv1 = ( e1 == eV1 ) ? uvV1 : e1->LastUV( F, _eos );
6212 double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
6213 double param1 = _leParams[ iTo ];
6214 gp_XY rangeUV = uv1 - uv0;
6215 for ( size_t i = iFrom; i < iTo; ++i )
6217 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6218 double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
6219 gp_XY newUV = uv0 + param * rangeUV;
6221 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
6222 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6223 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
6224 dumpMove( tgtNode );
6226 if ( SMDS_FacePositionPtr pos = tgtNode->GetPosition() ) // NULL if F is noShrink
6228 pos->SetUParameter( newUV.X() );
6229 pos->SetVParameter( newUV.Y() );
6232 gp_XYZ newUV0( newUV.X(), newUV.Y(), 0 );
6234 if ( !_eos[i]->Is( _LayerEdge::SMOOTHED ))
6236 _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
6237 if ( _eos[i]->_pos.size() > 2 )
6239 // modify previous positions to make _LayerEdge less sharply bent
6240 vector<gp_XYZ>& uvVec = _eos[i]->_pos;
6241 const gp_XYZ uvShift = newUV0 - uvVec.back();
6242 const double len2 = ( uvVec.back() - uvVec[ 0 ] ).SquareModulus();
6243 int iPrev = uvVec.size() - 2;
6246 double r = ( uvVec[ iPrev ] - uvVec[0] ).SquareModulus() / len2;
6247 uvVec[ iPrev ] += uvShift * r;
6252 _eos[i]->_pos.back() = newUV0;
6259 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
6261 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
6262 gp_Pnt center3D = circle->Location();
6264 if ( F.IsNull() ) // 3D
6266 if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
6267 return true; // closed EDGE - nothing to do
6269 // circle is a real curve of EDGE
6270 gp_Circ circ = circle->Circ();
6272 // new center is shifted along its axis
6273 const gp_Dir& axis = circ.Axis().Direction();
6274 _LayerEdge* e0 = getLEdgeOnV(0);
6275 _LayerEdge* e1 = getLEdgeOnV(1);
6276 SMESH_TNodeXYZ p0 = e0->_nodes.back();
6277 SMESH_TNodeXYZ p1 = e1->_nodes.back();
6278 double shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
6279 double shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
6280 gp_Pnt newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
6282 double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
6284 gp_Ax2 newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
6285 gp_Circ newCirc( newAxis, newRadius );
6286 gp_Vec vecC1 ( newCenter, p1 );
6288 double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
6292 for ( size_t i = 0; i < _eos.size(); ++i )
6294 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6295 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6296 double u = uLast * _leParams[i];
6297 gp_Pnt p = ElCLib::Value( u, newCirc );
6298 _eos._edges[i]->_pos.back() = p.XYZ();
6300 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
6301 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6302 dumpMove( tgtNode );
6308 const gp_XY center( center3D.X(), center3D.Y() );
6310 _LayerEdge* e0 = getLEdgeOnV(0);
6311 _LayerEdge* eM = _eos._edges[ 0 ];
6312 _LayerEdge* e1 = getLEdgeOnV(1);
6313 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
6314 gp_XY uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
6315 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
6316 gp_Vec2d vec0( center, uv0 );
6317 gp_Vec2d vecM( center, uvM );
6318 gp_Vec2d vec1( center, uv1 );
6319 double uLast = vec0.Angle( vec1 ); // -PI - +PI
6320 double uMidl = vec0.Angle( vecM );
6321 if ( uLast * uMidl <= 0. )
6322 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
6323 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
6325 gp_Ax2d axis( center, vec0 );
6326 gp_Circ2d circ( axis, radius );
6327 for ( size_t i = 0; i < _eos.size(); ++i )
6329 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6330 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6331 double newU = uLast * _leParams[i];
6332 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
6333 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
6335 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
6336 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
6337 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
6338 dumpMove( tgtNode );
6340 if ( SMDS_FacePositionPtr pos = tgtNode->GetPosition() ) // NULL if F is noShrink
6342 pos->SetUParameter( newUV.X() );
6343 pos->SetVParameter( newUV.Y() );
6345 _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
6354 //================================================================================
6356 * \brief smooth _LayerEdge's on a an EDGE
6358 //================================================================================
6360 bool _Smoother1D::smoothComplexEdge( _SolidData& /*data*/,
6361 Handle(ShapeAnalysis_Surface)& surface,
6362 const TopoDS_Face& F,
6363 SMESH_MesherHelper& /*helper*/)
6365 if ( _offPoints.empty() )
6368 // ----------------------------------------------
6369 // move _offPoints along normals of _LayerEdge's
6370 // ----------------------------------------------
6372 _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6373 if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
6374 _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
6375 if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED ))
6376 _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
6377 _leOnV[0]._len = e[0]->_len;
6378 _leOnV[1]._len = e[1]->_len;
6379 for ( size_t i = 0; i < _offPoints.size(); i++ )
6381 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
6382 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
6383 const double w0 = _offPoints[i]._2edges._wgt[0];
6384 const double w1 = _offPoints[i]._2edges._wgt[1];
6385 gp_XYZ avgNorm = ( e0->_normal * w0 + e1->_normal * w1 ).Normalized();
6386 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
6387 double avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
6388 if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
6389 e1->Is( _LayerEdge::NORMAL_UPDATED ))
6390 avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
6392 _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
6393 _offPoints[i]._len = avgLen;
6397 if ( !surface.IsNull() ) // project _offPoints to the FACE
6399 fTol = 100 * BRep_Tool::Tolerance( F );
6400 //const double segLen = _offPoints[0].Distance( _offPoints[1] );
6402 gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
6403 //if ( surface->Gap() < 0.5 * segLen )
6404 _offPoints[0]._xyz = surface->Value( uv ).XYZ();
6406 for ( size_t i = 1; i < _offPoints.size(); ++i )
6408 uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
6409 //if ( surface->Gap() < 0.5 * segLen )
6410 _offPoints[i]._xyz = surface->Value( uv ).XYZ();
6414 // -----------------------------------------------------------------
6415 // project tgt nodes of extreme _LayerEdge's to the offset segments
6416 // -----------------------------------------------------------------
6418 const int updatedOrBlocked = _LayerEdge::NORMAL_UPDATED | _LayerEdge::BLOCKED;
6419 if ( e[0]->Is( updatedOrBlocked )) _iSeg[0] = 0;
6420 if ( e[1]->Is( updatedOrBlocked )) _iSeg[1] = _offPoints.size()-2;
6422 gp_Pnt pExtreme[2], pProj[2];
6423 bool isProjected[2];
6424 for ( int is2nd = 0; is2nd < 2; ++is2nd )
6426 pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
6427 int i = _iSeg[ is2nd ];
6428 int di = is2nd ? -1 : +1;
6429 bool & projected = isProjected[ is2nd ];
6431 double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
6434 gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ] );
6435 gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
6436 uOnSeg = ( v0p * v01 ) / v01.SquareMagnitude(); // param [0,1] along v01
6437 projected = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
6438 dist = pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
6439 if ( dist < distMin || projected )
6442 pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
6445 else if ( dist > distPrev )
6447 if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
6453 while ( !projected &&
6454 i >= 0 && i+1 < (int)_offPoints.size() );
6458 if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
6461 _iSeg[1] = _offPoints.size()-2;
6462 debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
6467 if ( _iSeg[0] > _iSeg[1] )
6469 debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
6473 // adjust length of extreme LE (test viscous_layers_01/B7)
6474 gp_Vec vDiv0( pExtreme[0], pProj[0] );
6475 gp_Vec vDiv1( pExtreme[1], pProj[1] );
6476 double d0 = vDiv0.Magnitude();
6477 double d1 = isProjected[1] ? vDiv1.Magnitude() : 0;
6478 if ( e[0]->Is( _LayerEdge::BLOCKED )) {
6479 if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
6480 else e[0]->_len -= d0;
6482 if ( e[1]->Is( _LayerEdge::BLOCKED )) {
6483 if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
6484 else e[1]->_len -= d1;
6487 // ---------------------------------------------------------------------------------
6488 // compute normalized length of the offset segments located between the projections
6489 // ---------------------------------------------------------------------------------
6491 // temporary replace extreme _offPoints by pExtreme
6492 gp_XYZ opXYZ[2] = { _offPoints[ _iSeg[0] ]._xyz,
6493 _offPoints[ _iSeg[1]+1 ]._xyz };
6494 _offPoints[ _iSeg[0] ]._xyz = pExtreme[0].XYZ();
6495 _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
6497 size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
6498 vector< double > len( nbSeg + 1 );
6500 len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
6501 for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
6503 len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
6505 // if ( isProjected[ 1 ])
6506 // len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6508 // len[ nbSeg ] += pExtreme[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6510 double fullLen = len.back() - d0 - d1;
6511 for ( iSeg = 0; iSeg < len.size(); ++iSeg )
6512 len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
6514 // -------------------------------------------------------------
6515 // distribute tgt nodes of _LayerEdge's between the projections
6516 // -------------------------------------------------------------
6519 for ( size_t i = 0; i < _eos.size(); ++i )
6521 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6522 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6523 while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
6525 double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
6526 gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0] ]._xyz * ( 1 - r ) +
6527 _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
6529 if ( surface.IsNull() )
6531 _eos[i]->_pos.back() = p;
6533 else // project a new node position to a FACE
6535 gp_Pnt2d uv ( _eos[i]->_pos.back().X(), _eos[i]->_pos.back().Y() );
6536 gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
6538 p = surface->Value( uv2 ).XYZ();
6539 _eos[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
6541 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6542 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6543 dumpMove( tgtNode );
6546 _offPoints[ _iSeg[0] ]._xyz = opXYZ[0];
6547 _offPoints[ _iSeg[1]+1 ]._xyz = opXYZ[1];
6552 //================================================================================
6554 * \brief Prepare for smoothing
6556 //================================================================================
6558 void _Smoother1D::prepare(_SolidData& data)
6560 const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
6561 _curveLen = SMESH_Algo::EdgeLength( E );
6563 // sort _LayerEdge's by position on the EDGE
6564 data.SortOnEdge( E, _eos._edges );
6566 // compute normalized param of _eos._edges on EDGE
6567 _leParams.resize( _eos._edges.size() + 1 );
6570 gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
6572 for ( size_t i = 0; i < _eos._edges.size(); ++i )
6574 gp_Pnt p = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
6575 curLen = p.Distance( pPrev );
6576 _leParams[i+1] = _leParams[i] + curLen;
6579 double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
6580 for ( size_t i = 0; i < _leParams.size()-1; ++i )
6581 _leParams[i] = _leParams[i+1] / fullLen;
6582 _leParams.back() = 1.;
6585 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6587 // get cosin to use in findEdgesToSmooth()
6588 _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
6589 _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
6590 _leOnV[0]._cosin = Abs( leOnV[0]->_cosin );
6591 _leOnV[1]._cosin = Abs( leOnV[1]->_cosin );
6592 _leOnV[0]._flags = _leOnV[1]._flags = 0;
6593 if ( _eos._sWOL.IsNull() ) // 3D
6594 for ( int iEnd = 0; iEnd < 2; ++iEnd )
6595 _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6600 // divide E to have offset segments with low deflection
6601 BRepAdaptor_Curve c3dAdaptor( E );
6602 const double curDeflect = 0.1; //0.01; // Curvature deflection == |p1p2|*sin(p1p2,p1pM)
6603 const double angDeflect = 0.1; //0.09; // Angular deflection == sin(p1pM,pMp2)
6604 GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
6605 if ( discret.NbPoints() <= 2 )
6607 _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
6611 const double u0 = c3dAdaptor.FirstParameter();
6612 gp_Pnt p; gp_Vec tangent;
6613 if ( discret.NbPoints() >= (int) _eos.size() + 2 )
6615 _offPoints.resize( discret.NbPoints() );
6616 for ( size_t i = 0; i < _offPoints.size(); i++ )
6618 double u = discret.Parameter( i+1 );
6619 c3dAdaptor.D1( u, p, tangent );
6620 _offPoints[i]._xyz = p.XYZ();
6621 _offPoints[i]._edgeDir = tangent.XYZ();
6622 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6627 std::vector< double > params( _eos.size() + 2 );
6629 params[0] = data.GetHelper().GetNodeU( E, leOnV[0]->_nodes[0] );
6630 params.back() = data.GetHelper().GetNodeU( E, leOnV[1]->_nodes[0] );
6631 for ( size_t i = 0; i < _eos.size(); i++ )
6632 params[i+1] = data.GetHelper().GetNodeU( E, _eos[i]->_nodes[0] );
6634 if ( params[1] > params[ _eos.size() ] )
6635 std::reverse( params.begin() + 1, params.end() - 1 );
6637 _offPoints.resize( _eos.size() + 2 );
6638 for ( size_t i = 0; i < _offPoints.size(); i++ )
6640 const double u = params[i];
6641 c3dAdaptor.D1( u, p, tangent );
6642 _offPoints[i]._xyz = p.XYZ();
6643 _offPoints[i]._edgeDir = tangent.XYZ();
6644 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6649 _offPoints [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
6650 _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
6651 _2NearEdges tmp2edges;
6652 tmp2edges._edges[1] = _eos._edges[0];
6653 _leOnV[0]._2neibors = & tmp2edges;
6654 _leOnV[0]._nodes = leOnV[0]->_nodes;
6655 _leOnV[1]._nodes = leOnV[1]->_nodes;
6656 _LayerEdge* eNext, *ePrev = & _leOnV[0];
6657 for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
6659 // find _LayerEdge's located before and after an offset point
6660 // (_eos._edges[ iLE ] is next after ePrev)
6661 while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
6662 ePrev = _eos._edges[ iLE++ ];
6663 eNext = ePrev->_2neibors->_edges[1];
6665 gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
6666 gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
6667 double r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
6668 _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
6671 // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
6672 for ( size_t i = 0; i < _offPoints.size(); i++ )
6673 if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
6674 _offPoints[i]._2edges._edges[0] = & _leOnV[0];
6676 for ( size_t i = _offPoints.size()-1; i > 0; i-- )
6677 if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
6678 _offPoints[i]._2edges._edges[1] = & _leOnV[1];
6681 // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
6683 int iLBO = _offPoints.size() - 2; // last but one
6685 if ( leOnV[ 0 ]->Is( _LayerEdge::MULTI_NORMAL ))
6686 _leOnV[ 0 ]._normal = getNormalNormal( _eos._edges[1]->_normal, _edgeDir[0] );
6688 _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
6689 if ( leOnV[ 1 ]->Is( _LayerEdge::MULTI_NORMAL ))
6690 _leOnV[ 1 ]._normal = getNormalNormal( _eos._edges.back()->_normal, _edgeDir[1] );
6692 _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
6693 _leOnV[ 0 ]._len = 0;
6694 _leOnV[ 1 ]._len = 0;
6695 _leOnV[ 0 ]._lenFactor = _offPoints[1 ]._2edges._edges[1]->_lenFactor;
6696 _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
6699 _iSeg[1] = _offPoints.size()-2;
6701 // initialize OffPnt::_len
6702 for ( size_t i = 0; i < _offPoints.size(); ++i )
6703 _offPoints[i]._len = 0;
6705 if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
6707 _leOnV[0]._len = leOnV[0]->_len;
6708 _leOnV[1]._len = leOnV[1]->_len;
6709 for ( size_t i = 0; i < _offPoints.size(); i++ )
6711 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
6712 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
6713 const double w0 = _offPoints[i]._2edges._wgt[0];
6714 const double w1 = _offPoints[i]._2edges._wgt[1];
6715 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
6716 gp_XYZ avgXYZ = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
6717 SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
6718 _offPoints[i]._xyz = avgXYZ;
6719 _offPoints[i]._len = avgLen;
6724 //================================================================================
6726 * \brief return _normal of _leOnV[is2nd] normal to the EDGE
6728 //================================================================================
6730 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
6731 const gp_XYZ& edgeDir)
6733 gp_XYZ cross = normal ^ edgeDir;
6734 gp_XYZ norm = edgeDir ^ cross;
6735 double size = norm.Modulus();
6737 // if ( size == 0 ) // MULTI_NORMAL _LayerEdge
6738 // return gp_XYZ( 1e-100, 1e-100, 1e-100 );
6740 if ( size < 1e-5 ) // normal || edgeDir (almost) at inflation along EDGE (bos #20643)
6742 const _LayerEdge* le = _eos._edges[ _eos._edges.size() / 2 ];
6743 const gp_XYZ& leNorm = le->_normal;
6745 cross = leNorm ^ edgeDir;
6746 norm = edgeDir ^ cross;
6747 size = norm.Modulus();
6753 //================================================================================
6755 * \brief Writes a script creating a mesh composed of _offPoints
6757 //================================================================================
6759 void _Smoother1D::offPointsToPython() const
6761 const char* fname = "/tmp/offPoints.py";
6762 cout << "exec(open('"<<fname<<"','rb').read() )"<<endl;
6764 py << "import SMESH" << endl
6765 << "from salome.smesh import smeshBuilder" << endl
6766 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
6767 << "mesh = smesh.Mesh( 'offPoints' )"<<endl;
6768 for ( size_t i = 0; i < _offPoints.size(); i++ )
6770 py << "mesh.AddNode( "
6771 << _offPoints[i]._xyz.X() << ", "
6772 << _offPoints[i]._xyz.Y() << ", "
6773 << _offPoints[i]._xyz.Z() << " )" << endl;
6777 //================================================================================
6779 * \brief Sort _LayerEdge's by a parameter on a given EDGE
6781 //================================================================================
6783 void _SolidData::SortOnEdge( const TopoDS_Edge& E,
6784 vector< _LayerEdge* >& edges)
6786 map< double, _LayerEdge* > u2edge;
6787 for ( size_t i = 0; i < edges.size(); ++i )
6788 u2edge.insert( u2edge.end(),
6789 make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
6791 ASSERT( u2edge.size() == edges.size() );
6792 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
6793 for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
6794 edges[i] = u2e->second;
6796 Sort2NeiborsOnEdge( edges );
6799 //================================================================================
6801 * \brief Set _2neibors according to the order of _LayerEdge on EDGE
6803 //================================================================================
6805 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
6807 if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
6809 for ( size_t i = 0; i < edges.size()-1; ++i )
6810 if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
6811 edges[i]->_2neibors->reverse();
6813 const size_t iLast = edges.size() - 1;
6814 if ( edges.size() > 1 &&
6815 edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
6816 edges[iLast]->_2neibors->reverse();
6819 //================================================================================
6821 * \brief Return _EdgesOnShape* corresponding to the shape
6823 //================================================================================
6825 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6827 if ( shapeID < (int)_edgesOnShape.size() &&
6828 _edgesOnShape[ shapeID ]._shapeID == shapeID )
6829 return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6831 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6832 if ( _edgesOnShape[i]._shapeID == shapeID )
6833 return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6838 //================================================================================
6840 * \brief Return _EdgesOnShape* corresponding to the shape
6842 //================================================================================
6844 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6846 SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6847 return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6850 //================================================================================
6852 * \brief Prepare data of the _LayerEdge for smoothing on FACE
6854 //================================================================================
6856 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6858 SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6860 set< TGeomID > vertices;
6862 if ( eos->ShapeType() == TopAbs_FACE )
6864 // check FACE concavity and get concave VERTEXes
6865 F = TopoDS::Face( eos->_shape );
6866 if ( isConcave( F, helper, &vertices ))
6867 _concaveFaces.insert( eos->_shapeID );
6869 // set eos._eosConcaVer
6870 eos->_eosConcaVer.clear();
6871 eos->_eosConcaVer.reserve( vertices.size() );
6872 for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6874 _EdgesOnShape* eov = GetShapeEdges( *v );
6875 if ( eov && eov->_edges.size() == 1 )
6877 eos->_eosConcaVer.push_back( eov );
6878 for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6879 eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6883 // SetSmooLen() to _LayerEdge's on FACE
6884 // for ( size_t i = 0; i < eos->_edges.size(); ++i )
6886 // eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6888 // SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6889 // while ( smIt->more() ) // loop on sub-shapes of the FACE
6891 // _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6892 // if ( !eoe ) continue;
6894 // vector<_LayerEdge*>& eE = eoe->_edges;
6895 // for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6897 // if ( eE[iE]->_cosin <= theMinSmoothCosin )
6900 // SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6901 // while ( segIt->more() )
6903 // const SMDS_MeshElement* seg = segIt->next();
6904 // if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6906 // if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6907 // continue; // not to check a seg twice
6908 // for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6910 // _LayerEdge* eN = eE[iE]->_neibors[iN];
6911 // if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6913 // double dist = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6914 // double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6915 // eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6916 // eN->Set( _LayerEdge::NEAR_BOUNDARY );
6921 } // if ( eos->ShapeType() == TopAbs_FACE )
6923 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6925 eos->_edges[i]->_smooFunction = 0;
6926 eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6928 bool isCurved = false;
6929 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6931 _LayerEdge* edge = eos->_edges[i];
6933 // get simplices sorted
6934 _Simplex::SortSimplices( edge->_simplices );
6936 // smoothing function
6937 edge->ChooseSmooFunction( vertices, _n2eMap );
6940 double avgNormProj = 0, avgLen = 0;
6941 for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6943 _Simplex& s = edge->_simplices[iS];
6945 gp_XYZ vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6946 avgNormProj += edge->_normal * vec;
6947 avgLen += vec.Modulus();
6948 if ( substituteSrcNodes )
6950 s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6951 s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6954 avgNormProj /= edge->_simplices.size();
6955 avgLen /= edge->_simplices.size();
6956 if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6958 edge->Set( _LayerEdge::SMOOTHED_C1 );
6960 SMDS_FacePositionPtr fPos = edge->_nodes[0]->GetPosition();
6962 for ( size_t iS = 0; iS < edge->_simplices.size() && !fPos; ++iS )
6963 fPos = edge->_simplices[iS]._nPrev->GetPosition();
6965 edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6969 // prepare for putOnOffsetSurface()
6970 if (( eos->ShapeType() == TopAbs_FACE ) &&
6971 ( isCurved || !eos->_eosConcaVer.empty() ))
6973 eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6974 eos->_edgeForOffset = 0;
6976 double maxCosin = -1;
6977 //bool hasNoShrink = false;
6978 for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6980 _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6981 if ( !eoe || eoe->_edges.empty() ) continue;
6983 // if ( eos->GetData()._noShrinkShapes.count( eoe->_shapeID ))
6984 // hasNoShrink = true;
6986 vector<_LayerEdge*>& eE = eoe->_edges;
6987 _LayerEdge* e = eE[ eE.size() / 2 ];
6988 if ( !e->Is( _LayerEdge::RISKY_SWOL ) && e->_cosin > maxCosin )
6990 eos->_edgeForOffset = e;
6991 maxCosin = e->_cosin;
6994 if ( !eoe->_sWOL.IsNull() )
6995 for ( _LayerEdge* le : eoe->_edges )
6996 if ( le->Is( _LayerEdge::RISKY_SWOL ) && e->_cosin > 0 )
6998 // make _neibors on FACE be smoothed after le->Is( BLOCKED )
6999 for ( _LayerEdge* neibor : le->_neibors )
7001 int shapeDim = neibor->BaseShapeDim();
7002 if ( shapeDim == 2 )
7003 neibor->Set( _LayerEdge::NEAR_BOUNDARY ); // on FACE
7004 else if ( shapeDim == 0 )
7005 neibor->Set( _LayerEdge::RISKY_SWOL ); // on VERTEX
7007 if ( !neibor->_curvature )
7009 gp_XY uv = helper.GetNodeUV( F, neibor->_nodes[0] );
7010 neibor->_curvature = _Factory::NewCurvature();
7011 neibor->_curvature->_r = 0;
7012 neibor->_curvature->_k = 0;
7013 neibor->_curvature->_h2lenRatio = 0;
7014 neibor->_curvature->_uv = uv;
7020 // Try to initialize _Mapper2D
7022 // if ( hasNoShrink )
7025 SMDS_ElemIteratorPtr fIt = eos->_subMesh->GetSubMeshDS()->GetElements();
7026 if ( !fIt->more() || fIt->next()->NbCornerNodes() != 4 )
7029 // get EDGEs of quadrangle bottom
7030 std::list< TopoDS_Edge > edges;
7031 std::list< int > nbEdgesInWire;
7032 int nbWire = SMESH_Block::GetOrderedEdges( F, edges, nbEdgesInWire );
7033 if ( nbWire != 1 || nbEdgesInWire.front() < 4 )
7035 const SMDS_MeshNode* node;
7036 while ( true ) // make edges start at a corner VERTEX
7038 node = SMESH_Algo::VertexNode( helper.IthVertex( 0, edges.front() ), helper.GetMeshDS() );
7039 if ( node && helper.IsCornerOfStructure( node, eos->_subMesh->GetSubMeshDS(), helper ))
7042 if ( edges.empty() )
7045 std::list< TopoDS_Edge >::iterator edgeIt = edges.begin();
7046 while ( true ) // make edges finish at a corner VERTEX
7048 node = SMESH_Algo::VertexNode( helper.IthVertex( 1, *edgeIt ), helper.GetMeshDS() );
7050 if ( node && helper.IsCornerOfStructure( node, eos->_subMesh->GetSubMeshDS(), helper ))
7052 edges.erase( edgeIt, edges.end() );
7055 if ( edgeIt == edges.end() )
7059 // get structure of nodes
7060 TParam2ColumnMap param2ColumnMap;
7061 if ( !helper.LoadNodeColumns( param2ColumnMap, F, edges, helper.GetMeshDS() ))
7064 eos->_mapper2D = new _Mapper2D( param2ColumnMap, eos->GetData()._n2eMap );
7066 } // if eos is of curved FACE
7071 //================================================================================
7073 * \brief Add faces for smoothing
7075 //================================================================================
7077 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
7078 const set< _EdgesOnShape* >* edgesNoAnaSmooth )
7080 set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
7081 for ( ; eos != eosToSmooth.end(); ++eos )
7083 if ( !*eos || (*eos)->_toSmooth ) continue;
7085 (*eos)->_toSmooth = true;
7087 if ( (*eos)->ShapeType() == TopAbs_FACE )
7089 PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
7090 (*eos)->_toSmooth = true;
7094 // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
7095 if ( edgesNoAnaSmooth )
7096 for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
7098 if ( (*eos)->_edgeSmoother )
7099 (*eos)->_edgeSmoother->_anaCurve.Nullify();
7103 //================================================================================
7105 * \brief Limit _LayerEdge::_maxLen according to local curvature
7107 //================================================================================
7109 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& /*helper*/ )
7111 // find intersection of neighbor _LayerEdge's to limit _maxLen
7112 // according to local curvature (IPAL52648)
7114 // This method must be called after findCollisionEdges() where _LayerEdge's
7115 // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
7117 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7119 _EdgesOnShape& eosI = data._edgesOnShape[iS];
7120 if ( eosI._edges.empty() ) continue;
7121 if ( !eosI._hyp.ToSmooth() )
7123 for ( size_t i = 0; i < eosI._edges.size(); ++i )
7125 _LayerEdge* eI = eosI._edges[i];
7126 for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
7128 _LayerEdge* eN = eI->_neibors[iN];
7129 if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
7131 _EdgesOnShape* eosN = data.GetShapeEdges( eN );
7132 limitMaxLenByCurvature( eI, eN, eosI, *eosN, eosI._hyp.ToSmooth() );
7137 else if ( eosI.ShapeType() == TopAbs_EDGE )
7139 const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
7140 if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
7142 _LayerEdge* e0 = eosI._edges[0];
7143 for ( size_t i = 1; i < eosI._edges.size(); ++i )
7145 _LayerEdge* eI = eosI._edges[i];
7146 limitMaxLenByCurvature( eI, e0, eosI, eosI, eosI._hyp.ToSmooth() );
7153 //================================================================================
7155 * \brief Limit _LayerEdge::_maxLen according to local curvature
7157 //================================================================================
7159 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge* e1,
7161 _EdgesOnShape& /*eos1*/,
7162 _EdgesOnShape& /*eos2*/,
7163 const bool /*isSmoothable*/ )
7165 if (( e1->_nodes[0]->GetPosition()->GetDim() !=
7166 e2->_nodes[0]->GetPosition()->GetDim() ) &&
7167 ( e1->_cosin < 0.75 ))
7168 return; // angle > 90 deg at e1
7170 gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
7171 double norSize = plnNorm.SquareModulus();
7172 if ( norSize < std::numeric_limits<double>::min() )
7173 return; // parallel normals
7175 // find closest points of skew _LayerEdge's
7176 SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
7177 gp_XYZ dir12 = src2 - src1;
7178 gp_XYZ perp1 = e1->_normal ^ plnNorm;
7179 gp_XYZ perp2 = e2->_normal ^ plnNorm;
7180 double dot1 = perp2 * e1->_normal;
7181 double dot2 = perp1 * e2->_normal;
7182 double u1 = ( perp2 * dir12 ) / dot1;
7183 double u2 = - ( perp1 * dir12 ) / dot2;
7184 if ( u1 > 0 && u2 > 0 )
7186 double ovl = ( u1 * e1->_normal * dir12 -
7187 u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
7188 if ( ovl > theSmoothThickToElemSizeRatio )
7190 const double coef = 0.75;
7191 e1->SetMaxLen( Min( e1->_maxLen, coef * u1 / e1->_lenFactor ));
7192 e2->SetMaxLen( Min( e2->_maxLen, coef * u2 / e2->_lenFactor ));
7197 //================================================================================
7199 * \brief Fill data._collisionEdges
7201 //================================================================================
7203 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
7205 data._collisionEdges.clear();
7207 // set the full thickness of the layers to LEs
7208 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7210 _EdgesOnShape& eos = data._edgesOnShape[iS];
7211 if ( eos._edges.empty() ) continue;
7212 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
7213 if ( !eos._sWOL.IsNull() ) continue; // PAL23566
7215 for ( size_t i = 0; i < eos._edges.size(); ++i )
7217 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
7218 double maxLen = eos._edges[i]->_maxLen;
7219 eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
7220 eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
7221 eos._edges[i]->_maxLen = maxLen;
7225 // make temporary quadrangles got by extrusion of
7226 // mesh edges along _LayerEdge._normal's
7228 vector< const SMDS_MeshElement* > tmpFaces;
7230 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7232 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7233 if ( eos.ShapeType() != TopAbs_EDGE )
7235 if ( eos._edges.empty() )
7237 _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
7238 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
7239 while ( smIt->more() )
7240 if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
7241 if ( eov->_edges.size() == 1 )
7242 edge[ bool( edge[0]) ] = eov->_edges[0];
7246 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
7247 tmpFaces.push_back( f );
7250 for ( size_t i = 0; i < eos._edges.size(); ++i )
7252 _LayerEdge* edge = eos._edges[i];
7253 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
7255 const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
7256 if ( src2->GetPosition()->GetDim() > 0 &&
7257 src2->GetID() < edge->_nodes[0]->GetID() )
7258 continue; // avoid using same segment twice
7260 // a _LayerEdge containing tgt2
7261 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
7263 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
7264 tmpFaces.push_back( f );
7269 // Find _LayerEdge's intersecting tmpFaces.
7271 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
7273 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
7274 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
7276 double dist1, dist2, segLen, eps = 0.5;
7277 _CollisionEdges collEdges;
7278 vector< const SMDS_MeshElement* > suspectFaces;
7279 const double angle45 = Cos( 45. * M_PI / 180. );
7281 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7283 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7284 if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
7286 // find sub-shapes whose VL can influence VL on eos
7287 set< TGeomID > neighborShapes;
7288 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
7289 while ( const TopoDS_Shape* face = fIt->next() )
7291 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
7292 if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
7294 SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
7295 while ( subIt->more() )
7296 neighborShapes.insert( subIt->next()->GetId() );
7299 if ( eos.ShapeType() == TopAbs_VERTEX )
7301 PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
7302 while ( const TopoDS_Shape* edge = eIt->next() )
7303 neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
7305 // find intersecting _LayerEdge's
7306 for ( size_t i = 0; i < eos._edges.size(); ++i )
7308 if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
7309 _LayerEdge* edge = eos._edges[i];
7310 gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
7313 gp_Vec eSegDir0, eSegDir1;
7314 if ( edge->IsOnEdge() )
7316 SMESH_TNodeXYZ eP( edge->_nodes[0] );
7317 eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
7318 eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
7320 suspectFaces.clear();
7321 searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
7322 SMDSAbs_Face, suspectFaces );
7323 collEdges._intEdges.clear();
7324 for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
7326 const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
7327 if ( f->_le1 == edge || f->_le2 == edge ) continue;
7328 if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
7329 if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
7330 if ( edge->IsOnEdge() ) {
7331 if ( edge->_2neibors->include( f->_le1 ) ||
7332 edge->_2neibors->include( f->_le2 )) continue;
7335 if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
7336 ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge ))) continue;
7338 dist1 = dist2 = Precision::Infinite();
7339 if ( !edge->SegTriaInter( lastSegment, f->n(0), f->n(1), f->n(2), dist1, eps ))
7340 dist1 = Precision::Infinite();
7341 if ( !edge->SegTriaInter( lastSegment, f->n(3), f->n(2), f->n(0), dist2, eps ))
7342 dist2 = Precision::Infinite();
7343 if (( dist1 > segLen ) && ( dist2 > segLen ))
7346 if ( edge->IsOnEdge() )
7348 // skip perpendicular EDGEs
7349 gp_Vec fSegDir = SMESH_TNodeXYZ( f->n(0) ) - SMESH_TNodeXYZ( f->n(3) );
7350 bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
7351 isLessAngle( eSegDir1, fSegDir, angle45 ) ||
7352 isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
7353 isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
7358 // either limit inflation of edges or remember them for updating _normal
7359 // double dot = edge->_normal * f->GetDir();
7362 collEdges._intEdges.push_back( f->_le1 );
7363 collEdges._intEdges.push_back( f->_le2 );
7367 // double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
7368 // edge->SetMaxLen( Min( shortLen, edge->_maxLen ));
7372 if ( !collEdges._intEdges.empty() )
7374 collEdges._edge = edge;
7375 data._collisionEdges.push_back( collEdges );
7380 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
7383 // restore the zero thickness
7384 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7386 _EdgesOnShape& eos = data._edgesOnShape[iS];
7387 if ( eos._edges.empty() ) continue;
7388 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
7390 for ( size_t i = 0; i < eos._edges.size(); ++i )
7392 eos._edges[i]->InvalidateStep( 1, eos );
7393 eos._edges[i]->_len = 0;
7398 //================================================================================
7400 * \brief Find _LayerEdge's located on boundary of a convex FACE whose normal
7401 * will be updated at each inflation step
7403 //================================================================================
7405 void _ViscousBuilder::findEdgesToUpdateNormalNearConvexFace( _ConvexFace & convFace,
7407 SMESH_MesherHelper& helper )
7409 const TGeomID convFaceID = getMeshDS()->ShapeToIndex( convFace._face );
7410 const double preci = BRep_Tool::Tolerance( convFace._face );
7411 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( convFace._face );
7413 bool edgesToUpdateFound = false;
7415 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7416 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7418 _EdgesOnShape& eos = * id2eos->second;
7419 if ( !eos._sWOL.IsNull() ) continue;
7420 if ( !eos._hyp.ToSmooth() ) continue;
7421 for ( size_t i = 0; i < eos._edges.size(); ++i )
7423 _LayerEdge* ledge = eos._edges[ i ];
7424 if ( ledge->Is( _LayerEdge::UPD_NORMAL_CONV )) continue; // already checked
7425 if ( ledge->Is( _LayerEdge::MULTI_NORMAL )) continue; // not inflatable
7427 gp_XYZ tgtPos = ( SMESH_NodeXYZ( ledge->_nodes[0] ) +
7428 ledge->_normal * ledge->_lenFactor * ledge->_maxLen );
7430 // the normal must be updated if distance from tgtPos to surface is less than
7433 // find an initial UV for search of a projection of tgtPos to surface
7434 const SMDS_MeshNode* nodeInFace = 0;
7435 SMDS_ElemIteratorPtr fIt = ledge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7436 while ( fIt->more() && !nodeInFace )
7438 const SMDS_MeshElement* f = fIt->next();
7439 if ( convFaceID != f->getshapeId() ) continue;
7441 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
7442 while ( nIt->more() && !nodeInFace )
7444 const SMDS_MeshElement* n = nIt->next();
7445 if ( n->getshapeId() == convFaceID )
7446 nodeInFace = static_cast< const SMDS_MeshNode* >( n );
7451 gp_XY uv = helper.GetNodeUV( convFace._face, nodeInFace );
7454 surface->NextValueOfUV( uv, tgtPos, preci );
7455 double dist = surface->Gap();
7456 if ( dist < 0.95 * ledge->_maxLen )
7458 ledge->Set( _LayerEdge::UPD_NORMAL_CONV );
7459 if ( !ledge->_curvature ) ledge->_curvature = _Factory::NewCurvature();
7460 ledge->_curvature->_uv.SetCoord( uv.X(), uv.Y() );
7461 edgesToUpdateFound = true;
7466 if ( !convFace._isTooCurved && edgesToUpdateFound )
7468 data._convexFaces.insert( make_pair( convFaceID, convFace )).first->second;
7472 //================================================================================
7474 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
7475 * _LayerEdge's on neighbor EDGE's
7477 //================================================================================
7479 bool _ViscousBuilder::updateNormals( _SolidData& data,
7480 SMESH_MesherHelper& helper,
7482 double /*stepSize*/)
7484 updateNormalsOfC1Vertices( data );
7486 if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
7489 // map to store new _normal and _cosin for each intersected edge
7490 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp > edge2newEdge;
7491 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
7492 _LayerEdge zeroEdge;
7493 zeroEdge._normal.SetCoord( 0,0,0 );
7494 zeroEdge._maxLen = Precision::Infinite();
7495 zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
7497 set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
7499 double segLen, dist1, dist2, dist;
7500 vector< pair< _LayerEdge*, double > > intEdgesDist;
7501 _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
7503 for ( int iter = 0; iter < 5; ++iter )
7505 edge2newEdge.clear();
7507 for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
7509 _CollisionEdges& ce = data._collisionEdges[iE];
7510 _LayerEdge* edge1 = ce._edge;
7511 if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
7512 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7513 if ( !eos1 ) continue;
7515 // detect intersections
7516 gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
7517 double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
7519 intEdgesDist.clear();
7520 double minIntDist = Precision::Infinite();
7521 for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
7523 if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7524 ce._intEdges[i ]->Is( _LayerEdge::BLOCKED ) &&
7525 ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
7527 double dot = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
7528 double fact = ( 1.1 + dot * dot );
7529 SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
7530 SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
7531 gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
7532 gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
7533 dist1 = dist2 = Precision::Infinite();
7534 if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1, dist1, eps ) &&
7535 !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
7538 if ( dist > testLen || dist <= 0 )
7541 if ( dist > testLen || dist <= 0 )
7544 // choose a closest edge
7545 gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
7546 double d1 = intP.SquareDistance( pSrc0 );
7547 double d2 = intP.SquareDistance( pSrc1 );
7548 int iClose = i + ( d2 < d1 );
7549 _LayerEdge* edge2 = ce._intEdges[iClose];
7550 edge2->Unset( _LayerEdge::MARKED );
7552 // choose a closest edge among neighbors
7553 gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
7554 d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
7555 for ( size_t j = 0; j < intEdgesDist.size(); ++j )
7557 _LayerEdge * edgeJ = intEdgesDist[j].first;
7558 if ( edge2->IsNeiborOnEdge( edgeJ ))
7560 d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
7561 ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
7564 intEdgesDist.push_back( make_pair( edge2, dist ));
7565 // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
7567 // iClose = i + !( d2 < d1 );
7568 // intEdges.push_back( ce._intEdges[iClose] );
7569 // ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
7571 minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
7576 // compute new _normals
7577 for ( size_t i = 0; i < intEdgesDist.size(); ++i )
7579 _LayerEdge* edge2 = intEdgesDist[i].first;
7580 double distWgt = edge1->_len / intEdgesDist[i].second;
7581 // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7582 // edge2->Is( _LayerEdge::BLOCKED )) continue;
7583 if ( edge2->Is( _LayerEdge::MARKED )) continue;
7584 edge2->Set( _LayerEdge::MARKED );
7587 gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
7589 double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7590 double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7591 double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7592 // double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7593 // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
7594 // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7595 // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7596 gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
7597 newNormal.Normalize();
7601 double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
7602 if ( cos1 < theMinSmoothCosin )
7604 newCos = cos2 * sgn1;
7606 else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
7608 newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
7612 newCos = edge1->_cosin;
7615 e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
7616 e2neIt->second._normal += distWgt * newNormal;
7617 e2neIt->second._cosin = newCos;
7618 e2neIt->second.SetMaxLen( 0.7 * minIntDist / edge1->_lenFactor );
7619 if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
7620 e2neIt->second._normal += dir2;
7622 e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
7623 e2neIt->second._normal += distWgt * newNormal;
7624 if ( Precision::IsInfinite( zeroEdge._maxLen ))
7626 e2neIt->second._cosin = edge2->_cosin;
7627 e2neIt->second.SetMaxLen( 1.3 * minIntDist / edge1->_lenFactor );
7629 if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
7630 e2neIt->second._normal += dir1;
7634 if ( edge2newEdge.empty() )
7635 break; //return true;
7637 dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
7639 // Update data of edges depending on a new _normal
7642 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7644 _LayerEdge* edge = e2neIt->first;
7645 _LayerEdge& newEdge = e2neIt->second;
7646 _EdgesOnShape* eos = data.GetShapeEdges( edge );
7647 if ( edge->Is( _LayerEdge::BLOCKED ) && newEdge._maxLen > edge->_len )
7650 // Check if a new _normal is OK:
7651 newEdge._normal.Normalize();
7652 if ( !isNewNormalOk( data, *edge, newEdge._normal ))
7654 if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
7656 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7657 edge->SetMaxLen( newEdge._maxLen );
7658 edge->SetNewLength( newEdge._maxLen, *eos, helper );
7660 continue; // the new _normal is bad
7662 // the new _normal is OK
7664 // find shapes that need smoothing due to change of _normal
7665 if ( edge->_cosin < theMinSmoothCosin &&
7666 newEdge._cosin > theMinSmoothCosin )
7668 if ( eos->_sWOL.IsNull() )
7670 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7671 while ( fIt->more() )
7672 shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
7674 else // edge inflates along a FACE
7676 TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
7677 PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
7678 while ( const TopoDS_Shape* E = eIt->next() )
7680 gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ),
7681 eos->_hyp.Get1stLayerThickness() );
7682 double angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
7683 if ( angle < M_PI / 2 )
7684 shapesToSmooth.insert( data.GetShapeEdges( *E ));
7689 double len = edge->_len;
7690 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7691 edge->SetNormal( newEdge._normal );
7692 edge->SetCosin( newEdge._cosin );
7693 edge->SetNewLength( len, *eos, helper );
7694 edge->Set( _LayerEdge::MARKED );
7695 edge->Set( _LayerEdge::NORMAL_UPDATED );
7696 edgesNoAnaSmooth.insert( eos );
7699 // Update normals and other dependent data of not intersecting _LayerEdge's
7700 // neighboring the intersecting ones
7702 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7704 _LayerEdge* edge1 = e2neIt->first;
7705 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7706 if ( !edge1->Is( _LayerEdge::MARKED ))
7709 if ( edge1->IsOnEdge() )
7711 const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
7712 const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
7713 edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
7716 if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
7718 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
7720 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
7721 if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
7722 continue; // j-th neighbor is also intersected
7723 _LayerEdge* prevEdge = edge1;
7724 const int nbSteps = 10;
7725 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
7727 if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
7728 neighbor->Is( _LayerEdge::MARKED ))
7730 _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
7731 if ( !eos ) continue;
7732 _LayerEdge* nextEdge = neighbor;
7733 if ( neighbor->_2neibors )
7736 nextEdge = neighbor->_2neibors->_edges[iNext];
7737 if ( nextEdge == prevEdge )
7738 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
7740 double r = double(step-1)/nbSteps/(iter+1);
7741 if ( !nextEdge->_2neibors )
7744 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
7745 newNorm.Normalize();
7746 if ( !isNewNormalOk( data, *neighbor, newNorm ))
7749 double len = neighbor->_len;
7750 neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7751 neighbor->SetNormal( newNorm );
7752 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
7753 if ( neighbor->_2neibors )
7754 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
7755 neighbor->SetNewLength( len, *eos, helper );
7756 neighbor->Set( _LayerEdge::MARKED );
7757 neighbor->Set( _LayerEdge::NORMAL_UPDATED );
7758 edgesNoAnaSmooth.insert( eos );
7760 if ( !neighbor->_2neibors )
7761 break; // neighbor is on VERTEX
7763 // goto the next neighbor
7764 prevEdge = neighbor;
7765 neighbor = nextEdge;
7772 data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
7777 //================================================================================
7779 * \brief Check if a new normal is OK
7781 //================================================================================
7783 bool _ViscousBuilder::isNewNormalOk( _SolidData& data,
7785 const gp_XYZ& newNormal)
7787 // check a min angle between the newNormal and surrounding faces
7788 vector<_Simplex> simplices;
7789 SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
7790 _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
7791 double newMinDot = 1, curMinDot = 1;
7792 for ( size_t i = 0; i < simplices.size(); ++i )
7794 n1.Set( simplices[i]._nPrev );
7795 n2.Set( simplices[i]._nNext );
7796 gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
7797 double normLen2 = normFace.SquareModulus();
7798 if ( normLen2 < std::numeric_limits<double>::min() )
7800 normFace /= Sqrt( normLen2 );
7801 newMinDot = Min( newNormal * normFace, newMinDot );
7802 curMinDot = Min( edge._normal * normFace, curMinDot );
7805 if ( newMinDot < 0.5 )
7807 ok = ( newMinDot >= curMinDot * 0.9 );
7808 //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
7809 // double initMinDot2 = 1. - edge._cosin * edge._cosin;
7810 // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
7816 //================================================================================
7818 * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
7820 //================================================================================
7822 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData& data,
7823 SMESH_MesherHelper& /*helper*/,
7825 const double stepSize )
7827 if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
7828 return true; // no shapes needing smoothing
7830 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7832 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7833 if ( //!eos._toSmooth || _eosC1 have _toSmooth == false
7834 !eos._hyp.ToSmooth() ||
7835 eos.ShapeType() != TopAbs_FACE ||
7836 eos._edges.empty() )
7839 bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
7840 if ( !toSmooth ) continue;
7842 for ( size_t i = 0; i < eos._edges.size(); ++i )
7844 _LayerEdge* edge = eos._edges[i];
7845 if ( !edge->Is( _LayerEdge::SMOOTHED ))
7847 if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
7850 const gp_XYZ& pPrev = edge->PrevPos();
7851 const gp_XYZ& pLast = edge->_pos.back();
7852 gp_XYZ stepVec = pLast - pPrev;
7853 double realStepSize = stepVec.Modulus();
7854 if ( realStepSize < numeric_limits<double>::min() )
7857 edge->_lenFactor = realStepSize / stepSize;
7858 edge->_normal = stepVec / realStepSize;
7859 edge->Set( _LayerEdge::NORMAL_UPDATED );
7866 //================================================================================
7868 * \brief Modify normals of _LayerEdge's on C1 VERTEXes
7870 //================================================================================
7872 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
7874 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7876 _EdgesOnShape& eov = data._edgesOnShape[ iS ];
7877 if ( eov._eosC1.empty() ||
7878 eov.ShapeType() != TopAbs_VERTEX ||
7879 eov._edges.empty() )
7882 gp_XYZ newNorm = eov._edges[0]->_normal;
7883 double curThick = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
7884 bool normChanged = false;
7886 for ( size_t i = 0; i < eov._eosC1.size(); ++i )
7888 _EdgesOnShape* eoe = eov._eosC1[i];
7889 const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
7890 const double eLen = SMESH_Algo::EdgeLength( e );
7891 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
7892 if ( oppV.IsSame( eov._shape ))
7893 oppV = SMESH_MesherHelper::IthVertex( 1, e );
7894 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
7895 if ( !eovOpp || eovOpp->_edges.empty() ) continue;
7896 if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
7898 double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
7899 if ( curThickOpp + curThick < eLen )
7902 double wgt = 2. * curThick / eLen;
7903 newNorm += wgt * eovOpp->_edges[0]->_normal;
7908 eov._edges[0]->SetNormal( newNorm.Normalized() );
7909 eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
7914 //================================================================================
7916 * \brief Modify normals of _LayerEdge's on _ConvexFace's
7918 //================================================================================
7920 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData& data,
7921 SMESH_MesherHelper& helper,
7924 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
7927 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
7928 for ( ; id2face != data._convexFaces.end(); ++id2face )
7930 _ConvexFace & convFace = (*id2face).second;
7931 convFace._normalsFixedOnBorders = false; // to update at each inflation step
7933 if ( convFace._normalsFixed )
7934 continue; // already fixed
7935 if ( convFace.CheckPrisms() )
7936 continue; // nothing to fix
7938 convFace._normalsFixed = true;
7940 BRepAdaptor_Surface surface ( convFace._face, false );
7941 BRepLProp_SLProps surfProp( surface, 2, 1e-6 );
7943 // check if the convex FACE is of spherical shape
7945 Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
7949 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7950 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7952 _EdgesOnShape& eos = *(id2eos->second);
7953 if ( eos.ShapeType() == TopAbs_VERTEX )
7955 _LayerEdge* ledge = eos._edges[ 0 ];
7956 if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7957 centersBox.Add( center );
7959 for ( size_t i = 0; i < eos._edges.size(); ++i )
7960 nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
7962 if ( centersBox.IsVoid() )
7964 debugMsg( "Error: centersBox.IsVoid()" );
7967 const bool isSpherical =
7968 ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7970 int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
7971 vector < _CentralCurveOnEdge > centerCurves( nbEdges );
7975 // set _LayerEdge::_normal as average of all normals
7977 // WARNING: different density of nodes on EDGEs is not taken into account that
7978 // can lead to an improper new normal
7980 gp_XYZ avgNormal( 0,0,0 );
7982 id2eos = convFace._subIdToEOS.begin();
7983 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7985 _EdgesOnShape& eos = *(id2eos->second);
7986 // set data of _CentralCurveOnEdge
7987 if ( eos.ShapeType() == TopAbs_EDGE )
7989 _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
7990 ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
7991 if ( !eos._sWOL.IsNull() )
7992 ceCurve._adjFace.Nullify();
7994 ceCurve._ledges.insert( ceCurve._ledges.end(),
7995 eos._edges.begin(), eos._edges.end());
7997 // summarize normals
7998 for ( size_t i = 0; i < eos._edges.size(); ++i )
7999 avgNormal += eos._edges[ i ]->_normal;
8001 double normSize = avgNormal.SquareModulus();
8002 if ( normSize < 1e-200 )
8004 debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
8007 avgNormal /= Sqrt( normSize );
8009 // compute new _LayerEdge::_cosin on EDGEs
8010 double avgCosin = 0;
8013 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
8015 _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
8016 if ( ceCurve._adjFace.IsNull() )
8018 for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
8020 const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
8021 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
8024 double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
8025 ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
8026 avgCosin += ceCurve._ledges[ iLE ]->_cosin;
8032 avgCosin /= nbCosin;
8034 // set _LayerEdge::_normal = avgNormal
8035 id2eos = convFace._subIdToEOS.begin();
8036 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
8038 _EdgesOnShape& eos = *(id2eos->second);
8039 if ( eos.ShapeType() != TopAbs_EDGE )
8040 for ( size_t i = 0; i < eos._edges.size(); ++i )
8041 eos._edges[ i ]->_cosin = avgCosin;
8043 for ( size_t i = 0; i < eos._edges.size(); ++i )
8045 eos._edges[ i ]->SetNormal( avgNormal );
8046 eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
8050 else // if ( isSpherical )
8052 // We suppose that centers of curvature at all points of the FACE
8053 // lie on some curve, let's call it "central curve". For all _LayerEdge's
8054 // having a common center of curvature we define the same new normal
8055 // as a sum of normals of _LayerEdge's on EDGEs among them.
8057 // get all centers of curvature for each EDGE
8059 helper.SetSubShape( convFace._face );
8060 _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
8062 TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
8063 for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
8065 const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
8067 // set adjacent FACE
8068 centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
8070 // get _LayerEdge's of the EDGE
8071 TGeomID edgeID = meshDS->ShapeToIndex( edge );
8072 _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
8073 if ( !eos || eos->_edges.empty() )
8075 // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
8076 for ( int iV = 0; iV < 2; ++iV )
8078 TopoDS_Vertex v = helper.IthVertex( iV, edge );
8079 TGeomID vID = meshDS->ShapeToIndex( v );
8080 eos = data.GetShapeEdges( vID );
8081 vertexLEdges[ iV ] = eos->_edges[ 0 ];
8083 edgeLEdge = &vertexLEdges[0];
8084 edgeLEdgeEnd = edgeLEdge + 2;
8086 centerCurves[ iE ]._adjFace.Nullify();
8090 if ( ! eos->_toSmooth )
8091 data.SortOnEdge( edge, eos->_edges );
8092 edgeLEdge = &eos->_edges[ 0 ];
8093 edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
8094 vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
8095 vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
8097 if ( ! eos->_sWOL.IsNull() )
8098 centerCurves[ iE ]._adjFace.Nullify();
8101 // Get curvature centers
8105 if ( edgeLEdge[0]->IsOnEdge() &&
8106 convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
8108 centerCurves[ iE ].Append( center, vertexLEdges[0] );
8109 centersBox.Add( center );
8111 for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
8112 if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
8113 { // EDGE or VERTEXes
8114 centerCurves[ iE ].Append( center, *edgeLEdge );
8115 centersBox.Add( center );
8117 if ( edgeLEdge[-1]->IsOnEdge() &&
8118 convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
8120 centerCurves[ iE ].Append( center, vertexLEdges[1] );
8121 centersBox.Add( center );
8123 centerCurves[ iE ]._isDegenerated =
8124 ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
8126 } // loop on EDGES of convFace._face to set up data of centerCurves
8128 // Compute new normals for _LayerEdge's on EDGEs
8130 double avgCosin = 0;
8133 for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
8135 _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
8136 if ( ceCurve._isDegenerated )
8138 const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
8139 vector< gp_XYZ > & newNormals = ceCurve._normals;
8140 for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
8143 for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
8146 isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
8148 if ( isOK && !ceCurve._adjFace.IsNull() )
8150 // compute new _LayerEdge::_cosin
8151 const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
8152 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
8155 double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
8156 ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
8157 avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
8163 // set new normals to _LayerEdge's of NOT degenerated central curves
8164 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
8166 if ( centerCurves[ iE ]._isDegenerated )
8168 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
8170 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
8171 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
8174 // set new normals to _LayerEdge's of degenerated central curves
8175 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
8177 if ( !centerCurves[ iE ]._isDegenerated ||
8178 centerCurves[ iE ]._ledges.size() < 3 )
8180 // new normal is an average of new normals at VERTEXes that
8181 // was computed on non-degenerated _CentralCurveOnEdge's
8182 gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
8183 centerCurves[ iE ]._ledges.back ()->_normal );
8184 double sz = newNorm.Modulus();
8188 double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
8189 0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
8190 for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
8192 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
8193 centerCurves[ iE ]._ledges[ iLE ]->_cosin = newCosin;
8194 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
8198 // Find new normals for _LayerEdge's based on FACE
8201 avgCosin /= nbCosin;
8202 const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
8203 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
8204 if ( id2eos != convFace._subIdToEOS.end() )
8208 _EdgesOnShape& eos = * ( id2eos->second );
8209 for ( size_t i = 0; i < eos._edges.size(); ++i )
8211 _LayerEdge* ledge = eos._edges[ i ];
8212 if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
8214 for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
8216 iE = iE % centerCurves.size();
8217 if ( centerCurves[ iE ]._isDegenerated )
8219 newNorm.SetCoord( 0,0,0 );
8220 if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
8222 ledge->SetNormal( newNorm );
8223 ledge->_cosin = avgCosin;
8224 ledge->Set( _LayerEdge::NORMAL_UPDATED );
8231 } // not a quasi-spherical FACE
8233 // Update _LayerEdge's data according to a new normal
8235 dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
8236 <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
8238 id2eos = convFace._subIdToEOS.begin();
8239 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
8241 _EdgesOnShape& eos = * ( id2eos->second );
8242 for ( size_t i = 0; i < eos._edges.size(); ++i )
8244 _LayerEdge* & ledge = eos._edges[ i ];
8245 double len = ledge->_len;
8246 ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
8247 ledge->SetCosin( ledge->_cosin );
8248 ledge->SetNewLength( len, eos, helper );
8250 if ( eos.ShapeType() != TopAbs_FACE )
8251 for ( size_t i = 0; i < eos._edges.size(); ++i )
8253 _LayerEdge* ledge = eos._edges[ i ];
8254 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
8256 _LayerEdge* neibor = ledge->_neibors[iN];
8257 if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
8259 neibor->Set( _LayerEdge::NEAR_BOUNDARY );
8260 neibor->Set( _LayerEdge::MOVED );
8261 neibor->SetSmooLen( neibor->_len );
8265 } // loop on sub-shapes of convFace._face
8267 // Find FACEs adjacent to convFace._face that got necessity to smooth
8268 // as a result of normals modification
8270 set< _EdgesOnShape* > adjFacesToSmooth;
8271 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
8273 if ( centerCurves[ iE ]._adjFace.IsNull() ||
8274 centerCurves[ iE ]._adjFaceToSmooth )
8276 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
8278 if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
8280 adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
8285 data.AddShapesToSmooth( adjFacesToSmooth );
8290 } // loop on data._convexFaces
8295 //================================================================================
8297 * \brief Return max curvature of a FACE
8299 //================================================================================
8301 double _ConvexFace::GetMaxCurvature( _SolidData& data,
8303 BRepLProp_SLProps& surfProp,
8304 SMESH_MesherHelper& helper)
8306 double maxCurvature = 0;
8308 TopoDS_Face F = TopoDS::Face( eof._shape );
8310 const int nbTestPnt = 5;
8311 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
8312 SMESH_subMeshIteratorPtr smIt = eof._subMesh->getDependsOnIterator(/*includeSelf=*/true);
8313 while ( smIt->more() )
8315 SMESH_subMesh* sm = smIt->next();
8316 const TGeomID subID = sm->GetId();
8318 // find _LayerEdge's of a sub-shape
8320 if (( eos = data.GetShapeEdges( subID )))
8321 this->_subIdToEOS.insert( make_pair( subID, eos ));
8325 // check concavity and curvature and limit data._stepSize
8326 const double minCurvature =
8327 1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
8328 size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
8329 for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
8331 gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
8332 surfProp.SetParameters( uv.X(), uv.Y() );
8333 if ( surfProp.IsCurvatureDefined() )
8335 double curvature = Max( surfProp.MaxCurvature() * oriFactor,
8336 surfProp.MinCurvature() * oriFactor );
8337 maxCurvature = Max( maxCurvature, curvature );
8339 if ( curvature > minCurvature )
8340 this->_isTooCurved = true;
8343 } // loop on sub-shapes of the FACE
8345 return maxCurvature;
8348 //================================================================================
8350 * \brief Finds a center of curvature of a surface at a _LayerEdge
8352 //================================================================================
8354 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge* ledge,
8355 BRepLProp_SLProps& surfProp,
8356 SMESH_MesherHelper& helper,
8357 gp_Pnt & center ) const
8359 gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
8360 surfProp.SetParameters( uv.X(), uv.Y() );
8361 if ( !surfProp.IsCurvatureDefined() )
8364 const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
8365 double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
8366 double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
8367 if ( surfCurvatureMin > surfCurvatureMax )
8368 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
8370 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
8375 //================================================================================
8377 * \brief Check that prisms are not distorted
8379 //================================================================================
8381 bool _ConvexFace::CheckPrisms() const
8384 for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
8386 const _LayerEdge* edge = _simplexTestEdges[i];
8387 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
8388 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
8389 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
8391 debugMsg( "Bad simplex of _simplexTestEdges ("
8392 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
8393 << " "<< edge->_simplices[j]._nPrev->GetID()
8394 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
8401 //================================================================================
8403 * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
8404 * stored in this _CentralCurveOnEdge.
8405 * \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
8406 * \param [in,out] newNormal - current normal at this point, to be redefined
8407 * \return bool - true if succeeded.
8409 //================================================================================
8411 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
8413 if ( this->_isDegenerated )
8416 // find two centers the given one lies between
8418 for ( size_t i = 0, nb = _curvaCenters.size()-1; i < nb; ++i )
8420 double sl2 = 1.001 * _segLength2[ i ];
8422 double d1 = center.SquareDistance( _curvaCenters[ i ]);
8426 double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
8427 if ( d2 > sl2 || d2 + d1 < 1e-100 )
8432 double r = d1 / ( d1 + d2 );
8433 gp_XYZ norm = (( 1. - r ) * _ledges[ i ]->_normal +
8434 ( r ) * _ledges[ i+1 ]->_normal );
8438 double sz = newNormal.Modulus();
8447 //================================================================================
8449 * \brief Set shape members
8451 //================================================================================
8453 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge& edge,
8454 const _ConvexFace& convFace,
8456 SMESH_MesherHelper& helper)
8460 PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
8461 while ( const TopoDS_Shape* F = fIt->next())
8462 if ( !convFace._face.IsSame( *F ))
8464 _adjFace = TopoDS::Face( *F );
8465 _adjFaceToSmooth = false;
8466 // _adjFace already in a smoothing queue ?
8467 if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
8468 _adjFaceToSmooth = eos->_toSmooth;
8473 //================================================================================
8475 * \brief Looks for intersection of it's last segment with faces
8476 * \param distance - returns shortest distance from the last node to intersection
8478 //================================================================================
8480 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
8482 const double& epsilon,
8484 const SMDS_MeshElement** intFace)
8486 vector< const SMDS_MeshElement* > suspectFaces;
8488 gp_Ax1 lastSegment = LastSegment( segLen, eos );
8489 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
8491 bool segmentIntersected = false;
8492 distance = Precision::Infinite();
8493 int iFace = -1; // intersected face
8494 for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
8496 const SMDS_MeshElement* face = suspectFaces[j];
8497 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
8498 face->GetNodeIndex( _nodes[0] ) >= 0 )
8499 continue; // face sharing _LayerEdge node
8500 const int nbNodes = face->NbCornerNodes();
8501 bool intFound = false;
8503 SMDS_MeshElement::iterator nIt = face->begin_nodes();
8506 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
8510 const SMDS_MeshNode* tria[3];
8513 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
8516 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
8522 if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
8523 segmentIntersected = true;
8524 if ( distance > dist )
8525 distance = dist, iFace = j;
8528 if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
8532 if ( segmentIntersected )
8535 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
8536 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
8537 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
8538 << ", intersection with face ("
8539 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
8540 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
8541 << ") distance = " << distance << endl;
8545 return segmentIntersected;
8548 //================================================================================
8550 * \brief Returns a point used to check orientation of _simplices
8552 //================================================================================
8554 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
8556 size_t i = Is( NORMAL_UPDATED ) && IsOnFace() ? _pos.size()-2 : 0;
8558 if ( !eos || eos->_sWOL.IsNull() )
8561 if ( eos->SWOLType() == TopAbs_EDGE )
8563 return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
8565 //else // TopAbs_FACE
8567 return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
8570 //================================================================================
8572 * \brief Returns size and direction of the last segment
8574 //================================================================================
8576 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
8578 // find two non-coincident positions
8579 gp_XYZ orig = _pos.back();
8581 int iPrev = _pos.size() - 2;
8582 //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
8583 const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
8584 while ( iPrev >= 0 )
8586 vec = orig - _pos[iPrev];
8587 if ( vec.SquareModulus() > tol*tol )
8597 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
8598 segDir.SetDirection( _normal );
8603 gp_Pnt pPrev = _pos[ iPrev ];
8604 if ( !eos._sWOL.IsNull() )
8606 TopLoc_Location loc;
8607 if ( eos.SWOLType() == TopAbs_EDGE )
8610 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8611 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
8615 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
8616 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
8618 vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
8620 segDir.SetLocation( pPrev );
8621 segDir.SetDirection( vec );
8622 segLen = vec.Modulus();
8628 //================================================================================
8630 * \brief Return the last (or \a which) position of the target node on a FACE.
8631 * \param [in] F - the FACE this _LayerEdge is inflated along
8632 * \param [in] which - index of position
8633 * \return gp_XY - result UV
8635 //================================================================================
8637 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which ) const
8639 if ( F.IsSame( eos._sWOL )) // F is my FACE
8640 return gp_XY( _pos.back().X(), _pos.back().Y() );
8642 if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
8643 return gp_XY( 1e100, 1e100 );
8645 // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
8646 double f, l, u = _pos[ which < 0 ? _pos.size()-1 : which ].X();
8647 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
8648 if ( !C2d.IsNull() && f <= u && u <= l )
8649 return C2d->Value( u ).XY();
8651 return gp_XY( 1e100, 1e100 );
8654 //================================================================================
8656 * \brief Test intersection of the last segment with a given triangle
8657 * using Moller-Trumbore algorithm
8658 * Intersection is detected if distance to intersection is less than _LayerEdge._len
8660 //================================================================================
8662 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
8663 const gp_XYZ& vert0,
8664 const gp_XYZ& vert1,
8665 const gp_XYZ& vert2,
8667 const double& EPSILON) const
8669 const gp_Pnt& orig = lastSegment.Location();
8670 const gp_Dir& dir = lastSegment.Direction();
8672 /* calculate distance from vert0 to ray origin */
8673 //gp_XYZ tvec = orig.XYZ() - vert0;
8675 //if ( tvec * dir > EPSILON )
8676 // intersected face is at back side of the temporary face this _LayerEdge belongs to
8679 gp_XYZ edge1 = vert1 - vert0;
8680 gp_XYZ edge2 = vert2 - vert0;
8682 /* begin calculating determinant - also used to calculate U parameter */
8683 gp_XYZ pvec = dir.XYZ() ^ edge2;
8685 /* if determinant is near zero, ray lies in plane of triangle */
8686 double det = edge1 * pvec;
8688 const double ANGL_EPSILON = 1e-12;
8689 if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
8692 /* calculate distance from vert0 to ray origin */
8693 gp_XYZ tvec = orig.XYZ() - vert0;
8695 /* calculate U parameter and test bounds */
8696 double u = ( tvec * pvec ) / det;
8697 //if (u < 0.0 || u > 1.0)
8698 if ( u < -EPSILON || u > 1.0 + EPSILON )
8701 /* prepare to test V parameter */
8702 gp_XYZ qvec = tvec ^ edge1;
8704 /* calculate V parameter and test bounds */
8705 double v = (dir.XYZ() * qvec) / det;
8706 //if ( v < 0.0 || u + v > 1.0 )
8707 if ( v < -EPSILON || u + v > 1.0 + EPSILON )
8710 /* calculate t, ray intersects triangle */
8711 t = (edge2 * qvec) / det;
8717 //================================================================================
8719 * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
8720 * neighbor _LayerEdge's by it's own inflation vector.
8721 * \param [in] eov - EOS of the VERTEX
8722 * \param [in] eos - EOS of the FACE
8723 * \param [in] step - inflation step
8724 * \param [in,out] badSmooEdges - tangled _LayerEdge's
8726 //================================================================================
8728 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape* eov,
8729 const _EdgesOnShape* eos,
8731 vector< _LayerEdge* > & badSmooEdges )
8733 // check if any of _neibors is in badSmooEdges
8734 if ( std::find_first_of( _neibors.begin(), _neibors.end(),
8735 badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
8738 // get all edges to move
8740 set< _LayerEdge* > edges;
8742 // find a distance between _LayerEdge on VERTEX and its neighbors
8743 gp_XYZ curPosV = SMESH_TNodeXYZ( _nodes.back() );
8745 for ( size_t i = 0; i < _neibors.size(); ++i )
8747 _LayerEdge* nEdge = _neibors[i];
8748 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
8750 edges.insert( nEdge );
8751 dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
8754 // add _LayerEdge's close to curPosV
8758 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8760 _LayerEdge* edgeF = *e;
8761 for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
8763 _LayerEdge* nEdge = edgeF->_neibors[i];
8764 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
8765 dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
8766 edges.insert( nEdge );
8770 while ( nbE < edges.size() );
8772 // move the target node of the got edges
8774 gp_XYZ prevPosV = PrevPos();
8775 if ( eov->SWOLType() == TopAbs_EDGE )
8777 BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
8778 prevPosV = curve.Value( prevPosV.X() ).XYZ();
8780 else if ( eov->SWOLType() == TopAbs_FACE )
8782 BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
8783 prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
8786 SMDS_FacePositionPtr fPos;
8787 //double r = 1. - Min( 0.9, step / 10. );
8788 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8790 _LayerEdge* edgeF = *e;
8791 const gp_XYZ prevVF = edgeF->PrevPos() - prevPosV;
8792 const gp_XYZ newPosF = curPosV + prevVF;
8793 SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8794 tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
8795 edgeF->_pos.back() = newPosF;
8796 dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
8798 // set _curvature to make edgeF updated by putOnOffsetSurface()
8799 if ( !edgeF->_curvature )
8800 if (( fPos = edgeF->_nodes[0]->GetPosition() ))
8802 edgeF->_curvature = _Factory::NewCurvature();
8803 edgeF->_curvature->_r = 0;
8804 edgeF->_curvature->_k = 0;
8805 edgeF->_curvature->_h2lenRatio = 0;
8806 edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
8809 // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
8810 // SMESH_TNodeXYZ( _nodes[0] ));
8811 // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8813 // _LayerEdge* edgeF = *e;
8814 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8815 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8816 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8817 // edgeF->_pos.back() = newPosF;
8818 // dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
8821 // smooth _LayerEdge's around moved nodes
8822 //size_t nbBadBefore = badSmooEdges.size();
8823 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8825 _LayerEdge* edgeF = *e;
8826 for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
8827 if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
8828 //&& !edges.count( edgeF->_neibors[j] ))
8830 _LayerEdge* edgeFN = edgeF->_neibors[j];
8831 edgeFN->Unset( SMOOTHED );
8832 int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
8835 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
8836 // const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
8837 // int nbBadAfter = edgeFN->_simplices.size();
8839 // for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
8841 // nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
8843 // if ( nbBadAfter <= nbBad )
8845 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
8846 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8847 // edgeF->_pos.back() = newPosF;
8848 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8849 // nbBad = nbBadAfter;
8853 badSmooEdges.push_back( edgeFN );
8856 // move a bit not smoothed around moved nodes
8857 // for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
8859 // _LayerEdge* edgeF = badSmooEdges[i];
8860 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8861 // gp_XYZ newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8862 // gp_XYZ newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
8863 // tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
8864 // edgeF->_pos.back() = newPosF;
8865 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8869 //================================================================================
8871 * \brief Perform smooth of _LayerEdge's based on EDGE's
8872 * \retval bool - true if node has been moved
8874 //================================================================================
8876 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
8877 const TopoDS_Face& F,
8878 SMESH_MesherHelper& helper)
8880 ASSERT( IsOnEdge() );
8882 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
8883 SMESH_TNodeXYZ oldPos( tgtNode );
8884 double dist01, distNewOld;
8886 SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
8887 SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
8888 dist01 = p0.Distance( _2neibors->tgtNode(1) );
8890 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
8891 double lenDelta = 0;
8894 //lenDelta = _curvature->lenDelta( _len );
8895 lenDelta = _curvature->lenDeltaByDist( dist01 );
8896 newPos.ChangeCoord() += _normal * lenDelta;
8899 distNewOld = newPos.Distance( oldPos );
8903 if ( _2neibors->_plnNorm )
8905 // put newPos on the plane defined by source node and _plnNorm
8906 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
8907 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
8908 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
8910 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8911 _pos.back() = newPos.XYZ();
8915 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8916 gp_XY uv( Precision::Infinite(), 0 );
8917 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
8918 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8920 newPos = surface->Value( uv );
8921 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8924 // commented for IPAL0052478
8925 // if ( _curvature && lenDelta < 0 )
8927 // gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
8928 // _len -= prevPos.Distance( oldPos );
8929 // _len += prevPos.Distance( newPos );
8931 bool moved = distNewOld > dist01/50;
8933 dumpMove( tgtNode ); // debug
8938 //================================================================================
8940 * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
8942 //================================================================================
8944 void _LayerEdge::SmoothWoCheck()
8946 if ( Is( DIFFICULT ))
8949 bool moved = Is( SMOOTHED );
8950 for ( size_t i = 0; i < _neibors.size() && !moved; ++i )
8951 moved = _neibors[i]->Is( SMOOTHED );
8955 gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8957 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8958 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8959 _pos.back() = newPos;
8961 dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
8964 //================================================================================
8966 * \brief Checks validity of _neibors on EDGEs and VERTEXes
8968 //================================================================================
8970 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
8972 if ( ! Is( NEAR_BOUNDARY ))
8977 for ( size_t iN = 0; iN < _neibors.size(); ++iN )
8979 _LayerEdge* eN = _neibors[iN];
8980 if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
8983 *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
8984 eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
8985 eN->_pos.size() != _pos.size() );
8987 SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
8988 SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
8989 for ( size_t i = 0; i < eN->_simplices.size(); ++i )
8990 if ( eN->_nodes.size() > 1 &&
8991 eN->_simplices[i].Includes( _nodes.back() ) &&
8992 !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
8997 badNeibors->push_back( eN );
8998 debugMsg("Bad boundary simplex ( "
8999 << " "<< eN->_nodes[0]->GetID()
9000 << " "<< eN->_nodes.back()->GetID()
9001 << " "<< eN->_simplices[i]._nPrev->GetID()
9002 << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
9013 //================================================================================
9015 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
9016 * \retval int - nb of bad simplices around this _LayerEdge
9018 //================================================================================
9020 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
9022 if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
9023 return 0; // shape of simplices not changed
9024 if ( _simplices.size() < 2 )
9025 return 0; // _LayerEdge inflated along EDGE or FACE
9027 if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
9030 const gp_XYZ& curPos = _pos.back();
9031 const gp_XYZ& prevPos = _pos[0]; //PrevPos();
9033 // quality metrics (orientation) of tetras around _tgtNode
9035 double vol, minVolBefore = 1e100;
9036 for ( size_t i = 0; i < _simplices.size(); ++i )
9038 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
9039 minVolBefore = Min( minVolBefore, vol );
9041 int nbBad = _simplices.size() - nbOkBefore;
9043 bool bndNeedSmooth = false;
9045 nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
9049 // evaluate min angle
9050 if ( nbBad == 0 && !findBest && !bndNeedSmooth )
9052 size_t nbGoodAngles = _simplices.size();
9054 for ( size_t i = 0; i < _simplices.size(); ++i )
9056 if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
9059 if ( nbGoodAngles == _simplices.size() )
9065 if ( Is( ON_CONCAVE_FACE ))
9068 if ( step % 2 == 0 )
9071 if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
9073 if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
9074 _smooFunction = _funs[ FUN_CENTROIDAL ];
9076 _smooFunction = _funs[ FUN_LAPLACIAN ];
9079 // compute new position for the last _pos using different _funs
9082 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
9085 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
9086 else if ( _funs[ iFun ] == _smooFunction )
9087 continue; // _smooFunction again
9088 else if ( step > 1 )
9089 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
9091 break; // let "easy" functions improve elements around distorted ones
9095 double delta = _curvature->lenDelta( _len );
9097 newPos += _normal * delta;
9100 double segLen = _normal * ( newPos - prevPos );
9101 if ( segLen + delta > 0 )
9102 newPos += _normal * delta;
9104 // double segLenChange = _normal * ( curPos - newPos );
9105 // newPos += 0.5 * _normal * segLenChange;
9109 double minVolAfter = 1e100;
9110 for ( size_t i = 0; i < _simplices.size(); ++i )
9112 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
9113 minVolAfter = Min( minVolAfter, vol );
9116 if ( nbOkAfter < nbOkBefore )
9120 ( nbOkAfter == nbOkBefore ) &&
9121 ( minVolAfter <= minVolBefore ))
9124 nbBad = _simplices.size() - nbOkAfter;
9125 minVolBefore = minVolAfter;
9126 nbOkBefore = nbOkAfter;
9129 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
9130 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
9131 _pos.back() = newPos;
9133 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
9134 << (nbBad ? " --BAD" : ""));
9138 continue; // look for a better function
9144 } // loop on smoothing functions
9146 if ( moved ) // notify _neibors
9149 for ( size_t i = 0; i < _neibors.size(); ++i )
9150 if ( !_neibors[i]->Is( MOVED ))
9152 _neibors[i]->Set( MOVED );
9153 toSmooth.push_back( _neibors[i] );
9160 //================================================================================
9162 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
9163 * \retval int - nb of bad simplices around this _LayerEdge
9165 //================================================================================
9167 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
9169 if ( !_smooFunction )
9170 return 0; // _LayerEdge inflated along EDGE or FACE
9172 return 0; // not inflated
9174 const gp_XYZ& curPos = _pos.back();
9175 const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
9177 // quality metrics (orientation) of tetras around _tgtNode
9179 double vol, minVolBefore = 1e100;
9180 for ( size_t i = 0; i < _simplices.size(); ++i )
9182 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
9183 minVolBefore = Min( minVolBefore, vol );
9185 int nbBad = _simplices.size() - nbOkBefore;
9187 if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
9189 if ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
9190 _smooFunction = _funs[ FUN_LAPLACIAN ];
9191 else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
9192 _smooFunction = _funs[ FUN_CENTROIDAL ];
9195 // compute new position for the last _pos using different _funs
9197 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
9200 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
9201 else if ( _funs[ iFun ] == _smooFunction )
9202 continue; // _smooFunction again
9203 else if ( step > 1 )
9204 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
9206 break; // let "easy" functions improve elements around distorted ones
9210 double delta = _curvature->lenDelta( _len );
9212 newPos += _normal * delta;
9215 double segLen = _normal * ( newPos - prevPos );
9216 if ( segLen + delta > 0 )
9217 newPos += _normal * delta;
9219 // double segLenChange = _normal * ( curPos - newPos );
9220 // newPos += 0.5 * _normal * segLenChange;
9224 double minVolAfter = 1e100;
9225 for ( size_t i = 0; i < _simplices.size(); ++i )
9227 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
9228 minVolAfter = Min( minVolAfter, vol );
9231 if ( nbOkAfter < nbOkBefore )
9233 if (( isConcaveFace || findBest ) &&
9234 ( nbOkAfter == nbOkBefore ) &&
9235 ( minVolAfter <= minVolBefore )
9239 nbBad = _simplices.size() - nbOkAfter;
9240 minVolBefore = minVolAfter;
9241 nbOkBefore = nbOkAfter;
9243 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
9244 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
9245 _pos.back() = newPos;
9247 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
9248 << ( nbBad ? "--BAD" : ""));
9250 // commented for IPAL0052478
9251 // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
9252 // _len += prevPos.Distance(newPos);
9254 if ( iFun > -1 ) // findBest || the chosen _fun makes worse
9256 //_smooFunction = _funs[ iFun ];
9257 // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
9258 // << "\t nbBad: " << _simplices.size() - nbOkAfter
9259 // << " minVol: " << minVolAfter
9260 // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
9262 continue; // look for a better function
9268 } // loop on smoothing functions
9273 //================================================================================
9275 * \brief Chooses a smoothing technique giving a position most close to an initial one.
9276 * For a correct result, _simplices must contain nodes lying on geometry.
9278 //================================================================================
9280 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
9281 const TNode2Edge& /*n2eMap*/)
9283 if ( _smooFunction ) return;
9285 // use smoothNefPolygon() near concaveVertices
9286 if ( !concaveVertices.empty() )
9288 _smooFunction = _funs[ FUN_CENTROIDAL ];
9290 Set( ON_CONCAVE_FACE );
9292 for ( size_t i = 0; i < _simplices.size(); ++i )
9294 if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
9296 _smooFunction = _funs[ FUN_NEFPOLY ];
9298 // set FUN_CENTROIDAL to neighbor edges
9299 for ( i = 0; i < _neibors.size(); ++i )
9301 if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
9303 _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
9310 // // this choice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
9311 // // where the nodes are smoothed too far along a sphere thus creating
9312 // // inverted _simplices
9313 // double dist[theNbSmooFuns];
9314 // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
9315 // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
9317 // double minDist = Precision::Infinite();
9318 // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
9319 // for ( int i = 0; i < FUN_NEFPOLY; ++i )
9321 // gp_Pnt newP = (this->*_funs[i])();
9322 // dist[i] = p.SquareDistance( newP );
9323 // if ( dist[i]*coef[i] < minDist )
9325 // _smooFunction = _funs[i];
9326 // minDist = dist[i]*coef[i];
9332 _smooFunction = _funs[ FUN_LAPLACIAN ];
9335 // for ( size_t i = 0; i < _simplices.size(); ++i )
9336 // minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
9337 // if ( minDim == 0 )
9338 // _smooFunction = _funs[ FUN_CENTROIDAL ];
9339 // else if ( minDim == 1 )
9340 // _smooFunction = _funs[ FUN_CENTROIDAL ];
9344 // for ( int i = 0; i < FUN_NB; ++i )
9346 // //cout << dist[i] << " ";
9347 // if ( _smooFunction == _funs[i] ) {
9349 // //debugMsg( fNames[i] );
9353 // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
9356 //================================================================================
9358 * \brief Returns a name of _SmooFunction
9360 //================================================================================
9362 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
9365 fun = _smooFunction;
9366 for ( int i = 0; i < theNbSmooFuns; ++i )
9367 if ( fun == _funs[i] )
9370 return theNbSmooFuns;
9373 //================================================================================
9375 * \brief Computes a new node position using Laplacian smoothing
9377 //================================================================================
9379 gp_XYZ _LayerEdge::smoothLaplacian()
9381 gp_XYZ newPos (0,0,0);
9382 for ( size_t i = 0; i < _simplices.size(); ++i )
9383 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9384 newPos /= _simplices.size();
9389 //================================================================================
9391 * \brief Computes a new node position using angular-based smoothing
9393 //================================================================================
9395 gp_XYZ _LayerEdge::smoothAngular()
9397 vector< gp_Vec > edgeDir; edgeDir. reserve( _simplices.size() + 1 );
9398 vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
9399 vector< gp_XYZ > points; points. reserve( _simplices.size() + 1 );
9401 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
9403 for ( size_t i = 0; i < _simplices.size(); ++i )
9405 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9406 edgeDir.push_back( p - pPrev );
9407 edgeSize.push_back( edgeDir.back().Magnitude() );
9408 if ( edgeSize.back() < numeric_limits<double>::min() )
9411 edgeSize.pop_back();
9415 edgeDir.back() /= edgeSize.back();
9416 points.push_back( p );
9421 edgeDir.push_back ( edgeDir[0] );
9422 edgeSize.push_back( edgeSize[0] );
9423 pN /= points.size();
9425 gp_XYZ newPos(0,0,0);
9427 for ( size_t i = 0; i < points.size(); ++i )
9429 gp_Vec toN = pN - points[i];
9430 double toNLen = toN.Magnitude();
9431 if ( toNLen < numeric_limits<double>::min() )
9436 gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
9437 double bisecLen = bisec.SquareMagnitude();
9438 if ( bisecLen < numeric_limits<double>::min() )
9440 gp_Vec norm = edgeDir[i] ^ toN;
9441 bisec = norm ^ edgeDir[i];
9442 bisecLen = bisec.SquareMagnitude();
9444 bisecLen = Sqrt( bisecLen );
9448 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
9449 sumSize += bisecLen;
9451 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
9452 sumSize += ( edgeSize[i] + edgeSize[i+1] );
9458 // project newPos to an average plane
9460 gp_XYZ norm(0,0,0); // plane normal
9461 points.push_back( points[0] );
9462 for ( size_t i = 1; i < points.size(); ++i )
9464 gp_XYZ vec1 = points[ i-1 ] - pN;
9465 gp_XYZ vec2 = points[ i ] - pN;
9466 gp_XYZ cross = vec1 ^ vec2;
9469 if ( cross * norm < numeric_limits<double>::min() )
9470 norm += cross.Reversed();
9474 catch (Standard_Failure&) { // if |cross| == 0.
9477 gp_XYZ vec = newPos - pN;
9478 double r = ( norm * vec ) / norm.SquareModulus(); // param [0,1] on norm
9479 newPos = newPos - r * norm;
9484 //================================================================================
9486 * \brief Computes a new node position using weighted node positions
9488 //================================================================================
9490 gp_XYZ _LayerEdge::smoothLengthWeighted()
9492 vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
9493 vector< gp_XYZ > points; points. reserve( _simplices.size() );
9495 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
9496 for ( size_t i = 0; i < _simplices.size(); ++i )
9498 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9499 edgeSize.push_back( ( p - pPrev ).Modulus() );
9500 if ( edgeSize.back() < numeric_limits<double>::min() )
9502 edgeSize.pop_back();
9506 points.push_back( p );
9510 edgeSize.push_back( edgeSize[0] );
9512 gp_XYZ newPos(0,0,0);
9514 for ( size_t i = 0; i < points.size(); ++i )
9516 newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
9517 sumSize += edgeSize[i] + edgeSize[i+1];
9523 //================================================================================
9525 * \brief Computes a new node position using angular-based smoothing
9527 //================================================================================
9529 gp_XYZ _LayerEdge::smoothCentroidal()
9531 gp_XYZ newPos(0,0,0);
9532 gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
9534 for ( size_t i = 0; i < _simplices.size(); ++i )
9536 gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9537 gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
9538 gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
9539 double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
9542 newPos += gc * size;
9549 //================================================================================
9551 * \brief Computes a new node position located inside a Nef polygon
9553 //================================================================================
9555 gp_XYZ _LayerEdge::smoothNefPolygon()
9556 #ifdef OLD_NEF_POLYGON
9558 gp_XYZ newPos(0,0,0);
9560 // get a plane to search a solution on
9562 vector< gp_XYZ > vecs( _simplices.size() + 1 );
9564 const double tol = numeric_limits<double>::min();
9565 gp_XYZ center(0,0,0);
9566 for ( i = 0; i < _simplices.size(); ++i )
9568 vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
9569 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
9570 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9572 vecs.back() = vecs[0];
9573 center /= _simplices.size();
9575 gp_XYZ zAxis(0,0,0);
9576 for ( i = 0; i < _simplices.size(); ++i )
9577 zAxis += vecs[i] ^ vecs[i+1];
9580 for ( i = 0; i < _simplices.size(); ++i )
9583 if ( yAxis.SquareModulus() > tol )
9586 gp_XYZ xAxis = yAxis ^ zAxis;
9587 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9588 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9589 // p0.Distance( _simplices[2]._nPrev ));
9590 // gp_XYZ center = smoothLaplacian();
9591 // gp_XYZ xAxis, yAxis, zAxis;
9592 // for ( i = 0; i < _simplices.size(); ++i )
9594 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9595 // if ( xAxis.SquareModulus() > tol*tol )
9598 // for ( i = 1; i < _simplices.size(); ++i )
9600 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9601 // zAxis = xAxis ^ yAxis;
9602 // if ( zAxis.SquareModulus() > tol*tol )
9605 // if ( i == _simplices.size() ) return newPos;
9607 yAxis = zAxis ^ xAxis;
9608 xAxis /= xAxis.Modulus();
9609 yAxis /= yAxis.Modulus();
9611 // get half-planes of _simplices
9613 vector< _halfPlane > halfPlns( _simplices.size() );
9615 for ( size_t i = 0; i < _simplices.size(); ++i )
9617 gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9618 gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
9619 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
9620 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
9621 gp_XY vec12 = p2 - p1;
9622 double dist12 = vec12.Modulus();
9626 halfPlns[ nbHP ]._pos = p1;
9627 halfPlns[ nbHP ]._dir = vec12;
9628 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9632 // intersect boundaries of half-planes, define state of intersection points
9633 // in relation to all half-planes and calculate internal point of a 2D polygon
9636 gp_XY newPos2D (0,0);
9638 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9639 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9640 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9642 vector< vector< TIntPntState > > allIntPnts( nbHP );
9643 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9645 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9646 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9648 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9649 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9652 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9654 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9656 if ( iHP1 == iHP2 ) continue;
9658 TIntPntState & ips1 = intPnts1[ iHP2 ];
9659 if ( ips1.second == UNDEF )
9661 // find an intersection point of boundaries of iHP1 and iHP2
9663 if ( iHP2 == iPrev ) // intersection with neighbors is known
9664 ips1.first = halfPlns[ iHP1 ]._pos;
9665 else if ( iHP2 == iNext )
9666 ips1.first = halfPlns[ iHP2 ]._pos;
9667 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9668 ips1.second = NO_INT;
9670 // classify the found intersection point
9671 if ( ips1.second != NO_INT )
9673 ips1.second = NOT_OUT;
9674 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9675 if ( i != iHP1 && i != iHP2 &&
9676 halfPlns[ i ].IsOut( ips1.first, tol ))
9677 ips1.second = IS_OUT;
9679 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9680 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9681 TIntPntState & ips2 = intPnts2[ iHP1 ];
9684 if ( ips1.second == NOT_OUT )
9687 segEnds[ bool(segEnds[0]) ] = & ips1.first;
9691 // find a NOT_OUT segment of boundary which is located between
9692 // two NOT_OUT int points
9695 continue; // no such a segment
9699 // sort points along the boundary
9700 map< double, TIntPntState* > ipsByParam;
9701 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9703 TIntPntState & ips1 = intPnts1[ iHP2 ];
9704 if ( ips1.second != NO_INT )
9706 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
9707 double param = op * halfPlns[ iHP1 ]._dir;
9708 ipsByParam.insert( make_pair( param, & ips1 ));
9711 // look for two neighboring NOT_OUT points
9713 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9714 for ( ; u2ips != ipsByParam.end(); ++u2ips )
9716 TIntPntState & ips1 = *(u2ips->second);
9717 if ( ips1.second == NOT_OUT )
9718 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9719 else if ( nbNotOut >= 2 )
9726 if ( nbNotOut >= 2 )
9728 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9731 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9738 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9747 #else // OLD_NEF_POLYGON
9748 { ////////////////////////////////// NEW
9749 gp_XYZ newPos(0,0,0);
9751 // get a plane to search a solution on
9754 gp_XYZ center(0,0,0);
9755 for ( i = 0; i < _simplices.size(); ++i )
9756 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9757 center /= _simplices.size();
9759 vector< gp_XYZ > vecs( _simplices.size() + 1 );
9760 for ( i = 0; i < _simplices.size(); ++i )
9761 vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9762 vecs.back() = vecs[0];
9764 const double tol = numeric_limits<double>::min();
9765 gp_XYZ zAxis(0,0,0);
9766 for ( i = 0; i < _simplices.size(); ++i )
9768 gp_XYZ cross = vecs[i] ^ vecs[i+1];
9771 if ( cross * zAxis < tol )
9772 zAxis += cross.Reversed();
9776 catch (Standard_Failure) { // if |cross| == 0.
9781 for ( i = 0; i < _simplices.size(); ++i )
9784 if ( yAxis.SquareModulus() > tol )
9787 gp_XYZ xAxis = yAxis ^ zAxis;
9788 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9789 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9790 // p0.Distance( _simplices[2]._nPrev ));
9791 // gp_XYZ center = smoothLaplacian();
9792 // gp_XYZ xAxis, yAxis, zAxis;
9793 // for ( i = 0; i < _simplices.size(); ++i )
9795 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9796 // if ( xAxis.SquareModulus() > tol*tol )
9799 // for ( i = 1; i < _simplices.size(); ++i )
9801 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9802 // zAxis = xAxis ^ yAxis;
9803 // if ( zAxis.SquareModulus() > tol*tol )
9806 // if ( i == _simplices.size() ) return newPos;
9808 yAxis = zAxis ^ xAxis;
9809 xAxis /= xAxis.Modulus();
9810 yAxis /= yAxis.Modulus();
9812 // get half-planes of _simplices
9814 vector< _halfPlane > halfPlns( _simplices.size() );
9816 for ( size_t i = 0; i < _simplices.size(); ++i )
9818 const gp_XYZ& OP1 = vecs[ i ];
9819 const gp_XYZ& OP2 = vecs[ i+1 ];
9820 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
9821 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
9822 gp_XY vec12 = p2 - p1;
9823 double dist12 = vec12.Modulus();
9827 halfPlns[ nbHP ]._pos = p1;
9828 halfPlns[ nbHP ]._dir = vec12;
9829 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9833 // intersect boundaries of half-planes, define state of intersection points
9834 // in relation to all half-planes and calculate internal point of a 2D polygon
9837 gp_XY newPos2D (0,0);
9839 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9840 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9841 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9843 vector< vector< TIntPntState > > allIntPnts( nbHP );
9844 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9846 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9847 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9849 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9850 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9853 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9855 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9857 if ( iHP1 == iHP2 ) continue;
9859 TIntPntState & ips1 = intPnts1[ iHP2 ];
9860 if ( ips1.second == UNDEF )
9862 // find an intersection point of boundaries of iHP1 and iHP2
9864 if ( iHP2 == iPrev ) // intersection with neighbors is known
9865 ips1.first = halfPlns[ iHP1 ]._pos;
9866 else if ( iHP2 == iNext )
9867 ips1.first = halfPlns[ iHP2 ]._pos;
9868 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9869 ips1.second = NO_INT;
9871 // classify the found intersection point
9872 if ( ips1.second != NO_INT )
9874 ips1.second = NOT_OUT;
9875 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9876 if ( i != iHP1 && i != iHP2 &&
9877 halfPlns[ i ].IsOut( ips1.first, tol ))
9878 ips1.second = IS_OUT;
9880 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9881 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9882 TIntPntState & ips2 = intPnts2[ iHP1 ];
9885 if ( ips1.second == NOT_OUT )
9888 segEnds[ bool(segEnds[0]) ] = & ips1.first;
9892 // find a NOT_OUT segment of boundary which is located between
9893 // two NOT_OUT int points
9896 continue; // no such a segment
9900 // sort points along the boundary
9901 map< double, TIntPntState* > ipsByParam;
9902 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9904 TIntPntState & ips1 = intPnts1[ iHP2 ];
9905 if ( ips1.second != NO_INT )
9907 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
9908 double param = op * halfPlns[ iHP1 ]._dir;
9909 ipsByParam.insert( make_pair( param, & ips1 ));
9912 // look for two neighboring NOT_OUT points
9914 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9915 for ( ; u2ips != ipsByParam.end(); ++u2ips )
9917 TIntPntState & ips1 = *(u2ips->second);
9918 if ( ips1.second == NOT_OUT )
9919 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9920 else if ( nbNotOut >= 2 )
9927 if ( nbNotOut >= 2 )
9929 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9932 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9939 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9948 #endif // OLD_NEF_POLYGON
9950 //================================================================================
9952 * \brief Add a new segment to _LayerEdge during inflation
9954 //================================================================================
9956 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
9961 if ( len > _maxLen )
9964 Block( eos.GetData() );
9966 const double lenDelta = len - _len;
9967 // if ( lenDelta < 0 )
9969 if ( lenDelta < len * 1e-3 )
9971 Block( eos.GetData() );
9975 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9976 gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
9978 if ( eos._hyp.IsOffsetMethod() )
9982 SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
9983 while ( faceIt->more() )
9985 const SMDS_MeshElement* face = faceIt->next();
9986 if ( !eos.GetNormal( face, faceNorm ))
9989 // translate plane of a face
9990 gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
9992 // find point of intersection of the face plane located at baryCenter
9993 // and _normal located at newXYZ
9994 double d = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
9995 double dot = ( faceNorm.XYZ() * _normal );
9996 if ( dot < std::numeric_limits<double>::min() )
9997 dot = lenDelta * 1e-3;
9998 double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
9999 newXYZ += step * _normal;
10001 _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
10005 newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
10008 n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
10009 _pos.push_back( newXYZ );
10011 if ( !eos._sWOL.IsNull() )
10012 if ( !UpdatePositionOnSWOL( n, 2*lenDelta, eos, helper ))
10014 n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
10016 Block( eos.GetData() );
10023 if ( eos.ShapeType() != TopAbs_FACE )
10025 for ( size_t i = 0; i < _neibors.size(); ++i )
10026 //if ( _len > _neibors[i]->GetSmooLen() )
10027 _neibors[i]->Set( MOVED );
10031 dumpMove( n ); //debug
10035 //================================================================================
10037 * \brief Update last position on SWOL by projecting node on SWOL
10039 //================================================================================
10041 bool _LayerEdge::UpdatePositionOnSWOL( SMDS_MeshNode* n,
10043 _EdgesOnShape& eos,
10044 SMESH_MesherHelper& helper )
10048 if ( eos.SWOLType() == TopAbs_EDGE )
10050 double u = Precision::Infinite(); // to force projection w/o distance check
10051 uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u, tol, /*force=*/true, distXYZ );
10052 _pos.back().SetCoord( u, 0, 0 );
10053 if ( _nodes.size() > 1 && uvOK )
10055 SMDS_EdgePositionPtr pos = n->GetPosition();
10056 pos->SetUParameter( u );
10059 else // TopAbs_FACE
10061 gp_XY uv( Precision::Infinite(), 0 );
10062 uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv, tol, /*force=*/true, distXYZ );
10063 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
10064 if ( _nodes.size() > 1 && uvOK )
10066 SMDS_FacePositionPtr pos = n->GetPosition();
10067 pos->SetUParameter( uv.X() );
10068 pos->SetVParameter( uv.Y() );
10073 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
10078 //================================================================================
10080 * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
10082 //================================================================================
10084 void _LayerEdge::Block( _SolidData& data )
10086 //if ( Is( BLOCKED )) return;
10089 SMESH_Comment msg( "#BLOCK shape=");
10090 msg << data.GetShapeEdges( this )->_shapeID
10091 << ", nodes " << _nodes[0]->GetID() << ", " << _nodes.back()->GetID();
10092 dumpCmd( msg + " -- BEGIN");
10095 std::queue<_LayerEdge*> queue;
10096 queue.push( this );
10098 gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
10099 while ( !queue.empty() )
10101 _LayerEdge* edge = queue.front(); queue.pop();
10102 pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
10103 pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
10104 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
10106 _LayerEdge* neibor = edge->_neibors[iN];
10107 if ( neibor->_maxLen < edge->_maxLen * 1.01 )
10109 pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
10110 pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
10111 double minDist = pSrc.SquareDistance( pSrcN );
10112 minDist = Min( pTgt.SquareDistance( pTgtN ), minDist );
10113 minDist = Min( pSrc.SquareDistance( pTgtN ), minDist );
10114 minDist = Min( pTgt.SquareDistance( pSrcN ), minDist );
10115 double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
10116 //if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() ) viscous_layers_00/A3
10118 //newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
10119 // newMaxLen *= Min( edge->_lenFactor / neibor->_lenFactor,
10120 // neibor->_lenFactor / edge->_lenFactor );
10122 if ( neibor->_maxLen > newMaxLen )
10124 neibor->SetMaxLen( newMaxLen );
10125 if ( neibor->_maxLen < neibor->_len )
10127 _EdgesOnShape* eos = data.GetShapeEdges( neibor );
10128 int lastStep = neibor->Is( BLOCKED ) ? 1 : 0;
10129 while ( neibor->_len > neibor->_maxLen &&
10130 neibor->NbSteps() > lastStep )
10131 neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
10132 neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
10133 //neibor->Block( data );
10135 queue.push( neibor );
10139 dumpCmd( msg + " -- END");
10142 //================================================================================
10144 * \brief Remove last inflation step
10146 //================================================================================
10148 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
10150 if ( _pos.size() > curStep && _nodes.size() > 1 )
10152 _pos.resize( curStep );
10154 gp_Pnt nXYZ = _pos.back();
10155 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
10156 SMESH_TNodeXYZ curXYZ( n );
10157 if ( !eos._sWOL.IsNull() )
10159 TopLoc_Location loc;
10160 if ( eos.SWOLType() == TopAbs_EDGE )
10162 SMDS_EdgePositionPtr pos = n->GetPosition();
10163 pos->SetUParameter( nXYZ.X() );
10165 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
10166 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
10170 SMDS_FacePositionPtr pos = n->GetPosition();
10171 pos->SetUParameter( nXYZ.X() );
10172 pos->SetVParameter( nXYZ.Y() );
10173 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
10174 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
10177 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
10180 if ( restoreLength )
10182 if ( NbSteps() == 0 )
10184 else if ( IsOnFace() && Is( MOVED ))
10185 _len = ( nXYZ.XYZ() - SMESH_NodeXYZ( _nodes[0] )) * _normal;
10187 _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
10193 //================================================================================
10195 * \brief Return index of a _pos distant from _normal
10197 //================================================================================
10199 int _LayerEdge::GetSmoothedPos( const double tol )
10202 for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
10204 double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
10205 if ( normDist > tol * tol )
10211 //================================================================================
10213 * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
10215 //================================================================================
10217 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
10219 if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
10222 // find the 1st smoothed _pos
10223 int iSmoothed = GetSmoothedPos( tol );
10224 if ( !iSmoothed ) return;
10226 gp_XYZ normal = _normal;
10227 if ( Is( NORMAL_UPDATED ))
10230 for ( size_t i = 0; i < _neibors.size(); ++i )
10232 if ( _neibors[i]->IsOnFace() )
10234 double dot = _normal * _neibors[i]->_normal;
10235 if ( dot < minDot )
10237 normal = _neibors[i]->_normal;
10242 if ( minDot == 1. )
10243 for ( size_t i = 1; i < _pos.size(); ++i )
10245 normal = _pos[i] - _pos[0];
10246 double size = normal.Modulus();
10247 if ( size > RealSmall() )
10254 const double r = 0.2;
10255 for ( int iter = 0; iter < 50; ++iter )
10258 for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
10260 gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
10261 gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
10263 double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
10264 double newLen = ( 1-r ) * midLen + r * segLen[i];
10265 const_cast< double& >( segLen[i] ) = newLen;
10266 // check angle between normal and (_pos[i+1], _pos[i] )
10267 gp_XYZ posDir = _pos[i+1] - _pos[i];
10268 double size = posDir.SquareModulus();
10269 if ( size > RealSmall() )
10270 minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
10272 if ( minDot > 0.5 * 0.5 )
10278 //================================================================================
10280 * \brief Print flags
10282 //================================================================================
10284 std::string _LayerEdge::DumpFlags() const
10286 SMESH_Comment dump;
10287 for ( int flag = 1; flag < 0x1000000; flag *= 2 )
10288 if ( _flags & flag )
10290 EFlags f = (EFlags) flag;
10292 case TO_SMOOTH: dump << "TO_SMOOTH"; break;
10293 case MOVED: dump << "MOVED"; break;
10294 case SMOOTHED: dump << "SMOOTHED"; break;
10295 case DIFFICULT: dump << "DIFFICULT"; break;
10296 case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
10297 case BLOCKED: dump << "BLOCKED"; break;
10298 case INTERSECTED: dump << "INTERSECTED"; break;
10299 case NORMAL_UPDATED: dump << "NORMAL_UPDATED"; break;
10300 case UPD_NORMAL_CONV: dump << "UPD_NORMAL_CONV"; break;
10301 case MARKED: dump << "MARKED"; break;
10302 case MULTI_NORMAL: dump << "MULTI_NORMAL"; break;
10303 case NEAR_BOUNDARY: dump << "NEAR_BOUNDARY"; break;
10304 case SMOOTHED_C1: dump << "SMOOTHED_C1"; break;
10305 case DISTORTED: dump << "DISTORTED"; break;
10306 case RISKY_SWOL: dump << "RISKY_SWOL"; break;
10307 case SHRUNK: dump << "SHRUNK"; break;
10308 case UNUSED_FLAG: dump << "UNUSED_FLAG"; break;
10312 cout << dump << endl;
10317 //================================================================================
10319 * \brief Create layers of prisms
10321 //================================================================================
10323 bool _ViscousBuilder::refine(_SolidData& data)
10325 SMESH_MesherHelper& helper = data.GetHelper();
10326 helper.SetElementsOnShape(false);
10328 Handle(Geom_Curve) curve;
10329 Handle(ShapeAnalysis_Surface) surface;
10330 TopoDS_Edge geomEdge;
10331 TopoDS_Face geomFace;
10332 TopLoc_Location loc;
10335 vector< gp_XYZ > pos3D;
10336 bool isOnEdge, isTooConvexFace = false;
10337 TGeomID prevBaseId = -1;
10338 TNode2Edge* n2eMap = 0;
10339 TNode2Edge::iterator n2e;
10341 // Create intermediate nodes on each _LayerEdge
10343 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
10345 _EdgesOnShape& eos = data._edgesOnShape[iS];
10346 if ( eos._edges.empty() ) continue;
10348 if ( eos._edges[0]->_nodes.size() < 2 )
10349 continue; // on _noShrinkShapes
10351 // get data of a shrink shape
10353 geomEdge.Nullify(); geomFace.Nullify();
10354 curve.Nullify(); surface.Nullify();
10355 if ( !eos._sWOL.IsNull() )
10357 isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
10360 geomEdge = TopoDS::Edge( eos._sWOL );
10361 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
10365 geomFace = TopoDS::Face( eos._sWOL );
10366 surface = helper.GetSurface( geomFace );
10369 else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
10371 geomFace = TopoDS::Face( eos._shape );
10372 surface = helper.GetSurface( geomFace );
10373 // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
10374 for ( size_t i = 0; i < eos._eosC1.size(); ++i )
10375 eos._eosC1[ i ]->_toSmooth = true;
10377 isTooConvexFace = false;
10378 if ( _ConvexFace* cf = data.GetConvexFace( eos._shapeID ))
10379 isTooConvexFace = cf->_isTooCurved;
10382 vector< double > segLen;
10383 for ( size_t i = 0; i < eos._edges.size(); ++i )
10385 _LayerEdge& edge = *eos._edges[i];
10386 if ( edge._pos.size() < 2 )
10389 // get accumulated length of segments
10390 segLen.resize( edge._pos.size() );
10392 if ( eos._sWOL.IsNull() )
10394 bool useNormal = true;
10395 bool usePos = false;
10396 bool smoothed = false;
10397 double preci = 0.1 * edge._len;
10398 if ( eos._toSmooth && edge._pos.size() > 2 )
10400 smoothed = edge.GetSmoothedPos( preci );
10404 if ( !surface.IsNull() && !isTooConvexFace ) // edge smoothed on FACE
10406 useNormal = usePos = false;
10407 gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
10408 for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
10410 uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
10411 if ( surface->Gap() < 2. * edge._len )
10412 segLen[j] = surface->Gap();
10418 else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
10420 #ifndef __NODES_AT_POS
10421 useNormal = usePos = false;
10422 edge._pos[1] = edge._pos.back();
10423 edge._pos.resize( 2 );
10424 segLen.resize( 2 );
10425 segLen[ 1 ] = edge._len;
10428 if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
10430 useNormal = usePos = false;
10431 _LayerEdge tmpEdge; // get original _normal
10432 tmpEdge._nodes.push_back( edge._nodes[0] );
10433 if ( !setEdgeData( tmpEdge, eos, helper, data ))
10436 for ( size_t j = 1; j < edge._pos.size(); ++j )
10437 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
10441 for ( size_t j = 1; j < edge._pos.size(); ++j )
10442 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
10446 for ( size_t j = 1; j < edge._pos.size(); ++j )
10447 segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
10451 bool swapped = ( edge._pos.size() > 2 );
10455 for ( size_t j = 1; j < edge._pos.size()-1; ++j )
10456 if ( segLen[j] > segLen.back() )
10458 segLen.erase( segLen.begin() + j );
10459 edge._pos.erase( edge._pos.begin() + j );
10462 else if ( segLen[j] < segLen[j-1] )
10464 std::swap( segLen[j], segLen[j-1] );
10465 std::swap( edge._pos[j], edge._pos[j-1] );
10470 // smooth a path formed by edge._pos
10471 #ifndef __NODES_AT_POS
10472 if (( smoothed ) /*&&
10473 ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
10474 edge.SmoothPos( segLen, preci );
10477 else if ( eos._isRegularSWOL ) // usual SWOL
10479 if ( edge.Is( _LayerEdge::SMOOTHED ))
10481 SMESH_NodeXYZ p0( edge._nodes[0] );
10482 for ( size_t j = 1; j < edge._pos.size(); ++j )
10484 gp_XYZ pj = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
10485 segLen[j] = ( pj - p0 ) * edge._normal;
10490 for ( size_t j = 1; j < edge._pos.size(); ++j )
10491 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
10494 else // SWOL is surface with singularities or irregularly parametrized curve
10496 pos3D.resize( edge._pos.size() );
10498 if ( !surface.IsNull() )
10499 for ( size_t j = 0; j < edge._pos.size(); ++j )
10500 pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
10501 else if ( !curve.IsNull() )
10502 for ( size_t j = 0; j < edge._pos.size(); ++j )
10503 pos3D[j] = curve->Value( edge._pos[j].X() ).XYZ();
10505 for ( size_t j = 1; j < edge._pos.size(); ++j )
10506 segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
10509 // allocate memory for new nodes if it is not yet refined
10510 const SMDS_MeshNode* tgtNode = edge._nodes.back();
10511 if ( edge._nodes.size() == 2 )
10513 #ifdef __NODES_AT_POS
10514 int nbNodes = edge._pos.size();
10516 int nbNodes = eos._hyp.GetNumberLayers() + 1;
10518 edge._nodes.resize( nbNodes, 0 );
10519 edge._nodes[1] = 0;
10520 edge._nodes.back() = tgtNode;
10522 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
10523 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
10524 if ( baseShapeId != prevBaseId )
10526 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
10527 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
10528 prevBaseId = baseShapeId;
10530 _LayerEdge* edgeOnSameNode = 0;
10531 bool useExistingPos = false;
10532 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
10534 edgeOnSameNode = n2e->second;
10535 useExistingPos = ( edgeOnSameNode->_len < edge._len ||
10536 segLen[0] == segLen.back() ); // too short inflation step (bos #20643)
10537 const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
10538 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
10541 SMDS_EdgePositionPtr epos = lastPos;
10542 epos->SetUParameter( otherTgtPos.X() );
10546 SMDS_FacePositionPtr fpos = lastPos;
10547 fpos->SetUParameter( otherTgtPos.X() );
10548 fpos->SetVParameter( otherTgtPos.Y() );
10552 // create intermediate nodes
10553 const double h0 = eos._hyp.Get1stLayerThickness( segLen.back() );
10554 const double zeroLen = std::numeric_limits<double>::min();
10555 double hSum = 0, hi = h0/eos._hyp.GetStretchFactor();
10557 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
10559 // compute an intermediate position
10560 hi *= eos._hyp.GetStretchFactor();
10562 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
10564 int iPrevSeg = iSeg-1;
10565 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
10567 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
10568 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
10569 #ifdef __NODES_AT_POS
10570 pos = edge._pos[ iStep ];
10572 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
10573 if ( !eos._sWOL.IsNull() )
10575 // compute XYZ by parameters <pos>
10580 pos = curve->Value( u ).Transformed(loc);
10582 else if ( eos._isRegularSWOL )
10584 uv.SetCoord( pos.X(), pos.Y() );
10586 pos = surface->Value( pos.X(), pos.Y() );
10590 uv.SetCoord( pos.X(), pos.Y() );
10591 gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
10592 uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
10594 pos = surface->Value( uv );
10597 // create or update the node
10600 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
10601 if ( !eos._sWOL.IsNull() )
10604 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
10606 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
10610 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
10615 if ( !eos._sWOL.IsNull() )
10617 // make average pos from new and current parameters
10620 //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
10621 if ( useExistingPos )
10622 u = helper.GetNodeU( geomEdge, node );
10623 pos = curve->Value( u ).Transformed(loc);
10625 SMDS_EdgePositionPtr epos = node->GetPosition();
10626 epos->SetUParameter( u );
10630 //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
10631 if ( useExistingPos )
10632 uv = helper.GetNodeUV( geomFace, node );
10633 pos = surface->Value( uv );
10635 SMDS_FacePositionPtr fpos = node->GetPosition();
10636 fpos->SetUParameter( uv.X() );
10637 fpos->SetVParameter( uv.Y() );
10640 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
10642 } // loop on edge._nodes
10644 if ( !eos._sWOL.IsNull() ) // prepare for shrink()
10647 edge._pos.back().SetCoord( u, 0,0);
10649 edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
10651 if ( edgeOnSameNode )
10652 edgeOnSameNode->_pos.back() = edge._pos.back();
10655 } // loop on eos._edges to create nodes
10658 if ( !getMeshDS()->IsEmbeddedMode() )
10659 // Log node movement
10660 for ( size_t i = 0; i < eos._edges.size(); ++i )
10662 SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
10663 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
10670 helper.SetElementsOnShape(true);
10672 vector< vector<const SMDS_MeshNode*>* > nnVec;
10673 set< vector<const SMDS_MeshNode*>* > nnSet;
10674 set< int > degenEdgeInd;
10675 vector<const SMDS_MeshElement*> degenVols;
10677 TopExp_Explorer exp( data._solid, TopAbs_FACE );
10678 for ( ; exp.More(); exp.Next() )
10680 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
10681 if ( data._ignoreFaceIds.count( faceID ))
10683 _EdgesOnShape* eos = data.GetShapeEdges( faceID );
10684 SMDS_MeshGroup* group = StdMeshers_ViscousLayers::CreateGroup( eos->_hyp.GetGroupName(),
10687 std::vector< const SMDS_MeshElement* > vols;
10688 const bool isReversedFace = data._reversedFaceIds.count( faceID );
10689 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
10690 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
10691 while ( fIt->more() )
10693 const SMDS_MeshElement* face = fIt->next();
10694 const int nbNodes = face->NbCornerNodes();
10695 nnVec.resize( nbNodes );
10697 degenEdgeInd.clear();
10698 size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
10699 SMDS_NodeIteratorPtr nIt = face->nodeIterator();
10700 for ( int iN = 0; iN < nbNodes; ++iN )
10702 const SMDS_MeshNode* n = nIt->next();
10703 _LayerEdge* edge = data._n2eMap[ n ];
10704 const int i = isReversedFace ? nbNodes-1-iN : iN;
10705 nnVec[ i ] = & edge->_nodes;
10706 maxZ = std::max( maxZ, nnVec[ i ]->size() );
10707 minZ = std::min( minZ, nnVec[ i ]->size() );
10709 if ( helper.HasDegeneratedEdges() )
10710 nnSet.insert( nnVec[ i ]);
10715 if ( 0 < nnSet.size() && nnSet.size() < 3 )
10719 const SMDS_MeshElement* vol;
10726 for ( size_t iZ = 1; iZ < minZ; ++iZ )
10728 vol = helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
10729 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
10730 vols.push_back( vol );
10733 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10735 for ( int iN = 0; iN < nbNodes; ++iN )
10736 if ( nnVec[ iN ]->size() < iZ+1 )
10737 degenEdgeInd.insert( iN );
10739 if ( degenEdgeInd.size() == 1 ) // PYRAM
10741 int i2 = *degenEdgeInd.begin();
10742 int i0 = helper.WrapIndex( i2 - 1, nbNodes );
10743 int i1 = helper.WrapIndex( i2 + 1, nbNodes );
10744 vol = helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
10745 (*nnVec[i1])[iZ ], (*nnVec[i0])[iZ ], (*nnVec[i2]).back());
10746 vols.push_back( vol );
10750 int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
10751 vol = helper.AddVolume( (*nnVec[ 0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
10752 (*nnVec[ 1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
10753 (*nnVec[ 2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
10754 (*nnVec[ i3 ])[ iZ ]);
10755 vols.push_back( vol );
10763 for ( size_t iZ = 1; iZ < minZ; ++iZ )
10765 vol = helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
10766 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
10767 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
10768 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
10769 vols.push_back( vol );
10772 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10774 for ( int iN = 0; iN < nbNodes; ++iN )
10775 if ( nnVec[ iN ]->size() < iZ+1 )
10776 degenEdgeInd.insert( iN );
10778 switch ( degenEdgeInd.size() )
10782 int i2 = *degenEdgeInd.begin();
10783 int i3 = *degenEdgeInd.rbegin();
10784 bool ok = ( i3 - i2 == 1 );
10785 if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
10786 int i0 = helper.WrapIndex( i3 + 1, nbNodes );
10787 int i1 = helper.WrapIndex( i0 + 1, nbNodes );
10789 vol = helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
10790 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
10791 vols.push_back( vol );
10793 degenVols.push_back( vol );
10797 default: // degen HEX
10799 vol = helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
10800 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
10801 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
10802 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
10803 nnVec[0]->size() > iZ ? (*nnVec[0])[iZ] : nnVec[0]->back(),
10804 nnVec[1]->size() > iZ ? (*nnVec[1])[iZ] : nnVec[1]->back(),
10805 nnVec[2]->size() > iZ ? (*nnVec[2])[iZ] : nnVec[2]->back(),
10806 nnVec[3]->size() > iZ ? (*nnVec[3])[iZ] : nnVec[3]->back());
10807 vols.push_back( vol );
10808 degenVols.push_back( vol );
10815 return error("Not supported type of element", data._index);
10817 } // switch ( nbNodes )
10820 for ( size_t i = 0; i < vols.size(); ++i )
10821 group->Add( vols[ i ]);
10823 } // while ( fIt->more() )
10826 if ( !degenVols.empty() )
10828 SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
10829 if ( !err || err->IsOK() )
10831 SMESH_BadInputElements* badElems =
10832 new SMESH_BadInputElements( getMeshDS(), COMPERR_WARNING, "Bad quality volumes created" );
10833 badElems->myBadElements.insert( badElems->myBadElements.end(),
10834 degenVols.begin(),degenVols.end() );
10835 err.reset( badElems );
10842 namespace VISCOUS_3D
10845 //--------------------------------------------------------------------------------
10847 * \brief Pair of periodic FACEs
10849 struct PeriodicFaces
10851 typedef StdMeshers_ProjectionUtils::TrsfFinder3D Trsf;
10853 ShrinkFace* _shriFace[2];
10854 TNodeNodeMap _nnMap;
10857 PeriodicFaces( ShrinkFace* sf1, ShrinkFace* sf2 ): _shriFace{ sf1, sf2 } {}
10858 bool IncludeShrunk( const TopoDS_Face& face, const TopTools_MapOfShape& shrunkFaces ) const;
10859 bool MoveNodes( const TopoDS_Face& tgtFace );
10860 void Clear() { _nnMap.clear(); }
10861 bool IsEmpty() const { return _nnMap.empty(); }
10864 //--------------------------------------------------------------------------------
10866 * \brief Shrink FACE data used to find periodic FACEs
10870 // ................................................................................
10871 struct BndPart //!< part of FACE boundary, either shrink or no-shrink
10873 bool _isShrink, _isReverse;
10876 std::vector< SMESH_NodeXYZ > _nodes;
10877 TopAbs_ShapeEnum _vertSWOLType[2]; // shrink part includes VERTEXes
10878 AverageHyp* _vertHyp[2];
10879 double _edgeWOLLen[2]; // length of wol EDGE
10880 double _tol; // to compare _edgeWOLLen's
10883 _isShrink(0), _isReverse(0), _nbSegments(0), _hyp(0),
10884 _vertSWOLType{ TopAbs_WIRE, TopAbs_WIRE }, _vertHyp{ 0, 0 }, _edgeWOLLen{ 0., 0.}
10887 bool IsEqualLengthEWOL( const BndPart& other ) const
10889 return ( std::abs( _edgeWOLLen[0] - other._edgeWOLLen[0] ) < _tol &&
10890 std::abs( _edgeWOLLen[1] - other._edgeWOLLen[1] ) < _tol );
10893 bool operator==( const BndPart& other ) const
10895 return ( _isShrink == other._isShrink &&
10896 _nbSegments == other._nbSegments &&
10897 _nodes.size() == other._nodes.size() &&
10898 vertSWOLType1() == other.vertSWOLType1() &&
10899 vertSWOLType2() == other.vertSWOLType2() &&
10901 ( *_hyp == *other._hyp &&
10902 vertHyp1() == other.vertHyp1() &&
10903 vertHyp2() == other.vertHyp2() &&
10904 IsEqualLengthEWOL( other )))
10907 bool CanAppend( const BndPart& other )
10909 return ( _isShrink == other._isShrink &&
10911 ( *_hyp == *other._hyp &&
10912 *_hyp == vertHyp2() &&
10913 vertHyp2() == other.vertHyp1() ))
10916 void Append( const BndPart& other )
10918 _nbSegments += other._nbSegments;
10919 bool hasCommonNode = ( _nodes.back()->GetID() == other._nodes.front()->GetID() );
10920 _nodes.insert( _nodes.end(), other._nodes.begin() + hasCommonNode, other._nodes.end() );
10921 _vertSWOLType[1] = other._vertSWOLType[1];
10923 _vertHyp[1] = other._vertHyp[1];
10924 _edgeWOLLen[1] = other._edgeWOLLen[1];
10927 const SMDS_MeshNode* Node(size_t i) const
10929 return _nodes[ _isReverse ? ( _nodes.size() - 1 - i ) : i ]._node;
10931 void Reverse() { _isReverse = !_isReverse; }
10932 const TopAbs_ShapeEnum& vertSWOLType1() const { return _vertSWOLType[ _isReverse ]; }
10933 const TopAbs_ShapeEnum& vertSWOLType2() const { return _vertSWOLType[ !_isReverse ]; }
10934 const AverageHyp& vertHyp1() const { return *(_vertHyp[ _isReverse ]); }
10935 const AverageHyp& vertHyp2() const { return *(_vertHyp[ !_isReverse ]); }
10937 // ................................................................................
10939 SMESH_subMesh* _subMesh;
10940 _SolidData* _data1;
10941 _SolidData* _data2;
10943 std::list< BndPart > _boundary;
10944 int _boundarySize, _nbBoundaryParts;
10946 void Init( SMESH_subMesh* sm, _SolidData* sd1, _SolidData* sd2 )
10948 _subMesh = sm; _data1 = sd1; _data2 = sd2;
10950 bool IsSame( const TopoDS_Face& face ) const
10952 return _subMesh->GetSubShape().IsSame( face );
10954 bool IsShrunk( const TopTools_MapOfShape& shrunkFaces ) const
10956 return shrunkFaces.Contains( _subMesh->GetSubShape() );
10959 //================================================================================
10961 * Check if meshes on two FACEs are equal
10963 bool IsPeriodic( ShrinkFace& other, PeriodicFaces& periodic )
10965 if ( !IsSameNbElements( other ))
10968 this->SetBoundary();
10969 other.SetBoundary();
10970 if ( this->_boundarySize != other._boundarySize ||
10971 this->_nbBoundaryParts != other._nbBoundaryParts )
10974 for ( int isReverse = 0; isReverse < 2; ++isReverse )
10977 Reverse( _boundary );
10979 // check boundaries
10980 bool equalBoundary = false;
10981 for ( int iP = 0; iP < _nbBoundaryParts && !equalBoundary; ++iP )
10983 if ( ! ( equalBoundary = ( this->_boundary == other._boundary )))
10984 // set first part at end
10985 _boundary.splice( _boundary.end(), _boundary, _boundary.begin() );
10987 if ( !equalBoundary )
10990 // check connectivity
10991 std::set<const SMDS_MeshElement*> elemsThis, elemsOther;
10992 this->GetElements( elemsThis );
10993 other.GetElements( elemsOther );
10994 SMESH_MeshEditor::Sew_Error err =
10995 SMESH_MeshEditor::FindMatchingNodes( elemsThis, elemsOther,
10996 this->_boundary.front().Node(0),
10997 other._boundary.front().Node(0),
10998 this->_boundary.front().Node(1),
10999 other._boundary.front().Node(1),
11001 if ( err != SMESH_MeshEditor::SEW_OK )
11004 // check node positions
11005 std::vector< gp_XYZ > srcPnts, tgtPnts;
11006 this->GetBoundaryPoints( srcPnts );
11007 other.GetBoundaryPoints( tgtPnts );
11008 if ( !periodic._trsf.Solve( srcPnts, tgtPnts )) {
11011 double tol = std::numeric_limits<double>::max(); // tolerance by segment size
11012 for ( size_t i = 1; i < srcPnts.size(); ++i ) {
11013 tol = Min( tol, ( srcPnts[i-1] - srcPnts[i] ).SquareModulus() );
11015 tol = 0.01 * Sqrt( tol );
11016 for ( BndPart& boundary : _boundary ) { // tolerance by VL thickness
11017 if ( boundary._isShrink )
11018 tol = Min( tol, boundary._hyp->Get1stLayerThickness() / 50. );
11020 bool nodeCoincide = true;
11021 TNodeNodeMap::iterator n2n = periodic._nnMap.begin();
11022 for ( ; n2n != periodic._nnMap.end() && nodeCoincide; ++n2n )
11024 SMESH_NodeXYZ nSrc = n2n->first;
11025 SMESH_NodeXYZ nTgt = n2n->second;
11026 gp_XYZ pTgt = periodic._trsf.Transform( nSrc );
11027 nodeCoincide = (( pTgt - nTgt ).SquareModulus() < tol * tol );
11029 if ( nodeCoincide )
11035 bool IsSameNbElements( ShrinkFace& other ) // check number of mesh faces
11037 SMESHDS_SubMesh* sm1 = this->_subMesh->GetSubMeshDS();
11038 SMESHDS_SubMesh* sm2 = other._subMesh->GetSubMeshDS();
11039 return ( sm1->NbElements() == sm2->NbElements() &&
11040 sm1->NbNodes() == sm2->NbNodes() );
11043 void Reverse( std::list< BndPart >& boundary )
11045 boundary.reverse();
11046 for ( std::list< BndPart >::iterator part = boundary.begin(); part != boundary.end(); ++part )
11052 if ( !_boundary.empty() )
11055 TopoDS_Face F = TopoDS::Face( _subMesh->GetSubShape() );
11056 if ( F.Orientation() >= TopAbs_INTERNAL ) F.Orientation( TopAbs_FORWARD );
11057 std::list< TopoDS_Edge > edges;
11058 std::list< int > nbEdgesInWire;
11059 /*int nbWires =*/ SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
11061 // std::list< TopoDS_Edge >::iterator edgesEnd = edges.end();
11062 // if ( nbWires > 1 ) {
11063 // edgesEnd = edges.begin();
11064 // std::advance( edgesEnd, nbEdgesInWire.front() );
11066 StdMeshers_FaceSide fSide( F, edges, _subMesh->GetFather(),
11067 /*fwd=*/true, /*skipMedium=*/true );
11068 _boundarySize = fSide.NbSegments();
11070 //TopoDS_Vertex vv[2];
11071 //std::list< TopoDS_Edge >::iterator edgeIt = edges.begin();
11072 for ( int iE = 0; iE < nbEdgesInWire.front(); ++iE )
11076 std::vector<const SMDS_MeshNode*> nodes = fSide.GetOrderedNodes( iE );
11077 bndPart._nodes.assign( nodes.begin(), nodes.end() );
11078 bndPart._nbSegments = bndPart._nodes.size() - 1;
11080 _EdgesOnShape* eos = _data1->GetShapeEdges( fSide.EdgeID( iE ));
11082 bndPart._isShrink = ( eos->SWOLType() == TopAbs_FACE );
11083 if ( bndPart._isShrink )
11084 if (( _data1->_noShrinkShapes.count( eos->_shapeID )) ||
11085 ( _data2 && _data2->_noShrinkShapes.count( eos->_shapeID )))
11086 bndPart._isShrink = false;
11088 if ( bndPart._isShrink )
11090 bndPart._hyp = & eos->_hyp;
11091 _EdgesOnShape* eov[2] = { _data1->GetShapeEdges( fSide.FirstVertex( iE )),
11092 _data1->GetShapeEdges( fSide.LastVertex ( iE )) };
11093 for ( int iV = 0; iV < 2; ++iV )
11095 bndPart._vertHyp [iV] = & eov[iV]->_hyp;
11096 bndPart._vertSWOLType[iV] = eov[iV]->SWOLType();
11097 if ( _data1->_noShrinkShapes.count( eov[iV]->_shapeID ))
11098 bndPart._vertSWOLType[iV] = TopAbs_SHAPE;
11099 if ( _data2 && bndPart._vertSWOLType[iV] != TopAbs_SHAPE )
11101 eov[iV] = _data2->GetShapeEdges( iV ? fSide.LastVertex(iE) : fSide.FirstVertex(iE ));
11102 if ( _data2->_noShrinkShapes.count( eov[iV]->_shapeID ))
11103 bndPart._vertSWOLType[iV] = TopAbs_SHAPE;
11104 else if ( eov[iV]->SWOLType() > bndPart._vertSWOLType[iV] )
11105 bndPart._vertSWOLType[iV] = eov[iV]->SWOLType();
11108 bndPart._edgeWOLLen[0] = fSide.EdgeLength( iE - 1 );
11109 bndPart._edgeWOLLen[1] = fSide.EdgeLength( iE + 1 );
11111 bndPart._tol = std::numeric_limits<double>::max(); // tolerance by segment size
11112 for ( size_t i = 1; i < bndPart._nodes.size(); ++i )
11113 bndPart._tol = Min( bndPart._tol,
11114 ( bndPart._nodes[i-1] - bndPart._nodes[i] ).SquareModulus() );
11117 if ( _boundary.empty() || ! _boundary.back().CanAppend( bndPart ))
11118 _boundary.push_back( bndPart );
11120 _boundary.back().Append( bndPart );
11123 _nbBoundaryParts = _boundary.size();
11124 if ( _nbBoundaryParts > 1 && _boundary.front()._isShrink == _boundary.back()._isShrink )
11126 _boundary.back().Append( _boundary.front() );
11127 _boundary.pop_front();
11128 --_nbBoundaryParts;
11132 void GetElements( std::set<const SMDS_MeshElement*>& theElems)
11134 if ( SMESHDS_SubMesh* sm = _subMesh->GetSubMeshDS() )
11135 for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
11136 theElems.insert( theElems.end(), fIt->next() );
11141 void GetBoundaryPoints( std::vector< gp_XYZ >& points )
11143 points.reserve( _boundarySize );
11144 size_t nb = _boundary.rbegin()->_nodes.size();
11145 smIdType lastID = _boundary.rbegin()->Node( nb - 1 )->GetID();
11146 std::list< BndPart >::const_iterator part = _boundary.begin();
11147 for ( ; part != _boundary.end(); ++part )
11149 size_t nb = part->_nodes.size();
11151 size_t iR = nb - 1;
11152 size_t* i = part->_isReverse ? &iR : &iF;
11153 if ( part->_nodes[ *i ]->GetID() == lastID )
11155 for ( ; iF < nb; ++iF, --iR )
11156 points.push_back( part->_nodes[ *i ]);
11158 lastID = part->_nodes[ *i ]->GetID();
11161 }; // struct ShrinkFace
11163 //--------------------------------------------------------------------------------
11165 * \brief Periodic FACEs
11169 std::vector< ShrinkFace > _shrinkFaces;
11170 std::vector< PeriodicFaces > _periodicFaces;
11172 PeriodicFaces* GetPeriodic( const TopoDS_Face& face, const TopTools_MapOfShape& shrunkFaces )
11174 for ( size_t i = 0; i < _periodicFaces.size(); ++i )
11175 if ( _periodicFaces[ i ].IncludeShrunk( face, shrunkFaces ))
11176 return & _periodicFaces[ i ];
11179 void ClearPeriodic( const TopoDS_Face& face )
11181 for ( size_t i = 0; i < _periodicFaces.size(); ++i )
11182 if ( _periodicFaces[ i ]._shriFace[0]->IsSame( face ) ||
11183 _periodicFaces[ i ]._shriFace[1]->IsSame( face ))
11184 _periodicFaces[ i ].Clear();
11188 //================================================================================
11190 * Check if a pair includes the given FACE and the other FACE is already shrunk
11192 bool PeriodicFaces::IncludeShrunk( const TopoDS_Face& face,
11193 const TopTools_MapOfShape& shrunkFaces ) const
11195 if ( IsEmpty() ) return false;
11196 return (( _shriFace[0]->IsSame( face ) && _shriFace[1]->IsShrunk( shrunkFaces )) ||
11197 ( _shriFace[1]->IsSame( face ) && _shriFace[0]->IsShrunk( shrunkFaces )));
11200 //================================================================================
11202 * Make equal meshes on periodic faces by moving corresponding nodes
11204 bool PeriodicFaces::MoveNodes( const TopoDS_Face& tgtFace )
11206 int iTgt = _shriFace[1]->IsSame( tgtFace );
11207 int iSrc = 1 - iTgt;
11209 _SolidData* dataSrc = _shriFace[iSrc]->_data1;
11210 _SolidData* dataTgt = _shriFace[iTgt]->_data1;
11212 Trsf * trsf = & _trsf, trsfInverse;
11215 trsfInverse = _trsf;
11216 if ( !trsfInverse.Invert())
11218 trsf = &trsfInverse;
11220 SMESHDS_Mesh* meshDS = dataSrc->GetHelper().GetMeshDS();
11222 dumpFunction(SMESH_Comment("periodicMoveNodes_F")
11223 << _shriFace[iSrc]->_subMesh->GetId() << "_F"
11224 << _shriFace[iTgt]->_subMesh->GetId() );
11225 TNode2Edge::iterator n2e;
11226 TNodeNodeMap::iterator n2n = _nnMap.begin();
11227 for ( ; n2n != _nnMap.end(); ++n2n )
11229 const SMDS_MeshNode* const* nn = & n2n->first;
11230 const SMDS_MeshNode* nSrc = nn[ iSrc ];
11231 const SMDS_MeshNode* nTgt = nn[ iTgt ];
11233 if (( nSrc->GetPosition()->GetDim() == 2 ) ||
11234 (( n2e = dataSrc->_n2eMap.find( nSrc )) == dataSrc->_n2eMap.end() ))
11236 SMESH_NodeXYZ pSrc = nSrc;
11237 gp_XYZ pTgt = trsf->Transform( pSrc );
11238 meshDS->MoveNode( nTgt, pTgt.X(), pTgt.Y(), pTgt.Z() );
11242 _LayerEdge* leSrc = n2e->second;
11243 n2e = dataTgt->_n2eMap.find( nTgt );
11244 if ( n2e == dataTgt->_n2eMap.end() )
11246 _LayerEdge* leTgt = n2e->second;
11247 if ( leSrc->_nodes.size() != leTgt->_nodes.size() )
11249 for ( size_t iN = 1; iN < leSrc->_nodes.size(); ++iN )
11251 SMESH_NodeXYZ pSrc = leSrc->_nodes[ iN ];
11252 gp_XYZ pTgt = trsf->Transform( pSrc );
11253 meshDS->MoveNode( leTgt->_nodes[ iN ], pTgt.X(), pTgt.Y(), pTgt.Z() );
11255 dumpMove( leTgt->_nodes[ iN ]);
11259 bool done = ( n2n == _nnMap.end() );
11260 debugMsg( "PeriodicFaces::MoveNodes "
11261 << _shriFace[iSrc]->_subMesh->GetId() << " -> "
11262 << _shriFace[iTgt]->_subMesh->GetId() << " -- "
11263 << ( done ? "DONE" : "FAIL"));
11268 } // namespace VISCOUS_3D; Periodicity part
11271 //================================================================================
11273 * \brief Find FACEs to shrink, that are equally meshed before shrink (i.e. periodic)
11274 * and should remain equal after shrink
11276 //================================================================================
11278 void _ViscousBuilder::findPeriodicFaces()
11280 // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
11281 // _LayerEdge's inflated along FACE or EDGE)
11282 std::map< TGeomID, std::list< _SolidData* > > id2sdMap;
11283 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11285 _SolidData& data = _sdVec[i];
11286 std::map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
11287 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
11288 if ( s2s->second.ShapeType() == TopAbs_FACE )
11289 id2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
11292 _periodicity.reset( new Periodicity );
11293 _periodicity->_shrinkFaces.resize( id2sdMap.size() );
11295 std::map< TGeomID, std::list< _SolidData* > >::iterator id2sdIt = id2sdMap.begin();
11296 for ( size_t i = 0; i < id2sdMap.size(); ++i, ++id2sdIt )
11298 _SolidData* sd1 = id2sdIt->second.front();
11299 _SolidData* sd2 = id2sdIt->second.back();
11300 _periodicity->_shrinkFaces[ i ].Init( _mesh->GetSubMeshContaining( id2sdIt->first ), sd1, sd2 );
11303 for ( size_t i1 = 0; i1 < _periodicity->_shrinkFaces.size(); ++i1 )
11304 for ( size_t i2 = i1 + 1; i2 < _periodicity->_shrinkFaces.size(); ++i2 )
11306 PeriodicFaces pf( & _periodicity->_shrinkFaces[ i1 ],
11307 & _periodicity->_shrinkFaces[ i2 ]);
11308 if ( pf._shriFace[0]->IsPeriodic( *pf._shriFace[1], pf ))
11310 _periodicity->_periodicFaces.push_back( pf );
11316 //================================================================================
11318 * \brief Shrink 2D mesh on faces to let space for inflated layers
11320 //================================================================================
11322 bool _ViscousBuilder::shrink(_SolidData& theData)
11324 // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
11325 // _LayerEdge's inflated along FACE or EDGE)
11326 map< TGeomID, list< _SolidData* > > f2sdMap;
11327 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11329 _SolidData& data = _sdVec[i];
11330 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
11331 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
11332 if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrunkFaces.Contains( s2s->second ))
11334 f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
11336 // Put mesh faces on the shrunk FACE to the proxy sub-mesh to avoid
11337 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
11338 // by StdMeshers_QuadToTriaAdaptor
11339 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
11341 SMESH_ProxyMesh::SubMesh* proxySub =
11342 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
11343 if ( proxySub->NbElements() == 0 )
11345 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11346 while ( fIt->more() )
11348 const SMDS_MeshElement* f = fIt->next();
11349 // as a result 3D algo will use elements from proxySub and not from smDS
11350 proxySub->AddElement( f );
11351 f->setIsMarked( true );
11353 // Mark nodes on the FACE to discriminate them from nodes
11354 // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
11355 for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
11357 const SMDS_MeshNode* n = f->GetNode( iN );
11358 if ( n->GetPosition()->GetDim() == 2 )
11359 n->setIsMarked( true );
11367 SMESH_MesherHelper helper( *_mesh );
11368 helper.ToFixNodeParameters( true );
11371 map< TGeomID, _Shrinker1D > e2shrMap;
11372 vector< _EdgesOnShape* > subEOS;
11373 vector< _LayerEdge* > lEdges;
11375 // loop on FACEs to shrink mesh on
11376 map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
11377 for ( ; f2sd != f2sdMap.end(); ++f2sd )
11379 list< _SolidData* > & dataList = f2sd->second;
11380 if ( dataList.front()->_n2eMap.empty() ||
11381 dataList.back() ->_n2eMap.empty() )
11382 continue; // not yet computed
11383 if ( dataList.front() != &theData &&
11384 dataList.back() != &theData )
11387 _SolidData& data = *dataList.front();
11388 _SolidData* data2 = dataList.size() > 1 ? dataList.back() : 0;
11389 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
11390 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
11391 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
11393 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
11395 _shrunkFaces.Add( F );
11396 helper.SetSubShape( F );
11398 // ==============================
11399 // Use periodicity to move nodes
11400 // ==============================
11402 PeriodicFaces* periodic = _periodicity->GetPeriodic( F, _shrunkFaces );
11403 bool movedByPeriod = ( periodic && periodic->MoveNodes( F ));
11405 // ===========================
11406 // Prepare data for shrinking
11407 // ===========================
11409 // Collect nodes to smooth (they are marked at the beginning of this method)
11410 vector < const SMDS_MeshNode* > smoothNodes;
11412 if ( !movedByPeriod )
11414 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
11415 while ( nIt->more() )
11417 const SMDS_MeshNode* n = nIt->next();
11418 if ( n->isMarked() )
11419 smoothNodes.push_back( n );
11422 // Find out face orientation
11423 double refSign = 1;
11424 const set<TGeomID> ignoreShapes;
11426 if ( !smoothNodes.empty() )
11428 vector<_Simplex> simplices;
11429 _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
11430 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
11431 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
11432 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
11433 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
11437 // Find _LayerEdge's inflated along F
11441 SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
11442 /*complexFirst=*/true); //!!!
11443 while ( subIt->more() )
11445 const TGeomID subID = subIt->next()->GetId();
11446 if ( data._noShrinkShapes.count( subID ))
11448 _EdgesOnShape* eos = data.GetShapeEdges( subID );
11449 if ( !eos || eos->_sWOL.IsNull() )
11450 if ( data2 ) // check in adjacent SOLID
11452 eos = data2->GetShapeEdges( subID );
11453 if ( !eos || eos->_sWOL.IsNull() )
11456 subEOS.push_back( eos );
11458 if ( !movedByPeriod )
11459 for ( size_t i = 0; i < eos->_edges.size(); ++i )
11461 lEdges.push_back( eos->_edges[ i ] );
11462 prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
11467 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
11468 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11469 while ( fIt->more() )
11470 if ( const SMDS_MeshElement* f = fIt->next() )
11471 dumpChangeNodes( f );
11474 // Replace source nodes by target nodes in mesh faces to shrink
11475 dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
11476 const SMDS_MeshNode* nodes[20];
11477 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11479 _EdgesOnShape& eos = * subEOS[ iS ];
11480 for ( size_t i = 0; i < eos._edges.size(); ++i )
11482 _LayerEdge& edge = *eos._edges[i];
11483 const SMDS_MeshNode* srcNode = edge._nodes[0];
11484 const SMDS_MeshNode* tgtNode = edge._nodes.back();
11485 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
11486 while ( fIt->more() )
11488 const SMDS_MeshElement* f = fIt->next();
11489 if ( !smDS->Contains( f ) || !f->isMarked() )
11491 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
11492 for ( int iN = 0; nIt->more(); ++iN )
11494 const SMDS_MeshNode* n = nIt->next();
11495 nodes[iN] = ( n == srcNode ? tgtNode : n );
11497 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
11498 dumpChangeNodes( f );
11504 // find out if a FACE is concave
11505 const bool isConcaveFace = isConcave( F, helper );
11507 // Create _SmoothNode's on face F
11508 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
11510 dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
11511 const bool sortSimplices = isConcaveFace;
11512 for ( size_t i = 0; i < smoothNodes.size(); ++i )
11514 const SMDS_MeshNode* n = smoothNodes[i];
11515 nodesToSmooth[ i ]._node = n;
11516 // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
11517 _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
11518 // fix up incorrect uv of nodes on the FACE
11519 helper.GetNodeUV( F, n, 0, &isOkUV);
11524 //if ( nodesToSmooth.empty() ) continue;
11526 // Find EDGE's to shrink and set simpices to LayerEdge's
11527 set< _Shrinker1D* > eShri1D;
11529 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11531 _EdgesOnShape& eos = * subEOS[ iS ];
11532 if ( eos.SWOLType() == TopAbs_EDGE )
11534 SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
11535 VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
11536 if ( !movedByPeriod )
11538 _Shrinker1D& shrinker = e2shrMap[ edgeSM->GetId() ];
11539 eShri1D.insert( & shrinker );
11540 shrinker.AddEdge( eos._edges[0], eos, helper );
11541 // restore params of nodes on EDGE if the EDGE has been already
11542 // shrunk while shrinking other FACE
11543 shrinker.RestoreParams();
11546 for ( size_t i = 0; i < eos._edges.size(); ++i )
11548 _LayerEdge& edge = * eos._edges[i];
11549 _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
11551 // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
11552 // not-marked nodes are those added by refine()
11553 edge._nodes.back()->setIsMarked( true );
11558 bool toFixTria = false; // to improve quality of trias by diagonal swap
11559 if ( isConcaveFace && !movedByPeriod )
11561 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
11562 if ( hasTria != hasQuad ) {
11563 toFixTria = hasTria;
11566 set<int> nbNodesSet;
11567 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11568 while ( fIt->more() && nbNodesSet.size() < 2 )
11569 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
11570 toFixTria = ( *nbNodesSet.begin() == 3 );
11574 // ==================
11575 // Perform shrinking
11576 // ==================
11578 bool shrunk = !movedByPeriod;
11579 int nbBad, shriStep=0, smooStep=0;
11580 _SmoothNode::SmoothType smoothType
11581 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
11582 SMESH_Comment errMsg;
11586 // Move boundary nodes (actually just set new UV)
11587 // -----------------------------------------------
11588 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
11590 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11592 _EdgesOnShape& eos = * subEOS[ iS ];
11593 for ( size_t i = 0; i < eos._edges.size(); ++i )
11595 shrunk |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
11600 // Move nodes on EDGE's
11601 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
11602 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
11603 for ( ; shr != eShri1D.end(); ++shr )
11604 (*shr)->Compute( /*set3D=*/false, helper );
11607 // -----------------
11608 int nbNoImpSteps = 0;
11611 while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
11613 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11615 int oldBadNb = nbBad;
11618 // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
11619 _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
11620 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11622 moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
11623 smooTy, /*set3D=*/isConcaveFace);
11625 if ( nbBad < oldBadNb )
11635 errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
11636 if ( shriStep > 200 )
11637 errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
11638 if ( !errMsg.empty() )
11641 // Fix narrow triangles by swapping diagonals
11642 // ---------------------------------------
11645 set<const SMDS_MeshNode*> usedNodes;
11646 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
11648 // update working data
11649 set<const SMDS_MeshNode*>::iterator n;
11650 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
11652 n = usedNodes.find( nodesToSmooth[ i ]._node );
11653 if ( n != usedNodes.end())
11655 _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
11656 nodesToSmooth[ i ]._simplices,
11657 ignoreShapes, NULL,
11658 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
11659 usedNodes.erase( n );
11662 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
11664 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
11665 if ( n != usedNodes.end())
11667 _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
11668 lEdges[i]->_simplices,
11670 usedNodes.erase( n );
11674 // TODO: check effect of this additional smooth
11675 // additional laplacian smooth to increase allowed shrink step
11676 // for ( int st = 1; st; --st )
11678 // dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11679 // for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11681 // nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
11682 // _SmoothNode::LAPLACIAN,/*set3D=*/false);
11686 } // while ( shrunk )
11688 if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
11690 debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
11693 SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
11695 vector< const SMDS_MeshElement* > facesToRm;
11698 facesToRm.reserve( psm->NbElements() );
11699 for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
11700 facesToRm.push_back( ite->next() );
11702 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11703 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
11706 for ( size_t i = 0; i < facesToRm.size(); ++i )
11707 getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
11711 TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
11712 for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
11713 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
11714 nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
11715 subEOS[iS]->_edges[i]->_nodes.end() );
11717 SMDS_NodeIteratorPtr itn = smDS->GetNodes();
11718 while ( itn->more() ) {
11719 const SMDS_MeshNode* n = itn->next();
11720 if ( !nodesToKeep.count( n ))
11721 getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
11724 _periodicity->ClearPeriodic( F );
11726 // restore position and UV of target nodes
11728 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11729 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
11731 _LayerEdge* edge = subEOS[iS]->_edges[i];
11732 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
11733 if ( edge->_pos.empty() ||
11734 edge->Is( _LayerEdge::SHRUNK )) continue;
11735 if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
11737 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11738 pos->SetUParameter( edge->_pos[0].X() );
11739 pos->SetVParameter( edge->_pos[0].Y() );
11740 p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
11744 SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
11745 pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
11746 p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
11748 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11749 dumpMove( tgtNode );
11751 // shrink EDGE sub-meshes and set proxy sub-meshes
11752 UVPtStructVec uvPtVec;
11753 set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
11754 for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
11756 _Shrinker1D* shr = (*shrIt);
11757 shr->Compute( /*set3D=*/true, helper );
11759 // set proxy mesh of EDGEs w/o layers
11760 map< double, const SMDS_MeshNode* > nodes;
11761 SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
11762 // remove refinement nodes
11763 const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
11764 const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
11765 map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
11766 if ( u2n->second == sn0 || u2n->second == sn1 )
11768 while ( u2n->second != tn0 && u2n->second != tn1 )
11770 nodes.erase( nodes.begin(), u2n );
11772 u2n = --nodes.end();
11773 if ( u2n->second == sn0 || u2n->second == sn1 )
11775 while ( u2n->second != tn0 && u2n->second != tn1 )
11777 nodes.erase( ++u2n, nodes.end() );
11779 // set proxy sub-mesh
11780 uvPtVec.resize( nodes.size() );
11781 u2n = nodes.begin();
11782 BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
11783 for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
11785 uvPtVec[ i ].node = u2n->second;
11786 uvPtVec[ i ].param = u2n->first;
11787 uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
11789 StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
11790 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
11793 // set proxy mesh of EDGEs with layers
11794 vector< _LayerEdge* > edges;
11795 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11797 _EdgesOnShape& eos = * subEOS[ iS ];
11798 if ( eos.ShapeType() != TopAbs_EDGE ) continue;
11799 if ( eos.size() == 0 )
11802 const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
11803 data.SortOnEdge( E, eos._edges );
11806 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
11807 if ( !eov->_edges.empty() )
11808 edges.push_back( eov->_edges[0] ); // on 1st VERTEX
11810 edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
11812 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
11813 if ( !eov->_edges.empty() )
11814 edges.push_back( eov->_edges[0] ); // on last VERTEX
11816 uvPtVec.resize( edges.size() );
11817 for ( size_t i = 0; i < edges.size(); ++i )
11819 uvPtVec[ i ].node = edges[i]->_nodes.back();
11820 uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
11821 uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
11823 if ( uvPtVec[ 0 ].node == uvPtVec.back().node && // closed
11824 helper.IsSeamShape( uvPtVec[ 0 ].node->GetShapeID() ))
11826 uvPtVec[ 0 ].SetUV( helper.GetNodeUV( F,
11827 edges[0]->_nodes.back(),
11828 edges[1]->_nodes.back() ));
11829 size_t i = edges.size() - 1;
11830 uvPtVec[ i ].SetUV( helper.GetNodeUV( F,
11831 edges[i ]->_nodes.back(),
11832 edges[i-1]->_nodes.back() ));
11834 // if ( edges.empty() )
11836 BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
11837 StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
11838 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
11840 // temporary clear the FACE sub-mesh from faces made by refine()
11841 vector< const SMDS_MeshElement* > elems;
11842 elems.reserve( smDS->NbElements() + smDS->NbNodes() );
11843 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
11844 elems.push_back( ite->next() );
11845 for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
11846 elems.push_back( ite->next() );
11849 // compute the mesh on the FACE
11850 TopTools_IndexedMapOfShape allowed(1);
11851 allowed.Add( sm->GetSubShape() );
11852 sm->SetAllowedSubShapes( &allowed );
11853 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
11854 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
11855 sm->SetAllowedSubShapes( nullptr );
11857 // re-fill proxy sub-meshes of the FACE
11858 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11859 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
11860 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
11861 psm->AddElement( ite->next() );
11864 for ( size_t i = 0; i < elems.size(); ++i )
11865 smDS->AddElement( elems[i] );
11867 if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
11868 return error( errMsg );
11870 } // end of re-meshing in case of failed smoothing
11871 else if ( !movedByPeriod )
11873 // No wrongly shaped faces remain; final smooth. Set node XYZ.
11874 bool isStructuredFixed = false;
11875 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
11876 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
11877 if ( !isStructuredFixed )
11879 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
11880 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
11882 for ( int st = 3; st; --st )
11885 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
11886 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
11887 case 3: smoothType = _SmoothNode::ANGULAR; break;
11889 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11890 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11892 nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
11893 smoothType,/*set3D=*/st==1 );
11898 if ( !getMeshDS()->IsEmbeddedMode() )
11899 // Log node movement
11900 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11902 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
11903 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
11907 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
11908 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
11910 VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
11912 } // loop on FACES to shrink mesh on
11915 // Replace source nodes by target nodes in shrunk mesh edges
11917 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
11918 for ( ; e2shr != e2shrMap.end(); ++e2shr )
11919 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
11924 //================================================================================
11926 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
11928 //================================================================================
11930 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
11931 _EdgesOnShape& eos,
11932 SMESH_MesherHelper& helper,
11933 const SMESHDS_SubMesh* /*faceSubMesh*/)
11935 const SMDS_MeshNode* srcNode = edge._nodes[0];
11936 const SMDS_MeshNode* tgtNode = edge._nodes.back();
11938 if ( eos.SWOLType() == TopAbs_FACE )
11940 if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
11943 edge.Set( _LayerEdge::SHRUNK );
11944 return srcNode == tgtNode;
11946 gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() ); //helper.GetNodeUV( F, srcNode );
11947 gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
11948 gp_Vec2d uvDir( srcUV, tgtUV );
11949 double uvLen = uvDir.Magnitude();
11951 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
11954 //edge._pos.resize(1);
11955 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
11957 // set UV of source node to target node
11958 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11959 pos->SetUParameter( srcUV.X() );
11960 pos->SetVParameter( srcUV.Y() );
11962 else // _sWOL is TopAbs_EDGE
11964 if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
11967 edge.Set( _LayerEdge::SHRUNK );
11968 return srcNode == tgtNode;
11970 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
11971 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
11972 if ( !edgeSM || edgeSM->NbElements() == 0 )
11973 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
11975 const SMDS_MeshNode* n2 = 0;
11976 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11977 while ( eIt->more() && !n2 )
11979 const SMDS_MeshElement* e = eIt->next();
11980 if ( !edgeSM->Contains(e)) continue;
11981 n2 = e->GetNode( 0 );
11982 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
11985 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
11987 if ( n2 == tgtNode || // for 3D_mesh_GHS3D_01/B1
11988 n2 == edge._nodes[1] ) // bos #20643
11990 // shrunk by other SOLID
11991 edge.Set( _LayerEdge::SHRUNK ); // ???
11995 double uSrc = helper.GetNodeU( E, srcNode, n2 );
11996 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
11997 double u2 = helper.GetNodeU( E, n2, srcNode );
11999 //edge._pos.clear();
12001 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
12003 // tgtNode is located so that it does not make faces with wrong orientation
12004 edge.Set( _LayerEdge::SHRUNK );
12007 //edge._pos.resize(1);
12008 edge._pos[0].SetCoord( U_TGT, uTgt );
12009 edge._pos[0].SetCoord( U_SRC, uSrc );
12010 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
12012 edge._simplices.resize( 1 );
12013 edge._simplices[0]._nPrev = n2;
12015 // set U of source node to the target node
12016 SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
12017 pos->SetUParameter( uSrc );
12022 //================================================================================
12024 * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
12026 //================================================================================
12028 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
12030 if ( edge._nodes.size() == 1 )
12035 const SMDS_MeshNode* srcNode = edge._nodes[0];
12036 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
12037 if ( S.IsNull() ) return;
12041 switch ( S.ShapeType() )
12046 TopLoc_Location loc;
12047 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
12048 if ( curve.IsNull() ) return;
12049 SMDS_EdgePositionPtr ePos = srcNode->GetPosition();
12050 p = curve->Value( ePos->GetUParameter() );
12053 case TopAbs_VERTEX:
12055 p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
12060 getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
12061 dumpMove( srcNode );
12065 //================================================================================
12067 * \brief Try to fix triangles with high aspect ratio by swapping diagonals
12069 //================================================================================
12071 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
12072 SMESH_MesherHelper& helper,
12075 set<const SMDS_MeshNode*> * involvedNodes)
12077 SMESH::Controls::AspectRatio qualifier;
12078 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
12079 const double maxAspectRatio = is2D ? 4. : 2;
12080 _NodeCoordHelper xyz( F, helper, is2D );
12082 // find bad triangles
12084 vector< const SMDS_MeshElement* > badTrias;
12085 vector< double > badAspects;
12086 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
12087 SMDS_ElemIteratorPtr fIt = sm->GetElements();
12088 while ( fIt->more() )
12090 const SMDS_MeshElement * f = fIt->next();
12091 if ( f->NbCornerNodes() != 3 ) continue;
12092 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
12093 double aspect = qualifier.GetValue( points );
12094 if ( aspect > maxAspectRatio )
12096 badTrias.push_back( f );
12097 badAspects.push_back( aspect );
12102 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
12103 SMDS_ElemIteratorPtr fIt = sm->GetElements();
12104 while ( fIt->more() )
12106 const SMDS_MeshElement * f = fIt->next();
12107 if ( f->NbCornerNodes() == 3 )
12108 dumpChangeNodes( f );
12112 if ( badTrias.empty() )
12115 // find couples of faces to swap diagonal
12117 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
12118 vector< T2Trias > triaCouples;
12120 TIDSortedElemSet involvedFaces, emptySet;
12121 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
12124 double aspRatio [3];
12127 if ( !involvedFaces.insert( badTrias[iTia] ).second )
12129 for ( int iP = 0; iP < 3; ++iP )
12130 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
12132 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
12133 int bestCouple = -1;
12134 for ( int iSide = 0; iSide < 3; ++iSide )
12136 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
12137 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
12138 trias [iSide].first = badTrias[iTia];
12139 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
12141 if (( ! trias[iSide].second ) ||
12142 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
12143 ( ! sm->Contains( trias[iSide].second )))
12146 // aspect ratio of an adjacent tria
12147 for ( int iP = 0; iP < 3; ++iP )
12148 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
12149 double aspectInit = qualifier.GetValue( points2 );
12151 // arrange nodes as after diag-swaping
12152 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
12153 i3 = helper.WrapIndex( i1-1, 3 );
12155 i3 = helper.WrapIndex( i1+1, 3 );
12157 points1( 1+ iSide ) = points2( 1+ i3 );
12158 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
12160 // aspect ratio after diag-swaping
12161 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
12162 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
12165 // prevent inversion of a triangle
12166 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
12167 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
12168 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
12171 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
12172 bestCouple = iSide;
12175 if ( bestCouple >= 0 )
12177 triaCouples.push_back( trias[bestCouple] );
12178 involvedFaces.insert ( trias[bestCouple].second );
12182 involvedFaces.erase( badTrias[iTia] );
12185 if ( triaCouples.empty() )
12190 SMESH_MeshEditor editor( helper.GetMesh() );
12191 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
12192 for ( size_t i = 0; i < triaCouples.size(); ++i )
12194 dumpChangeNodes( triaCouples[i].first );
12195 dumpChangeNodes( triaCouples[i].second );
12196 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
12199 if ( involvedNodes )
12200 for ( size_t i = 0; i < triaCouples.size(); ++i )
12202 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
12203 triaCouples[i].first->end_nodes() );
12204 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
12205 triaCouples[i].second->end_nodes() );
12208 // just for debug dump resulting triangles
12209 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
12210 for ( size_t i = 0; i < triaCouples.size(); ++i )
12212 dumpChangeNodes( triaCouples[i].first );
12213 dumpChangeNodes( triaCouples[i].second );
12217 //================================================================================
12219 * \brief Move target node to it's final position on the FACE during shrinking
12221 //================================================================================
12223 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
12224 const TopoDS_Face& F,
12225 _EdgesOnShape& eos,
12226 SMESH_MesherHelper& helper )
12229 return false; // already at the target position
12231 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
12233 if ( eos.SWOLType() == TopAbs_FACE )
12235 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
12236 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
12237 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
12238 const double uvLen = tgtUV.Distance( curUV );
12239 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
12241 // Select shrinking step such that not to make faces with wrong orientation.
12242 double stepSize = 1e100;
12243 for ( size_t i = 0; i < _simplices.size(); ++i )
12245 if ( !_simplices[i]._nPrev->isMarked() ||
12246 !_simplices[i]._nNext->isMarked() )
12247 continue; // simplex of quadrangle created by addBoundaryElements()
12249 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
12250 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev, tgtNode );
12251 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext, tgtNode );
12252 gp_XY dirN = uvN2 - uvN1;
12253 double det = uvDir.Crossed( dirN );
12254 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
12255 gp_XY dirN2Cur = curUV - uvN1;
12256 double step = dirN.Crossed( dirN2Cur ) / det;
12258 stepSize = Min( step, stepSize );
12261 if ( uvLen <= stepSize )
12267 else if ( stepSize > 0 )
12269 newUV = curUV + uvDir.XY() * stepSize * kSafe;
12275 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
12276 pos->SetUParameter( newUV.X() );
12277 pos->SetVParameter( newUV.Y() );
12280 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
12281 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
12282 dumpMove( tgtNode );
12284 if ( surface.IsNull() ) {}
12287 else // _sWOL is TopAbs_EDGE
12289 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
12290 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
12291 SMDS_EdgePositionPtr tgtPos = tgtNode->GetPosition();
12293 const double u2 = helper.GetNodeU( E, n2, tgtNode );
12294 const double uSrc = _pos[0].Coord( U_SRC );
12295 const double lenTgt = _pos[0].Coord( LEN_TGT );
12297 double newU = _pos[0].Coord( U_TGT );
12298 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
12300 Set( _LayerEdge::SHRUNK );
12305 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
12307 tgtPos->SetUParameter( newU );
12309 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
12310 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
12311 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
12312 dumpMove( tgtNode );
12319 //================================================================================
12321 * \brief Perform smooth on the FACE
12322 * \retval bool - true if the node has been moved
12324 //================================================================================
12326 bool _SmoothNode::Smooth(int& nbBad,
12327 Handle(Geom_Surface)& surface,
12328 SMESH_MesherHelper& helper,
12329 const double refSign,
12333 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
12335 // get uv of surrounding nodes
12336 vector<gp_XY> uv( _simplices.size() );
12337 for ( size_t i = 0; i < _simplices.size(); ++i )
12338 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
12340 // compute new UV for the node
12341 gp_XY newPos (0,0);
12342 if ( how == TFI && _simplices.size() == 4 )
12345 for ( size_t i = 0; i < _simplices.size(); ++i )
12346 if ( _simplices[i]._nOpp )
12347 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
12349 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
12351 newPos = helper.calcTFI ( 0.5, 0.5,
12352 corners[0], corners[1], corners[2], corners[3],
12353 uv[1], uv[2], uv[3], uv[0] );
12355 else if ( how == ANGULAR )
12357 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
12359 else if ( how == CENTROIDAL && _simplices.size() > 3 )
12361 // average centers of diagonals wieghted with their reciprocal lengths
12362 if ( _simplices.size() == 4 )
12364 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
12365 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
12366 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
12370 double sumWeight = 0;
12371 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
12372 for ( int i = 0; i < nb; ++i )
12375 int iTo = i + _simplices.size() - 1;
12376 for ( int j = iFrom; j < iTo; ++j )
12378 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
12379 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
12381 newPos += w * ( uv[i]+uv[i2] );
12384 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
12389 // Laplacian smooth
12390 for ( size_t i = 0; i < _simplices.size(); ++i )
12392 newPos /= _simplices.size();
12395 // count quality metrics (orientation) of triangles around the node
12396 int nbOkBefore = 0;
12397 gp_XY tgtUV = helper.GetNodeUV( face, _node );
12398 for ( size_t i = 0; i < _simplices.size(); ++i )
12399 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
12402 for ( size_t i = 0; i < _simplices.size(); ++i )
12403 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
12405 if ( nbOkAfter < nbOkBefore )
12407 nbBad += _simplices.size() - nbOkBefore;
12411 SMDS_FacePositionPtr pos = _node->GetPosition();
12412 pos->SetUParameter( newPos.X() );
12413 pos->SetVParameter( newPos.Y() );
12420 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
12421 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
12425 nbBad += _simplices.size() - nbOkAfter;
12426 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
12429 //================================================================================
12431 * \brief Computes new UV using angle based smoothing technique
12433 //================================================================================
12435 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
12436 const gp_XY& uvToFix,
12437 const double refSign)
12439 uv.push_back( uv.front() );
12441 vector< gp_XY > edgeDir ( uv.size() );
12442 vector< double > edgeSize( uv.size() );
12443 for ( size_t i = 1; i < edgeDir.size(); ++i )
12445 edgeDir [i-1] = uv[i] - uv[i-1];
12446 edgeSize[i-1] = edgeDir[i-1].Modulus();
12447 if ( edgeSize[i-1] < numeric_limits<double>::min() )
12448 edgeDir[i-1].SetX( 100 );
12450 edgeDir[i-1] /= edgeSize[i-1] * refSign;
12452 edgeDir.back() = edgeDir.front();
12453 edgeSize.back() = edgeSize.front();
12457 for ( size_t i = 1; i < edgeDir.size(); ++i )
12459 const int i1 = i-1;
12460 if ( edgeDir[i1].X() > 1. ) continue;
12461 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
12462 if ( i == edgeDir.size() ) break;
12464 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
12465 gp_XY norm2( -edgeDir[i ].Y(), edgeDir[i ].X() );
12466 gp_XY bisec = norm1 + norm2;
12467 double bisecSize = bisec.Modulus();
12468 if ( bisecSize < numeric_limits<double>::min() )
12470 bisec = -edgeDir[i1] + edgeDir[i];
12471 bisecSize = bisec.Modulus();
12473 bisec /= bisecSize;
12475 gp_XY dirToN = uvToFix - p;
12476 double distToN = bisec * dirToN;
12477 if ( bisec * dirToN < 0 )
12478 distToN = -distToN;
12480 double wgt = edgeSize[i1] + edgeSize[i];
12481 newPos += ( p + bisec * distToN ) * wgt;
12488 //================================================================================
12490 * \brief Keep a _LayerEdge inflated along the EDGE
12492 //================================================================================
12494 void _Shrinker1D::AddEdge( const _LayerEdge* e,
12495 _EdgesOnShape& eos,
12496 SMESH_MesherHelper& helper )
12499 if ( _nodes.empty() )
12501 _edges[0] = _edges[1] = 0;
12504 // check _LayerEdge
12505 if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
12507 if ( eos.SWOLType() != TopAbs_EDGE )
12508 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
12509 if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
12510 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
12512 // store _LayerEdge
12513 _geomEdge = TopoDS::Edge( eos._sWOL );
12515 BRep_Tool::Range( _geomEdge, f,l );
12516 double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
12517 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
12519 // Check if the nodes are already shrunk by another SOLID
12521 const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
12522 const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
12524 _done = (( tgtNode0 && tgtNode0->NbInverseElements( SMDSAbs_Edge ) == 2 ) ||
12525 ( tgtNode1 && tgtNode1->NbInverseElements( SMDSAbs_Edge ) == 2 ));
12527 _nodes.resize( 1, nullptr );
12531 if ( _nodes.empty() )
12533 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
12534 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
12536 TopLoc_Location loc;
12537 Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
12538 GeomAdaptor_Curve aCurve(C, f,l);
12539 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
12541 smIdType nbExpectNodes = eSubMesh->NbNodes();
12542 _initU .reserve( nbExpectNodes );
12543 _normPar.reserve( nbExpectNodes );
12544 _nodes .reserve( nbExpectNodes );
12545 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
12546 while ( nIt->more() )
12548 const SMDS_MeshNode* node = nIt->next();
12550 // skip refinement nodes
12551 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
12552 node == tgtNode0 || node == tgtNode1 )
12554 bool hasMarkedFace = false;
12555 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
12556 while ( fIt->more() && !hasMarkedFace )
12557 hasMarkedFace = fIt->next()->isMarked();
12558 if ( !hasMarkedFace )
12561 _nodes.push_back( node );
12562 _initU.push_back( helper.GetNodeU( _geomEdge, node ));
12563 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
12564 _normPar.push_back( len / totLen );
12569 // remove target node of the _LayerEdge from _nodes
12570 size_t nbFound = 0;
12571 for ( size_t i = 0; i < _nodes.size(); ++i )
12572 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
12573 _nodes[i] = 0, nbFound++;
12574 if ( nbFound == _nodes.size() )
12579 //================================================================================
12581 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
12583 //================================================================================
12585 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
12587 if ( _done || _nodes.empty())
12589 const _LayerEdge* e = _edges[0];
12590 if ( !e ) e = _edges[1];
12593 _done = (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
12594 ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
12597 if ( set3D || _done )
12599 dumpFunction(SMESH_Comment("shrink1D_E") << helper.GetMeshDS()->ShapeToIndex( _geomEdge )<<
12600 "_F" << helper.GetSubShapeID() );
12601 Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
12602 GeomAdaptor_Curve aCurve(C, f,l);
12605 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
12607 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
12608 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
12610 for ( size_t i = 0; i < _nodes.size(); ++i )
12612 if ( !_nodes[i] ) continue;
12613 double len = totLen * _normPar[i];
12614 GCPnts_AbscissaPoint discret( aCurve, len, f );
12615 if ( !discret.IsDone() )
12616 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
12617 double u = discret.Parameter();
12618 SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12619 pos->SetUParameter( u );
12620 gp_Pnt p = C->Value( u );
12621 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
12622 dumpMove( _nodes[i] );
12628 BRep_Tool::Range( _geomEdge, f,l );
12630 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
12632 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
12634 for ( size_t i = 0; i < _nodes.size(); ++i )
12636 if ( !_nodes[i] ) continue;
12637 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
12638 SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12639 pos->SetUParameter( u );
12644 //================================================================================
12646 * \brief Restore initial parameters of nodes on EDGE
12648 //================================================================================
12650 void _Shrinker1D::RestoreParams()
12653 for ( size_t i = 0; i < _nodes.size(); ++i )
12655 if ( !_nodes[i] ) continue;
12656 SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12657 pos->SetUParameter( _initU[i] );
12662 //================================================================================
12664 * \brief Replace source nodes by target nodes in shrunk mesh edges
12666 //================================================================================
12668 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
12670 const SMDS_MeshNode* nodes[3];
12671 for ( int i = 0; i < 2; ++i )
12673 if ( !_edges[i] ) continue;
12675 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
12676 if ( !eSubMesh ) return;
12677 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
12678 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
12679 const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
12680 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
12681 while ( eIt->more() )
12683 const SMDS_MeshElement* e = eIt->next();
12684 if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
12686 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
12687 for ( int iN = 0; iN < e->NbNodes(); ++iN )
12689 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
12690 nodes[iN] = ( n == srcNode ? tgtNode : n );
12692 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
12697 //================================================================================
12699 * \brief Setup quadPoints
12701 //================================================================================
12703 _Mapper2D::_Mapper2D( const TParam2ColumnMap & param2ColumnMap, const TNode2Edge& n2eMap )
12705 size_t i, iSize = _quadPoints.iSize = param2ColumnMap.size();
12706 size_t j, jSize = _quadPoints.jSize = param2ColumnMap.begin()->second.size();
12707 if ( _quadPoints.iSize < 3 ||
12708 _quadPoints.jSize < 3 )
12710 _quadPoints.uv_grid.resize( iSize * jSize );
12714 for ( auto & u_columnNodes : param2ColumnMap )
12716 for ( j = 0; j < u_columnNodes.second.size(); ++j )
12717 _quadPoints.UVPt( i, j ).node = u_columnNodes.second[ j ];
12721 // compute x parameter on borders
12722 uvPnt( 0, 0 ).x = 0;
12723 uvPnt( 0, jSize-1 ).x = 0;
12724 gp_Pnt p0, pPrev0 = SMESH_NodeXYZ( uvPnt( 0, 0 ).node );
12725 gp_Pnt p1, pPrev1 = SMESH_NodeXYZ( uvPnt( 0, jSize-1 ).node );
12726 for ( i = 1; i < iSize; ++i )
12728 p0 = SMESH_NodeXYZ( uvPnt( i, 0 ).node );
12729 p1 = SMESH_NodeXYZ( uvPnt( i, jSize-1 ).node );
12730 uvPnt( i, 0 ).x = uvPnt( i-1, 0 ).x + p0.Distance( pPrev0 );
12731 uvPnt( i, jSize-1 ).x = uvPnt( i-1, jSize-1 ).x + p1.Distance( pPrev1 );
12735 for ( i = 1; i < iSize-1; ++i )
12737 uvPnt( i, 0 ).x /= uvPnt( iSize-1, 0 ).x;
12738 uvPnt( i, jSize-1 ).x /= uvPnt( iSize-1, jSize-1 ).x;
12739 uvPnt( i, 0 ).y = 0;
12740 uvPnt( i, jSize-1 ).y = 1;
12743 // compute y parameter on borders
12744 uvPnt( 0, 0 ).y = 0;
12745 uvPnt( iSize-1, 0 ).y = 0;
12746 pPrev0 = SMESH_NodeXYZ( uvPnt( 0, 0 ).node );
12747 pPrev1 = SMESH_NodeXYZ( uvPnt( iSize-1, 0 ).node );
12748 for ( j = 1; j < jSize; ++j )
12750 p0 = SMESH_NodeXYZ( uvPnt( 0, j ).node );
12751 p1 = SMESH_NodeXYZ( uvPnt( iSize-1, j ).node );
12752 uvPnt( 0, j ).y = uvPnt( 0, j-1 ).y + p0.Distance( pPrev0 );
12753 uvPnt( iSize-1, j ).y = uvPnt( iSize-1, j-1 ).y + p1.Distance( pPrev1 );
12757 for ( j = 1; j < jSize-1; ++j )
12759 uvPnt( 0, j ).y /= uvPnt( 0, jSize-1 ).y;
12760 uvPnt( iSize-1, j ).y /= uvPnt( iSize-1, jSize-1 ).y;
12761 uvPnt( 0, j ).x = 0;
12762 uvPnt( iSize-1, j ).x = 1;
12765 // compute xy of internal nodes
12766 for ( i = 1; i < iSize-1; ++i )
12768 const double x0 = uvPnt( i, 0 ).x;
12769 const double x1 = uvPnt( i, jSize-1 ).x;
12770 for ( j = 1; j < jSize-1; ++j )
12772 const double y0 = uvPnt( 0, j ).y;
12773 const double y1 = uvPnt( iSize-1, j ).y;
12774 double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
12775 double y = y0 + x * (y1 - y0);
12776 uvPnt( i, j ).x = x;
12777 uvPnt( i, j ).y = y;
12781 // replace base nodes with target ones
12782 for ( i = 0; i < iSize; ++i )
12783 for ( j = 0; j < jSize; ++j )
12785 auto n2e = n2eMap.find( uvPnt( i, j ).node );
12786 uvPnt( i, j ).node = n2e->second->_nodes.back();
12792 //================================================================================
12794 * \brief Compute positions of nodes of 2D structured mesh using TFI
12796 //================================================================================
12798 bool _Mapper2D::ComputeNodePositions()
12800 if ( _quadPoints.uv_grid.empty() )
12803 size_t i, iSize = _quadPoints.iSize;
12804 size_t j, jSize = _quadPoints.jSize;
12806 SMESH_NodeXYZ a0 ( uvPnt( 0, 0 ).node );
12807 SMESH_NodeXYZ a1 ( uvPnt( iSize-1, 0 ).node );
12808 SMESH_NodeXYZ a2 ( uvPnt( iSize-1, jSize-1 ).node );
12809 SMESH_NodeXYZ a3 ( uvPnt( 0, jSize-1 ).node );
12811 for ( i = 1; i < iSize-1; ++i )
12813 SMESH_NodeXYZ p0 ( uvPnt( i, 0 ).node );
12814 SMESH_NodeXYZ p2 ( uvPnt( i, jSize-1 ).node );
12815 for ( j = 1; j < jSize-1; ++j )
12817 SMESH_NodeXYZ p1 ( uvPnt( iSize-1, j ).node );
12818 SMESH_NodeXYZ p3 ( uvPnt( 0, j ).node );
12819 double x = uvPnt( i, j ).x;
12820 double y = uvPnt( i, j ).y;
12822 gp_XYZ p = SMESH_MesherHelper::calcTFI( x, y, a0,a1,a2,a3, p0,p1,p2,p3 );
12823 const_cast< SMDS_MeshNode* >( uvPnt( i, j ).node )->setXYZ( p.X(), p.Y(), p.Z() );
12825 dumpMove( uvPnt( i, j ).node );
12831 //================================================================================
12833 * \brief Creates 2D and 1D elements on boundaries of new prisms
12835 //================================================================================
12837 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
12839 SMESH_MesherHelper helper( *_mesh );
12841 vector< const SMDS_MeshNode* > faceNodes;
12843 //for ( size_t i = 0; i < _sdVec.size(); ++i )
12845 //_SolidData& data = _sdVec[i];
12846 TopTools_IndexedMapOfShape geomEdges;
12847 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
12848 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
12850 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
12851 const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
12852 if ( data._noShrinkShapes.count( edgeID ))
12855 // Get _LayerEdge's based on E
12857 map< double, const SMDS_MeshNode* > u2nodes;
12858 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
12861 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
12862 TNode2Edge & n2eMap = data._n2eMap;
12863 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
12865 //check if 2D elements are needed on E
12866 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
12867 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
12868 ledges.push_back( n2e->second );
12870 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
12871 continue; // no layers on E
12872 ledges.push_back( n2eMap[ u2n->second ]);
12874 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
12875 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
12876 int nbSharedPyram = 0;
12877 SMDS_ElemIteratorPtr vIt = tgtN1->GetInverseElementIterator(SMDSAbs_Volume);
12878 while ( vIt->more() )
12880 const SMDS_MeshElement* v = vIt->next();
12881 nbSharedPyram += int( v->GetNodeIndex( tgtN0 ) >= 0 );
12883 if ( nbSharedPyram > 1 )
12884 continue; // not free border of the pyramid
12887 faceNodes.push_back( ledges[0]->_nodes[0] );
12888 faceNodes.push_back( ledges[1]->_nodes[0] );
12889 if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
12890 if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
12892 if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
12893 continue; // faces already created
12895 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
12896 ledges.push_back( n2eMap[ u2n->second ]);
12898 // Find out orientation and type of face to create
12900 bool reverse = false, isOnFace;
12903 map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
12904 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
12906 F = e2f->second.Oriented( TopAbs_FORWARD );
12907 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
12908 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
12909 reverse = !reverse, F.Reverse();
12910 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
12911 reverse = !reverse;
12913 else if ( !data._ignoreFaceIds.count( e2f->first ))
12915 // find FACE with layers sharing E
12916 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
12918 F = *( fIt->next() );
12920 // Find the sub-mesh to add new faces
12921 SMESHDS_SubMesh* sm = 0;
12923 sm = getMeshDS()->MeshElements( F );
12925 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
12927 return error("error in addBoundaryElements()", data._index);
12929 // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
12930 // faces for 3D meshing (PAL23414)
12931 SMESHDS_SubMesh* adjSM = 0;
12934 const TGeomID faceID = sm->GetID();
12935 PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
12936 while ( const TopoDS_Shape* solid = soIt->next() )
12937 if ( !solid->IsSame( data._solid ))
12939 size_t iData = _solids.FindIndex( *solid ) - 1;
12940 if ( iData < _sdVec.size() &&
12941 _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
12942 _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
12944 SMESH_ProxyMesh::SubMesh* proxySub =
12945 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
12946 if ( proxySub && proxySub->NbElements() > 0 )
12953 const int dj1 = reverse ? 0 : 1;
12954 const int dj2 = reverse ? 1 : 0;
12955 vector< const SMDS_MeshElement*> ff; // new faces row
12956 SMESHDS_Mesh* m = getMeshDS();
12957 for ( size_t j = 1; j < ledges.size(); ++j )
12959 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
12960 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
12961 ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
12962 if ( nn1.size() == nn2.size() )
12965 for ( size_t z = 1; z < nn1.size(); ++z )
12966 sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
12968 for ( size_t z = 1; z < nn1.size(); ++z )
12969 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
12971 else if ( nn1.size() == 1 )
12974 for ( size_t z = 1; z < nn2.size(); ++z )
12975 sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
12977 for ( size_t z = 1; z < nn2.size(); ++z )
12978 sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
12983 for ( size_t z = 1; z < nn1.size(); ++z )
12984 sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
12986 for ( size_t z = 1; z < nn1.size(); ++z )
12987 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
12990 if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
12992 for ( size_t z = 0; z < ff.size(); ++z )
12994 adjSM->AddElement( ff[ z ]);
13000 for ( int isFirst = 0; isFirst < 2; ++isFirst )
13002 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
13003 _EdgesOnShape* eos = data.GetShapeEdges( edge );
13004 if ( eos && eos->SWOLType() == TopAbs_EDGE )
13006 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
13007 if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
13009 helper.SetSubShape( eos->_sWOL );
13010 helper.SetElementsOnShape( true );
13011 for ( size_t z = 1; z < nn.size(); ++z )
13012 helper.AddEdge( nn[z-1], nn[z] );
13016 } // loop on EDGE's
13017 } // loop on _SolidData's