1 // Copyright (C) 2007-2019 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_ViscousLayers.cxx
21 // Created : Wed Dec 1 15:15:34 2010
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers.hxx"
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_PolygonalFaceOfNodes.hxx"
31 #include "SMDS_SetIterator.hxx"
32 #include "SMESHDS_Group.hxx"
33 #include "SMESHDS_Hypothesis.hxx"
34 #include "SMESHDS_Mesh.hxx"
35 #include "SMESH_Algo.hxx"
36 #include "SMESH_ComputeError.hxx"
37 #include "SMESH_ControlsDef.hxx"
38 #include "SMESH_Gen.hxx"
39 #include "SMESH_Group.hxx"
40 #include "SMESH_HypoFilter.hxx"
41 #include "SMESH_Mesh.hxx"
42 #include "SMESH_MeshAlgos.hxx"
43 #include "SMESH_MesherHelper.hxx"
44 #include "SMESH_ProxyMesh.hxx"
45 #include "SMESH_subMesh.hxx"
46 #include "SMESH_MeshEditor.hxx"
47 #include "SMESH_subMeshEventListener.hxx"
48 #include "StdMeshers_FaceSide.hxx"
49 #include "StdMeshers_ViscousLayers2D.hxx"
51 #include <Adaptor3d_HSurface.hxx>
52 #include <BRepAdaptor_Curve.hxx>
53 #include <BRepAdaptor_Curve2d.hxx>
54 #include <BRepAdaptor_Surface.hxx>
55 //#include <BRepLProp_CLProps.hxx>
56 #include <BRepLProp_SLProps.hxx>
57 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
58 #include <BRep_Tool.hxx>
59 #include <Bnd_B2d.hxx>
60 #include <Bnd_B3d.hxx>
62 #include <GCPnts_AbscissaPoint.hxx>
63 #include <GCPnts_TangentialDeflection.hxx>
64 #include <Geom2d_Circle.hxx>
65 #include <Geom2d_Line.hxx>
66 #include <Geom2d_TrimmedCurve.hxx>
67 #include <GeomAdaptor_Curve.hxx>
68 #include <GeomLib.hxx>
69 #include <Geom_Circle.hxx>
70 #include <Geom_Curve.hxx>
71 #include <Geom_Line.hxx>
72 #include <Geom_TrimmedCurve.hxx>
73 #include <Precision.hxx>
74 #include <Standard_ErrorHandler.hxx>
75 #include <Standard_Failure.hxx>
76 #include <TColStd_Array1OfReal.hxx>
78 #include <TopExp_Explorer.hxx>
79 #include <TopTools_IndexedMapOfShape.hxx>
80 #include <TopTools_ListOfShape.hxx>
81 #include <TopTools_MapIteratorOfMapOfShape.hxx>
82 #include <TopTools_MapOfShape.hxx>
84 #include <TopoDS_Edge.hxx>
85 #include <TopoDS_Face.hxx>
86 #include <TopoDS_Vertex.hxx>
88 #include <gp_Cone.hxx>
89 #include <gp_Sphere.hxx>
98 #include <unordered_map>
102 //#define __NOT_INVALIDATE_BAD_SMOOTH
103 //#define __NODES_AT_POS
106 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
107 #define BLOCK_INFLATION // of individual _LayerEdge's
108 #define OLD_NEF_POLYGON
112 //================================================================================
117 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
119 const double theMinSmoothCosin = 0.1;
120 const double theSmoothThickToElemSizeRatio = 0.6;
121 const double theMinSmoothTriaAngle = 30;
122 const double theMinSmoothQuadAngle = 45;
124 // what part of thickness is allowed till intersection
125 // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
126 const double theThickToIntersection = 1.5;
128 bool needSmoothing( double cosin, double tgtThick, double elemSize )
130 return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
132 double getSmoothingThickness( double cosin, double elemSize )
134 return theSmoothThickToElemSizeRatio * elemSize / cosin;
138 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
139 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
141 struct _MeshOfSolid : public SMESH_ProxyMesh,
142 public SMESH_subMeshEventListenerData
144 bool _n2nMapComputed;
145 SMESH_ComputeErrorPtr _warning;
147 _MeshOfSolid( SMESH_Mesh* mesh)
148 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
150 SMESH_ProxyMesh::setMesh( *mesh );
153 // returns submesh for a geom face
154 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
156 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
157 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
159 void setNode2Node(const SMDS_MeshNode* srcNode,
160 const SMDS_MeshNode* proxyNode,
161 const SMESH_ProxyMesh::SubMesh* subMesh)
163 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
166 //--------------------------------------------------------------------------------
168 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
169 * It is used to clear an inferior dim sub-meshes modified by viscous layers
171 class _ShrinkShapeListener : SMESH_subMeshEventListener
173 _ShrinkShapeListener()
174 : SMESH_subMeshEventListener(/*isDeletable=*/false,
175 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
177 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
178 virtual void ProcessEvent(const int event,
180 SMESH_subMesh* solidSM,
181 SMESH_subMeshEventListenerData* data,
182 const SMESH_Hypothesis* hyp)
184 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
186 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
190 //--------------------------------------------------------------------------------
192 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
193 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
194 * delete the data as soon as it has been used
196 class _ViscousListener : SMESH_subMeshEventListener
199 SMESH_subMeshEventListener(/*isDeletable=*/false,
200 "StdMeshers_ViscousLayers::_ViscousListener") {}
201 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
203 virtual void ProcessEvent(const int event,
205 SMESH_subMesh* subMesh,
206 SMESH_subMeshEventListenerData* data,
207 const SMESH_Hypothesis* hyp)
209 if (( SMESH_subMesh::COMPUTE_EVENT == eventType ) &&
210 ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
211 SMESH_subMesh::SUBMESH_COMPUTED != event ))
213 // delete SMESH_ProxyMesh containing temporary faces
214 subMesh->DeleteEventListener( this );
217 // Finds or creates proxy mesh of the solid
218 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
219 const TopoDS_Shape& solid,
222 if ( !mesh ) return 0;
223 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
224 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
225 if ( !data && toCreate )
227 data = new _MeshOfSolid(mesh);
228 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
229 sm->SetEventListener( Get(), data, sm );
233 // Removes proxy mesh of the solid
234 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
236 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
240 //================================================================================
242 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
243 * the main shape when sub-mesh of the main shape is cleared,
244 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
247 //================================================================================
249 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
251 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
252 SMESH_subMeshEventListenerData* data =
253 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
256 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
257 data->mySubMeshes.end())
258 data->mySubMeshes.push_back( sub );
262 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
263 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
267 //--------------------------------------------------------------------------------
269 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
270 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
271 * The class is used to check validity of face or volumes around a smoothed node;
272 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
276 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
277 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
278 _Simplex(const SMDS_MeshNode* nPrev=0,
279 const SMDS_MeshNode* nNext=0,
280 const SMDS_MeshNode* nOpp=0)
281 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
282 bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
284 const double M[3][3] =
285 {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
286 { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
287 { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
288 vol = ( + M[0][0] * M[1][1] * M[2][2]
289 + M[0][1] * M[1][2] * M[2][0]
290 + M[0][2] * M[1][0] * M[2][1]
291 - M[0][0] * M[1][2] * M[2][1]
292 - M[0][1] * M[1][0] * M[2][2]
293 - M[0][2] * M[1][1] * M[2][0]);
296 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
298 SMESH_TNodeXYZ pSrc( nSrc );
299 return IsForward( &pSrc, &pTgt, vol );
301 bool IsForward(const gp_XY& tgtUV,
302 const SMDS_MeshNode* smoothedNode,
303 const TopoDS_Face& face,
304 SMESH_MesherHelper& helper,
305 const double refSign) const
307 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
308 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
309 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
311 return d*refSign > 1e-100;
313 bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
315 SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
316 if ( !_nOpp ) // triangle
318 gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
319 double tp2 = tp.SquareMagnitude();
320 double pn2 = pn.SquareMagnitude();
321 double nt2 = nt.SquareMagnitude();
323 if ( tp2 < pn2 && tp2 < nt2 )
324 minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
325 else if ( pn2 < nt2 )
326 minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
328 minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
330 static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
331 Cos( theMinSmoothTriaAngle * M_PI / 180. ));
332 return minAngle < theMaxCos2;
336 SMESH_TNodeXYZ pOpp( _nOpp );
337 gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
338 double tp2 = tp.SquareMagnitude();
339 double po2 = po.SquareMagnitude();
340 double on2 = on.SquareMagnitude();
341 double nt2 = nt.SquareMagnitude();
342 minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
343 (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
344 Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
345 (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
347 static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
348 Cos( theMinSmoothQuadAngle * M_PI / 180. ));
349 return minAngle < theMaxCos2;
352 bool IsNeighbour(const _Simplex& other) const
354 return _nPrev == other._nNext || _nNext == other._nPrev;
356 bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
357 static void GetSimplices( const SMDS_MeshNode* node,
358 vector<_Simplex>& simplices,
359 const set<TGeomID>& ingnoreShapes,
360 const _SolidData* dataToCheckOri = 0,
361 const bool toSort = false);
362 static void SortSimplices(vector<_Simplex>& simplices);
364 //--------------------------------------------------------------------------------
366 * Structure used to take into account surface curvature while smoothing
371 double _k; // factor to correct node smoothed position
372 double _h2lenRatio; // avgNormProj / (2*avgDist)
373 gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
375 static _Curvature* New( double avgNormProj, double avgDist )
378 if ( fabs( avgNormProj / avgDist ) > 1./200 )
381 c->_r = avgDist * avgDist / avgNormProj;
382 c->_k = avgDist * avgDist / c->_r / c->_r;
383 //c->_k = avgNormProj / c->_r;
384 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
385 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
387 c->_uv.SetCoord( 0., 0. );
391 double lenDelta(double len) const { return _k * ( _r + len ); }
392 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
394 //--------------------------------------------------------------------------------
398 struct _EdgesOnShape;
400 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
402 //--------------------------------------------------------------------------------
404 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
405 * and a node of the most internal layer (_nodes.back())
409 typedef gp_XYZ (_LayerEdge::*PSmooFun)();
411 vector< const SMDS_MeshNode*> _nodes;
413 gp_XYZ _normal; // to boundary of solid
414 vector<gp_XYZ> _pos; // points computed during inflation
415 double _len; // length achieved with the last inflation step
416 double _maxLen; // maximal possible length
417 double _cosin; // of angle (_normal ^ surface)
418 double _minAngle; // of _simplices
419 double _lenFactor; // to compute _len taking _cosin into account
422 // simplices connected to the source node (_nodes[0]);
423 // used for smoothing and quality check of _LayerEdge's based on the FACE
424 vector<_Simplex> _simplices;
425 vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
426 PSmooFun _smooFunction; // smoothing function
427 _Curvature* _curvature;
428 // data for smoothing of _LayerEdge's based on the EDGE
429 _2NearEdges* _2neibors;
431 enum EFlags { TO_SMOOTH = 0x0000001,
432 MOVED = 0x0000002, // set by _neibors[i]->SetNewLength()
433 SMOOTHED = 0x0000004, // set by _LayerEdge::Smooth()
434 DIFFICULT = 0x0000008, // near concave VERTEX
435 ON_CONCAVE_FACE = 0x0000010,
436 BLOCKED = 0x0000020, // not to inflate any more
437 INTERSECTED = 0x0000040, // close intersection with a face found
438 NORMAL_UPDATED = 0x0000080,
439 UPD_NORMAL_CONV = 0x0000100, // to update normal on boundary of concave FACE
440 MARKED = 0x0000200, // local usage
441 MULTI_NORMAL = 0x0000400, // a normal is invisible by some of surrounding faces
442 NEAR_BOUNDARY = 0x0000800, // is near FACE boundary forcing smooth
443 SMOOTHED_C1 = 0x0001000, // is on _eosC1
444 DISTORTED = 0x0002000, // was bad before smoothing
445 RISKY_SWOL = 0x0004000, // SWOL is parallel to a source FACE
446 SHRUNK = 0x0008000, // target node reached a tgt position while shrink()
447 UNUSED_FLAG = 0x0100000 // to add user flags after
449 bool Is ( int flag ) const { return _flags & flag; }
450 void Set ( int flag ) { _flags |= flag; }
451 void Unset( int flag ) { _flags &= ~flag; }
452 std::string DumpFlags() const; // debug
454 void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
455 bool SetNewLength2d( Handle(Geom_Surface)& surface,
456 const TopoDS_Face& F,
458 SMESH_MesherHelper& helper );
459 void SetDataByNeighbors( const SMDS_MeshNode* n1,
460 const SMDS_MeshNode* n2,
461 const _EdgesOnShape& eos,
462 SMESH_MesherHelper& helper);
463 void Block( _SolidData& data );
464 void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
465 void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
466 const TNode2Edge& n2eMap);
467 void SmoothPos( const vector< double >& segLen, const double tol );
468 int GetSmoothedPos( const double tol );
469 int Smooth(const int step, const bool isConcaveFace, bool findBest);
470 int Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
471 int CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
472 void SmoothWoCheck();
473 bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
474 const TopoDS_Face& F,
475 SMESH_MesherHelper& helper);
476 void MoveNearConcaVer( const _EdgesOnShape* eov,
477 const _EdgesOnShape* eos,
479 vector< _LayerEdge* > & badSmooEdges);
480 bool FindIntersection( SMESH_ElementSearcher& searcher,
482 const double& epsilon,
484 const SMDS_MeshElement** face = 0);
485 bool SegTriaInter( const gp_Ax1& lastSegment,
490 const double& epsilon) const;
491 bool SegTriaInter( const gp_Ax1& lastSegment,
492 const SMDS_MeshNode* n0,
493 const SMDS_MeshNode* n1,
494 const SMDS_MeshNode* n2,
496 const double& epsilon) const
497 { return SegTriaInter( lastSegment,
498 SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
501 const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
502 gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
503 gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
504 gp_XY LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which=-1 ) const;
505 bool IsOnEdge() const { return _2neibors; }
506 bool IsOnFace() const { return ( _nodes[0]->GetPosition()->GetDim() == 2 ); }
507 int BaseShapeDim() const { return _nodes[0]->GetPosition()->GetDim(); }
508 gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
509 void SetCosin( double cosin );
510 void SetNormal( const gp_XYZ& n ) { _normal = n; }
511 void SetMaxLen( double l ) { _maxLen = l; }
512 int NbSteps() const { return _pos.size() - 1; } // nb inlation steps
513 bool IsNeiborOnEdge( const _LayerEdge* edge ) const;
514 void SetSmooLen( double len ) { // set _len at which smoothing is needed
515 _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
517 double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
519 gp_XYZ smoothLaplacian();
520 gp_XYZ smoothAngular();
521 gp_XYZ smoothLengthWeighted();
522 gp_XYZ smoothCentroidal();
523 gp_XYZ smoothNefPolygon();
525 enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
526 static const int theNbSmooFuns = FUN_NB;
527 static PSmooFun _funs[theNbSmooFuns];
528 static const char* _funNames[theNbSmooFuns+1];
529 int smooFunID( PSmooFun fun=0) const;
531 _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
532 &_LayerEdge::smoothLengthWeighted,
533 &_LayerEdge::smoothCentroidal,
534 &_LayerEdge::smoothNefPolygon,
535 &_LayerEdge::smoothAngular };
536 const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
544 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
546 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
547 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
550 //--------------------------------------------------------------------------------
552 * A 2D half plane used by _LayerEdge::smoothNefPolygon()
556 gp_XY _pos, _dir, _inNorm;
557 bool IsOut( const gp_XY p, const double tol ) const
559 return _inNorm * ( p - _pos ) < -tol;
561 bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
563 //const double eps = 1e-10;
564 double D = _dir.Crossed( hp._dir );
565 if ( fabs(D) < std::numeric_limits<double>::min())
567 gp_XY vec21 = _pos - hp._pos;
568 double u = hp._dir.Crossed( vec21 ) / D;
569 intPnt = _pos + _dir * u;
573 //--------------------------------------------------------------------------------
575 * Structure used to smooth a _LayerEdge based on an EDGE.
579 double _wgt [2]; // weights of _nodes
580 _LayerEdge* _edges[2];
582 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
585 _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
586 const SMDS_MeshNode* tgtNode(bool is2nd) {
587 return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
589 const SMDS_MeshNode* srcNode(bool is2nd) {
590 return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
593 std::swap( _wgt [0], _wgt [1] );
594 std::swap( _edges[0], _edges[1] );
596 void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
597 _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
599 bool include( const _LayerEdge* e ) {
600 return ( _edges[0] == e || _edges[1] == e );
605 //--------------------------------------------------------------------------------
607 * \brief Layers parameters got by averaging several hypotheses
611 AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
612 :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
616 void Add( const StdMeshers_ViscousLayers* hyp )
621 _nbLayers = hyp->GetNumberLayers();
622 //_thickness += hyp->GetTotalThickness();
623 _thickness = Max( _thickness, hyp->GetTotalThickness() );
624 _stretchFactor += hyp->GetStretchFactor();
625 _method = hyp->GetMethod();
628 double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
629 double GetStretchFactor() const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
630 int GetNumberLayers() const { return _nbLayers; }
631 int GetMethod() const { return _method; }
633 bool UseSurfaceNormal() const
634 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
635 bool ToSmooth() const
636 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
637 bool IsOffsetMethod() const
638 { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
641 int _nbLayers, _nbHyps, _method;
642 double _thickness, _stretchFactor;
645 //--------------------------------------------------------------------------------
647 * \brief _LayerEdge's on a shape and other shape data
651 vector< _LayerEdge* > _edges;
655 SMESH_subMesh * _subMesh;
656 // face or edge w/o layer along or near which _edges are inflated
658 bool _isRegularSWOL; // w/o singularities
659 // averaged StdMeshers_ViscousLayers parameters
662 _Smoother1D* _edgeSmoother;
663 vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
664 vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
666 typedef std::unordered_map< const SMDS_MeshElement*, gp_XYZ > TFace2NormMap;
667 TFace2NormMap _faceNormals; // if _shape is FACE
668 vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
670 Handle(ShapeAnalysis_Surface) _offsetSurf;
671 _LayerEdge* _edgeForOffset;
673 _SolidData* _data; // parent SOLID
675 _LayerEdge* operator[](size_t i) const { return (_LayerEdge*) _edges[i]; }
676 size_t size() const { return _edges.size(); }
677 TopAbs_ShapeEnum ShapeType() const
678 { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
679 TopAbs_ShapeEnum SWOLType() const
680 { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
681 bool HasC1( const _EdgesOnShape* other ) const
682 { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
683 bool GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
684 _SolidData& GetData() const { return *_data; }
686 _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
689 //--------------------------------------------------------------------------------
691 * \brief Convex FACE whose radius of curvature is less than the thickness of
692 * layers. It is used to detect distortion of prisms based on a convex
693 * FACE and to update normals to enable further increasing the thickness
699 // edges whose _simplices are used to detect prism distortion
700 vector< _LayerEdge* > _simplexTestEdges;
702 // map a sub-shape to _SolidData::_edgesOnShape
703 map< TGeomID, _EdgesOnShape* > _subIdToEOS;
707 bool _normalsFixedOnBorders; // used in putOnOffsetSurface()
709 double GetMaxCurvature( _SolidData& data,
711 BRepLProp_SLProps& surfProp,
712 SMESH_MesherHelper& helper);
714 bool GetCenterOfCurvature( _LayerEdge* ledge,
715 BRepLProp_SLProps& surfProp,
716 SMESH_MesherHelper& helper,
717 gp_Pnt & center ) const;
718 bool CheckPrisms() const;
721 //--------------------------------------------------------------------------------
723 * \brief Structure holding _LayerEdge's based on EDGEs that will collide
724 * at inflation up to the full thickness. A detected collision
725 * is fixed in updateNormals()
727 struct _CollisionEdges
730 vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
731 const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
732 const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
735 //--------------------------------------------------------------------------------
737 * \brief Data of a SOLID
741 typedef const StdMeshers_ViscousLayers* THyp;
743 TopTools_MapOfShape _before; // SOLIDs to be computed before _solid
744 TGeomID _index; // SOLID id
745 _MeshOfSolid* _proxyMesh;
747 list< TopoDS_Shape > _hypShapes;
748 map< TGeomID, THyp > _face2hyp; // filled if _hyps.size() > 1
749 set< TGeomID > _reversedFaceIds;
750 set< TGeomID > _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
752 double _stepSize, _stepSizeCoeff, _geomSize;
753 const SMDS_MeshNode* _stepSizeNodes[2];
755 TNode2Edge _n2eMap; // nodes and _LayerEdge's based on them
757 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
758 map< TGeomID, TNode2Edge* > _s2neMap;
759 // _LayerEdge's with underlying shapes
760 vector< _EdgesOnShape > _edgesOnShape;
762 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
763 // layers and a FACE w/o layers
764 // value: the shape (FACE or EDGE) to shrink mesh on.
765 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
766 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
768 // Convex FACEs whose radius of curvature is less than the thickness of layers
769 map< TGeomID, _ConvexFace > _convexFaces;
771 // shapes (EDGEs and VERTEXes) shrink from which is forbidden due to collisions with
772 // the adjacent SOLID
773 set< TGeomID > _noShrinkShapes;
775 int _nbShapesToSmooth;
777 vector< _CollisionEdges > _collisionEdges;
778 set< TGeomID > _concaveFaces;
780 double _maxThickness; // of all _hyps
781 double _minThickness; // of all _hyps
783 double _epsilon; // precision for SegTriaInter()
785 SMESH_MesherHelper* _helper;
787 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
789 :_solid(s), _proxyMesh(m), _helper(0) {}
792 void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
793 void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
795 _ConvexFace* GetConvexFace( const TGeomID faceID ) {
796 map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
797 return id2face == _convexFaces.end() ? 0 : & id2face->second;
799 _EdgesOnShape* GetShapeEdges(const TGeomID shapeID );
800 _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
801 _EdgesOnShape* GetShapeEdges(const _LayerEdge* edge )
802 { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
804 SMESH_MesherHelper& GetHelper() const { return *_helper; }
806 void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
807 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
808 for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
809 _edgesOnShape[i]._edges[j]->Unset( flag );
811 void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
812 const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
814 void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
816 //--------------------------------------------------------------------------------
818 * \brief Offset plane used in getNormalByOffset()
824 int _faceIndexNext[2];
825 gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
828 _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
830 void ComputeIntersectionLine( _OffsetPlane& pln,
831 const TopoDS_Edge& E,
832 const TopoDS_Vertex& V );
833 gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
834 int NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
836 //--------------------------------------------------------------------------------
838 * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
840 struct _CentralCurveOnEdge
843 vector< gp_Pnt > _curvaCenters;
844 vector< _LayerEdge* > _ledges;
845 vector< gp_XYZ > _normals; // new normal for each of _ledges
846 vector< double > _segLength2;
849 TopoDS_Face _adjFace;
850 bool _adjFaceToSmooth;
852 void Append( const gp_Pnt& center, _LayerEdge* ledge )
854 if ( ledge->Is( _LayerEdge::MULTI_NORMAL ))
856 if ( _curvaCenters.size() > 0 )
857 _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
858 _curvaCenters.push_back( center );
859 _ledges.push_back( ledge );
860 _normals.push_back( ledge->_normal );
862 bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
863 void SetShapes( const TopoDS_Edge& edge,
864 const _ConvexFace& convFace,
866 SMESH_MesherHelper& helper);
868 //--------------------------------------------------------------------------------
870 * \brief Data of node on a shrinked FACE
874 const SMDS_MeshNode* _node;
875 vector<_Simplex> _simplices; // for quality check
877 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
879 bool Smooth(int& badNb,
880 Handle(Geom_Surface)& surface,
881 SMESH_MesherHelper& helper,
882 const double refSign,
886 gp_XY computeAngularPos(vector<gp_XY>& uv,
887 const gp_XY& uvToFix,
888 const double refSign );
891 //--------------------------------------------------------------------------------
893 * \brief Builder of viscous layers
895 class _ViscousBuilder
900 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
901 const TopoDS_Shape& shape);
902 // check validity of hypotheses
903 SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh& mesh,
904 const TopoDS_Shape& shape );
906 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
907 void RestoreListeners();
909 // computes SMESH_ProxyMesh::SubMesh::_n2n;
910 bool MakeN2NMap( _MeshOfSolid* pm );
914 bool findSolidsWithLayers();
915 bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
916 bool findFacesWithLayers(const bool onlyWith=false);
917 void getIgnoreFaces(const TopoDS_Shape& solid,
918 const StdMeshers_ViscousLayers* hyp,
919 const TopoDS_Shape& hypShape,
920 set<TGeomID>& ignoreFaces);
921 bool makeLayer(_SolidData& data);
922 void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
923 bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
924 SMESH_MesherHelper& helper, _SolidData& data);
925 gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
926 const TopoDS_Face& face,
927 SMESH_MesherHelper& helper,
929 bool shiftInside=false);
930 bool getFaceNormalAtSingularity(const gp_XY& uv,
931 const TopoDS_Face& face,
932 SMESH_MesherHelper& helper,
934 gp_XYZ getWeigthedNormal( const _LayerEdge* edge );
935 gp_XYZ getNormalByOffset( _LayerEdge* edge,
936 std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
938 bool lastNoOffset = false);
939 bool findNeiborsOnEdge(const _LayerEdge* edge,
940 const SMDS_MeshNode*& n1,
941 const SMDS_MeshNode*& n2,
944 void findSimplexTestEdges( _SolidData& data,
945 vector< vector<_LayerEdge*> >& edgesByGeom);
946 void computeGeomSize( _SolidData& data );
947 bool findShapesToSmooth( _SolidData& data);
948 void limitStepSizeByCurvature( _SolidData& data );
949 void limitStepSize( _SolidData& data,
950 const SMDS_MeshElement* face,
951 const _LayerEdge* maxCosinEdge );
952 void limitStepSize( _SolidData& data, const double minSize);
953 bool inflate(_SolidData& data);
954 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
955 int invalidateBadSmooth( _SolidData& data,
956 SMESH_MesherHelper& helper,
957 vector< _LayerEdge* >& badSmooEdges,
958 vector< _EdgesOnShape* >& eosC1,
960 void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
961 void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
962 vector< _EdgesOnShape* >& eosC1,
963 int smooStep=0, int moveAll=false );
964 void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
965 void findEdgesToUpdateNormalNearConvexFace( _ConvexFace & convFace,
967 SMESH_MesherHelper& helper );
968 void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
969 void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
970 _EdgesOnShape& eos1, _EdgesOnShape& eos2,
971 const bool isSmoothable );
972 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
973 bool updateNormalsOfConvexFaces( _SolidData& data,
974 SMESH_MesherHelper& helper,
976 void updateNormalsOfC1Vertices( _SolidData& data );
977 bool updateNormalsOfSmoothed( _SolidData& data,
978 SMESH_MesherHelper& helper,
980 const double stepSize );
981 bool isNewNormalOk( _SolidData& data,
983 const gp_XYZ& newNormal);
984 bool refine(_SolidData& data);
985 bool shrink(_SolidData& data);
986 bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
987 SMESH_MesherHelper& helper,
988 const SMESHDS_SubMesh* faceSubMesh );
989 void restoreNoShrink( _LayerEdge& edge ) const;
990 void fixBadFaces(const TopoDS_Face& F,
991 SMESH_MesherHelper& helper,
994 set<const SMDS_MeshNode*> * involvedNodes=NULL);
995 bool addBoundaryElements(_SolidData& data);
997 bool error( const string& text, int solidID=-1 );
998 SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
1001 void makeGroupOfLE();
1004 SMESH_ComputeErrorPtr _error;
1006 vector< _SolidData > _sdVec;
1007 TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
1008 TopTools_MapOfShape _shrinkedFaces;
1013 //--------------------------------------------------------------------------------
1015 * \brief Shrinker of nodes on the EDGE
1019 TopoDS_Edge _geomEdge;
1020 vector<double> _initU;
1021 vector<double> _normPar;
1022 vector<const SMDS_MeshNode*> _nodes;
1023 const _LayerEdge* _edges[2];
1026 void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1027 void Compute(bool set3D, SMESH_MesherHelper& helper);
1028 void RestoreParams();
1029 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1030 const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1031 const SMDS_MeshNode* TgtNode( bool is2nd ) const
1032 { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1033 const SMDS_MeshNode* SrcNode( bool is2nd ) const
1034 { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1036 //--------------------------------------------------------------------------------
1038 * \brief Smoother of _LayerEdge's on EDGE.
1042 struct OffPnt // point of the offsetted EDGE
1044 gp_XYZ _xyz; // coord of a point inflated from EDGE w/o smooth
1045 double _len; // length reached at previous inflation step
1046 double _param; // on EDGE
1047 _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1048 gp_XYZ _edgeDir;// EDGE tangent at _param
1049 double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1051 vector< OffPnt > _offPoints;
1052 vector< double > _leParams; // normalized param of _eos._edges on EDGE
1053 Handle(Geom_Curve) _anaCurve; // for analytic smooth
1054 _LayerEdge _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1055 gp_XYZ _edgeDir[2]; // tangent at VERTEXes
1056 size_t _iSeg[2]; // index of segment where extreme tgt node is projected
1057 _EdgesOnShape& _eos;
1058 double _curveLen; // length of the EDGE
1059 std::pair<int,int> _eToSmooth[2]; // <from,to> indices of _LayerEdge's in _eos
1061 static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
1063 SMESH_MesherHelper& helper);
1065 _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1066 _EdgesOnShape& eos )
1067 : _anaCurve( curveForSmooth ), _eos( eos )
1070 bool Perform(_SolidData& data,
1071 Handle(ShapeAnalysis_Surface)& surface,
1072 const TopoDS_Face& F,
1073 SMESH_MesherHelper& helper );
1075 void prepare(_SolidData& data );
1077 void findEdgesToSmooth();
1079 bool isToSmooth( int iE );
1081 bool smoothAnalyticEdge( _SolidData& data,
1082 Handle(ShapeAnalysis_Surface)& surface,
1083 const TopoDS_Face& F,
1084 SMESH_MesherHelper& helper);
1085 bool smoothComplexEdge( _SolidData& data,
1086 Handle(ShapeAnalysis_Surface)& surface,
1087 const TopoDS_Face& F,
1088 SMESH_MesherHelper& helper);
1089 gp_XYZ getNormalNormal( const gp_XYZ & normal,
1090 const gp_XYZ& edgeDir);
1091 _LayerEdge* getLEdgeOnV( bool is2nd )
1093 return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1095 bool isAnalytic() const { return !_anaCurve.IsNull(); }
1097 void offPointsToPython() const; // debug
1099 //--------------------------------------------------------------------------------
1101 * \brief Class of temporary mesh face.
1102 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1103 * needed because SMESH_ElementSearcher internally uses set of elements sorted by ID
1105 struct _TmpMeshFace : public SMDS_PolygonalFaceOfNodes
1107 const SMDS_MeshElement* _srcFace;
1109 _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1112 const SMDS_MeshElement* srcFace=0 ):
1113 SMDS_PolygonalFaceOfNodes(nodes), _srcFace( srcFace ) { setID( ID ); setShapeID( faceID ); }
1114 virtual SMDSAbs_EntityType GetEntityType() const
1115 { return _srcFace ? _srcFace->GetEntityType() : SMDSEntity_Quadrangle; }
1116 virtual SMDSAbs_GeometryType GetGeomType() const
1117 { return _srcFace ? _srcFace->GetGeomType() : SMDSGeom_QUADRANGLE; }
1119 //--------------------------------------------------------------------------------
1121 * \brief Class of temporary mesh quadrangle face storing _LayerEdge it's based on
1123 struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1125 _LayerEdge *_le1, *_le2;
1126 _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1127 _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1129 myNodes[0]=_le1->_nodes[0];
1130 myNodes[1]=_le1->_nodes.back();
1131 myNodes[2]=_le2->_nodes.back();
1132 myNodes[3]=_le2->_nodes[0];
1134 const SMDS_MeshNode* n( size_t i ) const
1136 return myNodes[ i ];
1138 gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1140 SMESH_TNodeXYZ p0s( myNodes[0] );
1141 SMESH_TNodeXYZ p0t( myNodes[1] );
1142 SMESH_TNodeXYZ p1t( myNodes[2] );
1143 SMESH_TNodeXYZ p1s( myNodes[3] );
1144 gp_XYZ v0 = p0t - p0s;
1145 gp_XYZ v1 = p1t - p1s;
1146 gp_XYZ v01 = p1s - p0s;
1147 gp_XYZ n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1152 gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1154 myNodes[0]=le1->_nodes[0];
1155 myNodes[1]=le1->_nodes.back();
1156 myNodes[2]=le2->_nodes.back();
1157 myNodes[3]=le2->_nodes[0];
1161 //--------------------------------------------------------------------------------
1163 * \brief Retriever of node coordinates either directly or from a surface by node UV.
1164 * \warning Location of a surface is ignored
1166 struct _NodeCoordHelper
1168 SMESH_MesherHelper& _helper;
1169 const TopoDS_Face& _face;
1170 Handle(Geom_Surface) _surface;
1171 gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1173 _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1174 : _helper( helper ), _face( F )
1178 TopLoc_Location loc;
1179 _surface = BRep_Tool::Surface( _face, loc );
1181 if ( _surface.IsNull() )
1182 _fun = & _NodeCoordHelper::direct;
1184 _fun = & _NodeCoordHelper::byUV;
1186 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1189 gp_XYZ direct(const SMDS_MeshNode* n) const
1191 return SMESH_TNodeXYZ( n );
1193 gp_XYZ byUV (const SMDS_MeshNode* n) const
1195 gp_XY uv = _helper.GetNodeUV( _face, n );
1196 return _surface->Value( uv.X(), uv.Y() ).XYZ();
1200 //================================================================================
1202 * \brief Check angle between vectors
1204 //================================================================================
1206 inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1208 double dot = v1 * v2; // cos * |v1| * |v2|
1209 double l1 = v1.SquareMagnitude();
1210 double l2 = v2.SquareMagnitude();
1211 return (( dot * cos >= 0 ) &&
1212 ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1215 } // namespace VISCOUS_3D
1219 //================================================================================
1220 // StdMeshers_ViscousLayers hypothesis
1222 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, SMESH_Gen* gen)
1223 :SMESH_Hypothesis(hypId, gen),
1224 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1225 _method( SURF_OFFSET_SMOOTH )
1227 _name = StdMeshers_ViscousLayers::GetHypType();
1228 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1229 } // --------------------------------------------------------------------------------
1230 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1232 if ( faceIds != _shapeIds )
1233 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1234 if ( _isToIgnoreShapes != toIgnore )
1235 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1236 } // --------------------------------------------------------------------------------
1237 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1239 if ( thickness != _thickness )
1240 _thickness = thickness, NotifySubMeshesHypothesisModification();
1241 } // --------------------------------------------------------------------------------
1242 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1244 if ( _nbLayers != nb )
1245 _nbLayers = nb, NotifySubMeshesHypothesisModification();
1246 } // --------------------------------------------------------------------------------
1247 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1249 if ( _stretchFactor != factor )
1250 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1251 } // --------------------------------------------------------------------------------
1252 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1254 if ( _method != method )
1255 _method = method, NotifySubMeshesHypothesisModification();
1256 } // --------------------------------------------------------------------------------
1257 SMESH_ProxyMesh::Ptr
1258 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
1259 const TopoDS_Shape& theShape,
1260 const bool toMakeN2NMap) const
1262 using namespace VISCOUS_3D;
1263 _ViscousBuilder builder;
1264 SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1265 if ( err && !err->IsOK() )
1266 return SMESH_ProxyMesh::Ptr();
1268 vector<SMESH_ProxyMesh::Ptr> components;
1269 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1270 for ( ; exp.More(); exp.Next() )
1272 if ( _MeshOfSolid* pm =
1273 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1275 if ( toMakeN2NMap && !pm->_n2nMapComputed )
1276 if ( !builder.MakeN2NMap( pm ))
1277 return SMESH_ProxyMesh::Ptr();
1278 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1279 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1281 if ( pm->_warning && !pm->_warning->IsOK() )
1283 SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1284 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1285 if ( !smError || smError->IsOK() )
1286 smError = pm->_warning;
1289 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1291 switch ( components.size() )
1295 case 1: return components[0];
1297 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1299 return SMESH_ProxyMesh::Ptr();
1300 } // --------------------------------------------------------------------------------
1301 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1303 save << " " << _nbLayers
1304 << " " << _thickness
1305 << " " << _stretchFactor
1306 << " " << _shapeIds.size();
1307 for ( size_t i = 0; i < _shapeIds.size(); ++i )
1308 save << " " << _shapeIds[i];
1309 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1310 save << " " << _method;
1312 } // --------------------------------------------------------------------------------
1313 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1315 int nbFaces, faceID, shapeToTreat, method;
1316 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1317 while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1318 _shapeIds.push_back( faceID );
1319 if ( load >> shapeToTreat ) {
1320 _isToIgnoreShapes = !shapeToTreat;
1321 if ( load >> method )
1322 _method = (ExtrusionMethod) method;
1325 _isToIgnoreShapes = true; // old behavior
1328 } // --------------------------------------------------------------------------------
1329 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
1330 const TopoDS_Shape& theShape)
1334 } // --------------------------------------------------------------------------------
1335 SMESH_ComputeErrorPtr
1336 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh& theMesh,
1337 const TopoDS_Shape& theShape,
1338 SMESH_Hypothesis::Hypothesis_Status& theStatus)
1340 VISCOUS_3D::_ViscousBuilder builder;
1341 SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1342 if ( err && !err->IsOK() )
1343 theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1345 theStatus = SMESH_Hypothesis::HYP_OK;
1349 // --------------------------------------------------------------------------------
1350 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1353 ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1354 return IsToIgnoreShapes() ? !isIn : isIn;
1356 // END StdMeshers_ViscousLayers hypothesis
1357 //================================================================================
1359 namespace VISCOUS_3D
1361 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1365 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1366 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1367 gp_Pnt p = BRep_Tool::Pnt( fromV );
1368 double distF = p.SquareDistance( c->Value( f ));
1369 double distL = p.SquareDistance( c->Value( l ));
1370 c->D1(( distF < distL ? f : l), p, dir );
1371 if ( distL < distF ) dir.Reverse();
1374 //--------------------------------------------------------------------------------
1375 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1376 SMESH_MesherHelper& helper)
1379 double f,l; gp_Pnt p;
1380 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1381 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1382 double u = helper.GetNodeU( E, atNode );
1386 //--------------------------------------------------------------------------------
1387 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1388 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1390 //--------------------------------------------------------------------------------
1391 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1392 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1395 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1398 TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1399 return getFaceDir( F, v, node, helper, ok );
1401 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1402 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1403 gp_Pnt p; gp_Vec du, dv, norm;
1404 surface->D1( uv.X(),uv.Y(), p, du,dv );
1407 double u = helper.GetNodeU( fromE, node, 0, &ok );
1409 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1410 if ( o == TopAbs_REVERSED )
1413 gp_Vec dir = norm ^ du;
1415 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1416 helper.IsClosedEdge( fromE ))
1418 if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1419 else c->D1( f, p, dv );
1420 if ( o == TopAbs_REVERSED )
1422 gp_Vec dir2 = norm ^ dv;
1423 dir = dir.Normalized() + dir2.Normalized();
1427 //--------------------------------------------------------------------------------
1428 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1429 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1430 bool& ok, double* cosin)
1432 TopoDS_Face faceFrw = F;
1433 faceFrw.Orientation( TopAbs_FORWARD );
1434 //double f,l; TopLoc_Location loc;
1435 TopoDS_Edge edges[2]; // sharing a vertex
1438 TopoDS_Vertex VV[2];
1439 TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1440 for ( ; exp.More() && nbEdges < 2; exp.Next() )
1442 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1443 if ( SMESH_Algo::isDegenerated( e )) continue;
1444 TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1445 if ( VV[1].IsSame( fromV )) {
1446 nbEdges += edges[ 0 ].IsNull();
1449 else if ( VV[0].IsSame( fromV )) {
1450 nbEdges += edges[ 1 ].IsNull();
1455 gp_XYZ dir(0,0,0), edgeDir[2];
1458 // get dirs of edges going fromV
1460 for ( size_t i = 0; i < nbEdges && ok; ++i )
1462 edgeDir[i] = getEdgeDir( edges[i], fromV );
1463 double size2 = edgeDir[i].SquareModulus();
1464 if (( ok = size2 > numeric_limits<double>::min() ))
1465 edgeDir[i] /= sqrt( size2 );
1467 if ( !ok ) return dir;
1469 // get angle between the 2 edges
1471 double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1472 if ( Abs( angle ) < 5 * M_PI/180 )
1474 dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1478 dir = edgeDir[0] + edgeDir[1];
1483 double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1484 *cosin = Cos( angle );
1487 else if ( nbEdges == 1 )
1489 dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1490 if ( cosin ) *cosin = 1.;
1500 //================================================================================
1502 * \brief Finds concave VERTEXes of a FACE
1504 //================================================================================
1506 bool getConcaveVertices( const TopoDS_Face& F,
1507 SMESH_MesherHelper& helper,
1508 set< TGeomID >* vertices = 0)
1510 // check angles at VERTEXes
1512 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1513 for ( size_t iW = 0; iW < wires.size(); ++iW )
1515 const int nbEdges = wires[iW]->NbEdges();
1516 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1518 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1520 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1521 int iE2 = ( iE1 + 1 ) % nbEdges;
1522 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1523 iE2 = ( iE2 + 1 ) % nbEdges;
1524 TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1525 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1526 wires[iW]->Edge( iE2 ), F, V );
1527 if ( angle < -5. * M_PI / 180. )
1531 vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1535 return vertices ? !vertices->empty() : false;
1538 //================================================================================
1540 * \brief Returns true if a FACE is bound by a concave EDGE
1542 //================================================================================
1544 bool isConcave( const TopoDS_Face& F,
1545 SMESH_MesherHelper& helper,
1546 set< TGeomID >* vertices = 0 )
1548 bool isConcv = false;
1549 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1551 gp_Vec2d drv1, drv2;
1553 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1554 for ( ; eExp.More(); eExp.Next() )
1556 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1557 if ( SMESH_Algo::isDegenerated( E )) continue;
1558 // check if 2D curve is concave
1559 BRepAdaptor_Curve2d curve( E, F );
1560 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1561 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1562 curve.Intervals( intervals, GeomAbs_C2 );
1563 bool isConvex = true;
1564 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1566 double u1 = intervals( i );
1567 double u2 = intervals( i+1 );
1568 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1569 double cross = drv1 ^ drv2;
1570 if ( E.Orientation() == TopAbs_REVERSED )
1572 isConvex = ( cross > -1e-9 ); // 0.1 );
1576 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1585 // check angles at VERTEXes
1586 if ( getConcaveVertices( F, helper, vertices ))
1592 //================================================================================
1594 * \brief Computes minimal distance of face in-FACE nodes from an EDGE
1595 * \param [in] face - the mesh face to treat
1596 * \param [in] nodeOnEdge - a node on the EDGE
1597 * \param [out] faceSize - the computed distance
1598 * \return bool - true if faceSize computed
1600 //================================================================================
1602 bool getDistFromEdge( const SMDS_MeshElement* face,
1603 const SMDS_MeshNode* nodeOnEdge,
1606 faceSize = Precision::Infinite();
1609 int nbN = face->NbCornerNodes();
1610 int iOnE = face->GetNodeIndex( nodeOnEdge );
1611 int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1612 SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1613 const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1614 face->GetNode( iNext[1] ) };
1615 gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1616 double segLen = -1.;
1617 // look for two neighbor not in-FACE nodes of face
1618 for ( int i = 0; i < 2; ++i )
1620 if (( nNext[i]->GetPosition()->GetDim() != 2 ) &&
1621 ( nodeOnEdge->GetPosition()->GetDim() == 0 || nNext[i]->GetID() < nodeOnEdge->GetID() ))
1623 // look for an in-FACE node
1624 for ( int iN = 0; iN < nbN; ++iN )
1626 if ( iN == iOnE || iN == iNext[i] )
1628 SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1629 gp_XYZ v = pInFace - segEnd;
1632 segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1633 segLen = segVec.Modulus();
1635 double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1636 faceSize = Min( faceSize, distToSeg );
1644 //================================================================================
1646 * \brief Return direction of axis or revolution of a surface
1648 //================================================================================
1650 bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1653 switch ( surface.GetType() ) {
1656 gp_Cone cone = surface.Cone();
1657 axis = cone.Axis().Direction();
1660 case GeomAbs_Sphere:
1662 gp_Sphere sphere = surface.Sphere();
1663 axis = sphere.Position().Direction();
1666 case GeomAbs_SurfaceOfRevolution:
1668 axis = surface.AxeOfRevolution().Direction();
1671 //case GeomAbs_SurfaceOfExtrusion:
1672 case GeomAbs_OffsetSurface:
1674 Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1675 return getRovolutionAxis( base->Surface(), axis );
1677 default: return false;
1682 //--------------------------------------------------------------------------------
1683 // DEBUG. Dump intermediate node positions into a python script
1684 // HOWTO use: run python commands written in a console to see
1685 // construction steps of viscous layers
1691 PyDump(SMESH_Mesh& m) {
1692 int tag = 3 + m.GetId();
1693 const char* fname = "/tmp/viscous.py";
1694 cout << "execfile('"<<fname<<"')"<<endl;
1695 py = _pyStream = new ofstream(fname);
1696 *py << "import SMESH" << endl
1697 << "from salome.smesh import smeshBuilder" << endl
1698 << "smesh = smeshBuilder.New()" << endl
1699 << "meshSO = salome.myStudy.FindObjectID('0:1:2:" << tag <<"')" << endl
1700 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
1705 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1706 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1707 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1708 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1712 ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1713 struct MyStream : public ostream
1715 template <class T> ostream & operator<<( const T &anything ) { return *this ; }
1717 void Pause() { py = &_mystream; }
1718 void Resume() { py = _pyStream; }
1722 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1723 #define dumpMove(n) { _dumpMove(n, __LINE__);}
1724 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1725 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
1726 void _dumpFunction(const string& fun, int ln)
1727 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1728 void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1729 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1730 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1731 void _dumpCmd(const string& txt, int ln)
1732 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
1733 void dumpFunctionEnd()
1734 { if (py) *py<< " return"<< endl; }
1735 void dumpChangeNodes( const SMDS_MeshElement* f )
1736 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
1737 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1738 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1739 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1743 struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} void Pause() {} void Resume() {} };
1744 #define dumpFunction(f) f
1746 #define dumpMoveComm(n,txt)
1747 #define dumpCmd(txt)
1748 #define dumpFunctionEnd()
1749 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1750 #define debugMsg( txt ) {}
1755 using namespace VISCOUS_3D;
1757 //================================================================================
1759 * \brief Constructor of _ViscousBuilder
1761 //================================================================================
1763 _ViscousBuilder::_ViscousBuilder()
1765 _error = SMESH_ComputeError::New(COMPERR_OK);
1769 //================================================================================
1771 * \brief Stores error description and returns false
1773 //================================================================================
1775 bool _ViscousBuilder::error(const string& text, int solidId )
1777 const string prefix = string("Viscous layers builder: ");
1778 _error->myName = COMPERR_ALGO_FAILED;
1779 _error->myComment = prefix + text;
1782 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1783 if ( !sm && !_sdVec.empty() )
1784 sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1785 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1787 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1788 if ( smError && smError->myAlgo )
1789 _error->myAlgo = smError->myAlgo;
1791 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1793 // set KO to all solids
1794 for ( size_t i = 0; i < _sdVec.size(); ++i )
1796 if ( _sdVec[i]._index == solidId )
1798 sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1799 if ( !sm->IsEmpty() )
1801 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1802 if ( !smError || smError->IsOK() )
1804 smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1805 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1809 makeGroupOfLE(); // debug
1814 //================================================================================
1816 * \brief At study restoration, restore event listeners used to clear an inferior
1817 * dim sub-mesh modified by viscous layers
1819 //================================================================================
1821 void _ViscousBuilder::RestoreListeners()
1826 //================================================================================
1828 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1830 //================================================================================
1832 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1834 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1835 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1836 for ( ; fExp.More(); fExp.Next() )
1838 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1839 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1841 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1843 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1846 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1847 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1849 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1850 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1851 while( prxIt->more() )
1853 const SMDS_MeshElement* fSrc = srcIt->next();
1854 const SMDS_MeshElement* fPrx = prxIt->next();
1855 if ( fSrc->NbNodes() != fPrx->NbNodes())
1856 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1857 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1858 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1861 pm->_n2nMapComputed = true;
1865 //================================================================================
1867 * \brief Does its job
1869 //================================================================================
1871 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1872 const TopoDS_Shape& theShape)
1876 // check if proxy mesh already computed
1877 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1879 return error("No SOLID's in theShape"), _error;
1881 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1882 return SMESH_ComputeErrorPtr(); // everything already computed
1884 PyDump debugDump( theMesh );
1885 _pyDump = &debugDump;
1887 // TODO: ignore already computed SOLIDs
1888 if ( !findSolidsWithLayers())
1891 if ( !findFacesWithLayers() )
1894 for ( size_t i = 0; i < _sdVec.size(); ++i )
1897 for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1898 if ( _sdVec[iSD]._before.IsEmpty() &&
1899 !_sdVec[iSD]._solid.IsNull() &&
1900 _sdVec[iSD]._n2eMap.empty() )
1903 if ( ! makeLayer(_sdVec[iSD]) ) // create _LayerEdge's
1906 if ( _sdVec[iSD]._n2eMap.size() == 0 ) // no layers in a SOLID
1908 _sdVec[iSD]._solid.Nullify();
1912 if ( ! inflate(_sdVec[iSD]) ) // increase length of _LayerEdge's
1915 if ( ! refine(_sdVec[iSD]) ) // create nodes and prisms
1918 if ( ! shrink(_sdVec[iSD]) ) // shrink 2D mesh on FACEs w/o layer
1921 addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
1923 const TopoDS_Shape& solid = _sdVec[iSD]._solid;
1924 for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1925 _sdVec[iSD]._before.Remove( solid );
1928 makeGroupOfLE(); // debug
1934 //================================================================================
1936 * \brief Check validity of hypotheses
1938 //================================================================================
1940 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh& mesh,
1941 const TopoDS_Shape& shape )
1945 if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1946 return SMESH_ComputeErrorPtr(); // everything already computed
1949 findSolidsWithLayers();
1950 bool ok = findFacesWithLayers( true );
1952 // remove _MeshOfSolid's of _SolidData's
1953 for ( size_t i = 0; i < _sdVec.size(); ++i )
1954 _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1959 return SMESH_ComputeErrorPtr();
1962 //================================================================================
1964 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1966 //================================================================================
1968 bool _ViscousBuilder::findSolidsWithLayers()
1971 TopTools_IndexedMapOfShape allSolids;
1972 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1973 _sdVec.reserve( allSolids.Extent());
1975 SMESH_HypoFilter filter;
1976 for ( int i = 1; i <= allSolids.Extent(); ++i )
1978 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1979 SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
1980 if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
1981 continue; // solid is already meshed
1982 SMESH_Algo* algo = sm->GetAlgo();
1983 if ( !algo ) continue;
1984 // TODO: check if algo is hidden
1985 const list <const SMESHDS_Hypothesis *> & allHyps =
1986 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1987 _SolidData* soData = 0;
1988 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1989 const StdMeshers_ViscousLayers* viscHyp = 0;
1990 for ( ; hyp != allHyps.end(); ++hyp )
1991 if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1993 TopoDS_Shape hypShape;
1994 filter.Init( filter.Is( viscHyp ));
1995 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1999 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
2002 _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
2003 soData = & _sdVec.back();
2004 soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
2005 soData->_helper = new SMESH_MesherHelper( *_mesh );
2006 soData->_helper->SetSubShape( allSolids(i) );
2007 _solids.Add( allSolids(i) );
2009 soData->_hyps.push_back( viscHyp );
2010 soData->_hypShapes.push_back( hypShape );
2013 if ( _sdVec.empty() )
2015 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
2020 //================================================================================
2022 * \brief Set a _SolidData to be computed before another
2024 //================================================================================
2026 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
2028 // check possibility to set this order; get all solids before solidBefore
2029 TopTools_IndexedMapOfShape allSolidsBefore;
2030 allSolidsBefore.Add( solidBefore._solid );
2031 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2033 int iSD = _solids.FindIndex( allSolidsBefore(i) );
2036 TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2037 for ( ; soIt.More(); soIt.Next() )
2038 allSolidsBefore.Add( soIt.Value() );
2041 if ( allSolidsBefore.Contains( solidAfter._solid ))
2044 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2045 solidAfter._before.Add( allSolidsBefore(i) );
2050 //================================================================================
2054 //================================================================================
2056 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2058 SMESH_MesherHelper helper( *_mesh );
2059 TopExp_Explorer exp;
2061 // collect all faces-to-ignore defined by hyp
2062 for ( size_t i = 0; i < _sdVec.size(); ++i )
2064 // get faces-to-ignore defined by each hyp
2065 typedef const StdMeshers_ViscousLayers* THyp;
2066 typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2067 list< TFacesOfHyp > ignoreFacesOfHyps;
2068 list< THyp >::iterator hyp = _sdVec[i]._hyps.begin();
2069 list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2070 for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2072 ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2073 getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2076 // fill _SolidData::_face2hyp and check compatibility of hypotheses
2077 const int nbHyps = _sdVec[i]._hyps.size();
2080 // check if two hypotheses define different parameters for the same FACE
2081 list< TFacesOfHyp >::iterator igFacesOfHyp;
2082 for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2084 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2086 igFacesOfHyp = ignoreFacesOfHyps.begin();
2087 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2088 if ( ! igFacesOfHyp->first.count( faceID ))
2091 return error(SMESH_Comment("Several hypotheses define "
2092 "Viscous Layers on the face #") << faceID );
2093 hyp = igFacesOfHyp->second;
2096 _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2098 _sdVec[i]._ignoreFaceIds.insert( faceID );
2101 // check if two hypotheses define different number of viscous layers for
2102 // adjacent faces of a solid
2103 set< int > nbLayersSet;
2104 igFacesOfHyp = ignoreFacesOfHyps.begin();
2105 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2107 nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2109 if ( nbLayersSet.size() > 1 )
2111 for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2113 PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2114 THyp hyp1 = 0, hyp2 = 0;
2115 while( const TopoDS_Shape* face = fIt->next() )
2117 const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2118 map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2119 if ( f2h != _sdVec[i]._face2hyp.end() )
2121 ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2124 if ( hyp1 && hyp2 &&
2125 hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2127 return error("Two hypotheses define different number of "
2128 "viscous layers on adjacent faces");
2132 } // if ( nbHyps > 1 )
2135 _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2139 if ( onlyWith ) // is called to check hypotheses compatibility only
2142 // fill _SolidData::_reversedFaceIds
2143 for ( size_t i = 0; i < _sdVec.size(); ++i )
2145 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2146 for ( ; exp.More(); exp.Next() )
2148 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2149 const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2150 if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2151 helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2152 helper.IsReversedSubMesh( face ))
2154 _sdVec[i]._reversedFaceIds.insert( faceID );
2159 // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2160 TopTools_IndexedMapOfShape shapes;
2161 std::string structAlgoName = "Hexa_3D";
2162 for ( size_t i = 0; i < _sdVec.size(); ++i )
2165 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2166 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2168 const TopoDS_Shape& edge = shapes(iE);
2169 // find 2 FACEs sharing an EDGE
2171 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2172 while ( fIt->more())
2174 const TopoDS_Shape* f = fIt->next();
2175 FF[ int( !FF[0].IsNull()) ] = *f;
2177 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2179 // check presence of layers on them
2181 for ( int j = 0; j < 2; ++j )
2182 ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2183 if ( ignore[0] == ignore[1] )
2184 continue; // nothing interesting
2185 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2188 if ( !fWOL.IsNull())
2190 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2191 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2196 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2198 for ( size_t i = 0; i < _sdVec.size(); ++i )
2201 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2202 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2204 const TopoDS_Shape& vertex = shapes(iV);
2205 // find faces WOL sharing the vertex
2206 vector< TopoDS_Shape > facesWOL;
2207 size_t totalNbFaces = 0;
2208 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2209 while ( fIt->more())
2211 const TopoDS_Shape* f = fIt->next();
2213 const int fID = getMeshDS()->ShapeToIndex( *f );
2214 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2215 facesWOL.push_back( *f );
2217 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2218 continue; // no layers at this vertex or no WOL
2219 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2220 switch ( facesWOL.size() )
2224 helper.SetSubShape( facesWOL[0] );
2225 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2227 TopoDS_Shape seamEdge;
2228 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2229 while ( eIt->more() && seamEdge.IsNull() )
2231 const TopoDS_Shape* e = eIt->next();
2232 if ( helper.IsRealSeam( *e ) )
2235 if ( !seamEdge.IsNull() )
2237 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2241 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2246 // find an edge shared by 2 faces
2247 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2248 while ( eIt->more())
2250 const TopoDS_Shape* e = eIt->next();
2251 if ( helper.IsSubShape( *e, facesWOL[0]) &&
2252 helper.IsSubShape( *e, facesWOL[1]))
2254 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2260 return error("Not yet supported case", _sdVec[i]._index);
2265 // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrinked since
2266 // the algo of the SOLID sharing the FACE does not support it or for other reasons
2267 set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2268 for ( size_t i = 0; i < _sdVec.size(); ++i )
2270 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2271 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2273 const TopoDS_Shape& fWOL = e2f->second;
2274 const TGeomID edgeID = e2f->first;
2275 TGeomID faceID = getMeshDS()->ShapeToIndex( fWOL );
2276 TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2277 if ( edge.ShapeType() != TopAbs_EDGE )
2278 continue; // shrink shape is VERTEX
2281 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2282 while ( soIt->more() && solid.IsNull() )
2284 const TopoDS_Shape* so = soIt->next();
2285 if ( !so->IsSame( _sdVec[i]._solid ))
2288 if ( solid.IsNull() )
2291 bool noShrinkE = false;
2292 SMESH_Algo* algo = _mesh->GetSubMesh( solid )->GetAlgo();
2293 bool isStructured = ( algo && algo->GetName() == structAlgoName );
2294 size_t iSolid = _solids.FindIndex( solid ) - 1;
2295 if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2297 // the adjacent SOLID has NO layers on fWOL;
2298 // shrink allowed if
2299 // - there are layers on the EDGE in the adjacent SOLID
2300 // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2301 bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2302 bool shrinkAllowed = (( hasWLAdj ) ||
2303 ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2304 noShrinkE = !shrinkAllowed;
2306 else if ( iSolid < _sdVec.size() )
2308 // the adjacent SOLID has layers on fWOL;
2309 // check if SOLID's mesh is unstructured and then try to set it
2310 // to be computed after the i-th solid
2311 if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2312 noShrinkE = true; // don't shrink fWOL
2316 // the adjacent SOLID has NO layers at all
2317 noShrinkE = isStructured;
2322 _sdVec[i]._noShrinkShapes.insert( edgeID );
2324 // check if there is a collision with to-shrink-from EDGEs in iSolid
2325 // if ( iSolid < _sdVec.size() )
2328 // TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2329 // for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2331 // const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2332 // const TGeomID eID = getMeshDS()->ShapeToIndex( E );
2333 // if ( eID == edgeID ||
2334 // !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2335 // _sdVec[i]._noShrinkShapes.count( eID ))
2337 // for ( int is1st = 0; is1st < 2; ++is1st )
2339 // TopoDS_Vertex V = helper.IthVertex( is1st, E );
2340 // if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2342 // return error("No way to make a conformal mesh with "
2343 // "the given set of faces with layers", _sdVec[i]._index);
2350 // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2351 // _shrinkShape2Shape is different in the adjacent SOLID
2352 for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2354 TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2355 bool noShrinkV = false, noShrinkIfAdjMeshed = false;
2357 if ( iSolid < _sdVec.size() )
2359 if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2361 map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2362 i2S = _sdVec[i ]._shrinkShape2Shape.find( vID );
2363 i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2364 if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2365 noShrinkV = (( isStructured ) ||
2366 ( noShrinkIfAdjMeshed = i2S->second.ShapeType() == TopAbs_EDGE ));
2368 noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2372 noShrinkV = noShrinkE;
2377 // the adjacent SOLID has NO layers at all
2384 noShrinkV = noShrinkIfAdjMeshed =
2385 ( _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2389 if ( noShrinkV && noShrinkIfAdjMeshed )
2391 // noShrinkV if FACEs in the adjacent SOLID are meshed
2392 PShapeIteratorPtr fIt = helper.GetAncestors( _sdVec[i]._shrinkShape2Shape[ vID ],
2393 *_mesh, TopAbs_FACE, &solid );
2394 while ( fIt->more() )
2396 const TopoDS_Shape* f = fIt->next();
2397 if ( !f->IsSame( fWOL ))
2399 noShrinkV = ! _mesh->GetSubMesh( *f )->IsEmpty();
2405 _sdVec[i]._noShrinkShapes.insert( vID );
2408 } // loop on _sdVec[i]._shrinkShape2Shape
2409 } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2412 // add FACEs of other SOLIDs to _ignoreFaceIds
2413 for ( size_t i = 0; i < _sdVec.size(); ++i )
2416 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2418 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2420 if ( !shapes.Contains( exp.Current() ))
2421 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2428 //================================================================================
2430 * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2432 //================================================================================
2434 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape& solid,
2435 const StdMeshers_ViscousLayers* hyp,
2436 const TopoDS_Shape& hypShape,
2437 set<TGeomID>& ignoreFaceIds)
2439 TopExp_Explorer exp;
2441 vector<TGeomID> ids = hyp->GetBndShapes();
2442 if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2444 for ( size_t ii = 0; ii < ids.size(); ++ii )
2446 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2447 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2448 ignoreFaceIds.insert( ids[ii] );
2451 else // FACEs with layers are given
2453 exp.Init( solid, TopAbs_FACE );
2454 for ( ; exp.More(); exp.Next() )
2456 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2457 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2458 ignoreFaceIds.insert( faceInd );
2462 // ignore internal FACEs if inlets and outlets are specified
2463 if ( hyp->IsToIgnoreShapes() )
2465 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2466 TopExp::MapShapesAndAncestors( hypShape,
2467 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2469 for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2471 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2472 if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2475 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2477 ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2482 //================================================================================
2484 * \brief Create the inner surface of the viscous layer and prepare data for infation
2486 //================================================================================
2488 bool _ViscousBuilder::makeLayer(_SolidData& data)
2490 // get all sub-shapes to make layers on
2491 set<TGeomID> subIds, faceIds;
2492 subIds = data._noShrinkShapes;
2493 TopExp_Explorer exp( data._solid, TopAbs_FACE );
2494 for ( ; exp.More(); exp.Next() )
2496 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2497 if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2498 faceIds.insert( fSubM->GetId() );
2501 // make a map to find new nodes on sub-shapes shared with other SOLID
2502 map< TGeomID, TNode2Edge* >::iterator s2ne;
2503 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2504 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2506 TGeomID shapeInd = s2s->first;
2507 for ( size_t i = 0; i < _sdVec.size(); ++i )
2509 if ( _sdVec[i]._index == data._index ) continue;
2510 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2511 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2512 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2514 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2520 // Create temporary faces and _LayerEdge's
2522 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2524 data._stepSize = Precision::Infinite();
2525 data._stepSizeNodes[0] = 0;
2527 SMESH_MesherHelper helper( *_mesh );
2528 helper.SetSubShape( data._solid );
2529 helper.SetElementsOnShape( true );
2531 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2532 TNode2Edge::iterator n2e2;
2534 // collect _LayerEdge's of shapes they are based on
2535 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2536 const int nbShapes = getMeshDS()->MaxShapeIndex();
2537 edgesByGeom.resize( nbShapes+1 );
2539 // set data of _EdgesOnShape's
2540 if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2542 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2543 while ( smIt->more() )
2546 if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2547 !faceIds.count( sm->GetId() ))
2549 setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2552 // make _LayerEdge's
2553 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2555 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2556 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2557 SMESH_ProxyMesh::SubMesh* proxySub =
2558 data._proxyMesh->getFaceSubM( F, /*create=*/true);
2560 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2561 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2563 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2564 while ( eIt->more() )
2566 const SMDS_MeshElement* face = eIt->next();
2567 double faceMaxCosin = -1;
2568 _LayerEdge* maxCosinEdge = 0;
2569 int nbDegenNodes = 0;
2571 newNodes.resize( face->NbCornerNodes() );
2572 for ( size_t i = 0 ; i < newNodes.size(); ++i )
2574 const SMDS_MeshNode* n = face->GetNode( i );
2575 const int shapeID = n->getshapeId();
2576 const bool onDegenShap = helper.IsDegenShape( shapeID );
2577 const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2582 // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2583 const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2584 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2585 if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2595 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2596 if ( !(*n2e).second )
2599 _LayerEdge* edge = new _LayerEdge();
2600 edge->_nodes.push_back( n );
2602 edgesByGeom[ shapeID ]._edges.push_back( edge );
2603 const bool noShrink = data._noShrinkShapes.count( shapeID );
2605 SMESH_TNodeXYZ xyz( n );
2607 // set edge data or find already refined _LayerEdge and get data from it
2608 if (( !noShrink ) &&
2609 ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE ) &&
2610 (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2611 (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end() ))
2613 _LayerEdge* foundEdge = (*n2e2).second;
2614 gp_XYZ lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2615 foundEdge->_pos.push_back( lastPos );
2616 // location of the last node is modified and we restore it by foundEdge->_pos.back()
2617 const_cast< SMDS_MeshNode* >
2618 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2624 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2626 if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2629 if ( edge->_nodes.size() < 2 )
2630 edge->Block( data );
2631 //data._noShrinkShapes.insert( shapeID );
2633 dumpMove(edge->_nodes.back());
2635 if ( edge->_cosin > faceMaxCosin )
2637 faceMaxCosin = edge->_cosin;
2638 maxCosinEdge = edge;
2641 newNodes[ i ] = n2e->second->_nodes.back();
2644 data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2646 if ( newNodes.size() - nbDegenNodes < 2 )
2649 // create a temporary face
2650 const SMDS_MeshElement* newFace =
2651 new _TmpMeshFace( newNodes, --_tmpFaceID, face->GetShapeID(), face );
2652 proxySub->AddElement( newFace );
2654 // compute inflation step size by min size of element on a convex surface
2655 if ( faceMaxCosin > theMinSmoothCosin )
2656 limitStepSize( data, face, maxCosinEdge );
2658 } // loop on 2D elements on a FACE
2659 } // loop on FACEs of a SOLID to create _LayerEdge's
2662 // Set _LayerEdge::_neibors
2663 TNode2Edge::iterator n2e;
2664 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2666 _EdgesOnShape& eos = data._edgesOnShape[iS];
2667 for ( size_t i = 0; i < eos._edges.size(); ++i )
2669 _LayerEdge* edge = eos._edges[i];
2670 TIDSortedNodeSet nearNodes;
2671 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2672 while ( fIt->more() )
2674 const SMDS_MeshElement* f = fIt->next();
2675 if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2676 nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2678 nearNodes.erase( edge->_nodes[0] );
2679 edge->_neibors.reserve( nearNodes.size() );
2680 TIDSortedNodeSet::iterator node = nearNodes.begin();
2681 for ( ; node != nearNodes.end(); ++node )
2682 if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2683 edge->_neibors.push_back( n2e->second );
2687 data._epsilon = 1e-7;
2688 if ( data._stepSize < 1. )
2689 data._epsilon *= data._stepSize;
2691 if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2694 // limit data._stepSize depending on surface curvature and fill data._convexFaces
2695 limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2697 // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2698 const SMDS_MeshNode* nn[2];
2699 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2701 _EdgesOnShape& eos = data._edgesOnShape[iS];
2702 for ( size_t i = 0; i < eos._edges.size(); ++i )
2704 _LayerEdge* edge = eos._edges[i];
2705 if ( edge->IsOnEdge() )
2707 // get neighbor nodes
2708 bool hasData = ( edge->_2neibors->_edges[0] );
2709 if ( hasData ) // _LayerEdge is a copy of another one
2711 nn[0] = edge->_2neibors->srcNode(0);
2712 nn[1] = edge->_2neibors->srcNode(1);
2714 else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2718 // set neighbor _LayerEdge's
2719 for ( int j = 0; j < 2; ++j )
2721 if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2722 return error("_LayerEdge not found by src node", data._index);
2723 edge->_2neibors->_edges[j] = n2e->second;
2726 edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2729 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2731 _Simplex& s = edge->_simplices[j];
2732 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2733 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2736 // For an _LayerEdge on a degenerated EDGE, copy some data from
2737 // a corresponding _LayerEdge on a VERTEX
2738 // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2739 if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2741 // Generally we should not get here
2742 if ( eos.ShapeType() != TopAbs_EDGE )
2744 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2745 const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2746 if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2748 const _LayerEdge* vEdge = n2e->second;
2749 edge->_normal = vEdge->_normal;
2750 edge->_lenFactor = vEdge->_lenFactor;
2751 edge->_cosin = vEdge->_cosin;
2754 } // loop on data._edgesOnShape._edges
2755 } // loop on data._edgesOnShape
2757 // fix _LayerEdge::_2neibors on EDGEs to smooth
2758 // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2759 // for ( ; e2c != data._edge2curve.end(); ++e2c )
2760 // if ( !e2c->second.IsNull() )
2762 // if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2763 // data.Sort2NeiborsOnEdge( eos->_edges );
2770 //================================================================================
2772 * \brief Compute inflation step size by min size of element on a convex surface
2774 //================================================================================
2776 void _ViscousBuilder::limitStepSize( _SolidData& data,
2777 const SMDS_MeshElement* face,
2778 const _LayerEdge* maxCosinEdge )
2781 double minSize = 10 * data._stepSize;
2782 const int nbNodes = face->NbCornerNodes();
2783 for ( int i = 0; i < nbNodes; ++i )
2785 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2786 const SMDS_MeshNode* curN = face->GetNode( i );
2787 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2788 curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2790 double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2791 if ( dist < minSize )
2792 minSize = dist, iN = i;
2795 double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2796 if ( newStep < data._stepSize )
2798 data._stepSize = newStep;
2799 data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2800 data._stepSizeNodes[0] = face->GetNode( iN );
2801 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2805 //================================================================================
2807 * \brief Compute inflation step size by min size of element on a convex surface
2809 //================================================================================
2811 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2813 if ( minSize < data._stepSize )
2815 data._stepSize = minSize;
2816 if ( data._stepSizeNodes[0] )
2819 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2820 data._stepSizeCoeff = data._stepSize / dist;
2825 //================================================================================
2827 * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2829 //================================================================================
2831 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2833 SMESH_MesherHelper helper( *_mesh );
2835 BRepLProp_SLProps surfProp( 2, 1e-6 );
2836 data._convexFaces.clear();
2838 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2840 _EdgesOnShape& eof = data._edgesOnShape[iS];
2841 if ( eof.ShapeType() != TopAbs_FACE ||
2842 data._ignoreFaceIds.count( eof._shapeID ))
2845 TopoDS_Face F = TopoDS::Face( eof._shape );
2846 const TGeomID faceID = eof._shapeID;
2848 BRepAdaptor_Surface surface( F, false );
2849 surfProp.SetSurface( surface );
2851 _ConvexFace cnvFace;
2853 cnvFace._normalsFixed = false;
2854 cnvFace._isTooCurved = false;
2856 double maxCurvature = cnvFace.GetMaxCurvature( data, eof, surfProp, helper );
2857 if ( maxCurvature > 0 )
2859 limitStepSize( data, 0.9 / maxCurvature );
2860 findEdgesToUpdateNormalNearConvexFace( cnvFace, data, helper );
2862 if ( !cnvFace._isTooCurved ) continue;
2864 _ConvexFace & convFace =
2865 data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2867 // skip a closed surface (data._convexFaces is useful anyway)
2868 bool isClosedF = false;
2869 helper.SetSubShape( F );
2870 if ( helper.HasRealSeam() )
2872 // in the closed surface there must be a closed EDGE
2873 for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2874 isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2878 // limit _LayerEdge::_maxLen on the FACE
2879 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2880 const double minCurvature =
2881 1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2882 map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2883 if ( id2eos != cnvFace._subIdToEOS.end() )
2885 _EdgesOnShape& eos = * id2eos->second;
2886 for ( size_t i = 0; i < eos._edges.size(); ++i )
2888 _LayerEdge* ledge = eos._edges[ i ];
2889 gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2890 surfProp.SetParameters( uv.X(), uv.Y() );
2891 if ( surfProp.IsCurvatureDefined() )
2893 double curvature = Max( surfProp.MaxCurvature() * oriFactor,
2894 surfProp.MinCurvature() * oriFactor );
2895 if ( curvature > minCurvature )
2896 ledge->SetMaxLen( Min( ledge->_maxLen, 1. / curvature ));
2903 // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2904 // prism distortion.
2905 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2906 if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2908 // there are _LayerEdge's on the FACE it-self;
2909 // select _LayerEdge's near EDGEs
2910 _EdgesOnShape& eos = * id2eos->second;
2911 for ( size_t i = 0; i < eos._edges.size(); ++i )
2913 _LayerEdge* ledge = eos._edges[ i ];
2914 for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2915 if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2917 // do not select _LayerEdge's neighboring sharp EDGEs
2918 bool sharpNbr = false;
2919 for ( size_t iN = 0; iN < ledge->_neibors.size() && !sharpNbr; ++iN )
2920 sharpNbr = ( ledge->_neibors[iN]->_cosin > theMinSmoothCosin );
2922 convFace._simplexTestEdges.push_back( ledge );
2929 // where there are no _LayerEdge's on a _ConvexFace,
2930 // as e.g. on a fillet surface with no internal nodes - issue 22580,
2931 // so that collision of viscous internal faces is not detected by check of
2932 // intersection of _LayerEdge's with the viscous internal faces.
2934 set< const SMDS_MeshNode* > usedNodes;
2936 // look for _LayerEdge's with null _sWOL
2937 id2eos = convFace._subIdToEOS.begin();
2938 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2940 _EdgesOnShape& eos = * id2eos->second;
2941 if ( !eos._sWOL.IsNull() )
2943 for ( size_t i = 0; i < eos._edges.size(); ++i )
2945 _LayerEdge* ledge = eos._edges[ i ];
2946 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2947 if ( !usedNodes.insert( srcNode ).second ) continue;
2949 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2951 usedNodes.insert( ledge->_simplices[i]._nPrev );
2952 usedNodes.insert( ledge->_simplices[i]._nNext );
2954 convFace._simplexTestEdges.push_back( ledge );
2958 } // loop on FACEs of data._solid
2961 //================================================================================
2963 * \brief Detect shapes (and _LayerEdge's on them) to smooth
2965 //================================================================================
2967 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2969 // define allowed thickness
2970 computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2973 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2974 // boundary inclined to the shape at a sharp angle
2976 TopTools_MapOfShape edgesOfSmooFaces;
2977 SMESH_MesherHelper helper( *_mesh );
2980 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2981 data._nbShapesToSmooth = 0;
2983 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2985 _EdgesOnShape& eos = edgesByGeom[iS];
2986 eos._toSmooth = false;
2987 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2990 double tgtThick = eos._hyp.GetTotalThickness();
2991 SMESH_subMeshIteratorPtr subIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false );
2992 while ( subIt->more() && !eos._toSmooth )
2994 TGeomID iSub = subIt->next()->GetId();
2995 const vector<_LayerEdge*>& eSub = edgesByGeom[ iSub ]._edges;
2996 if ( eSub.empty() ) continue;
2999 for ( size_t i = 0; i < eSub.size() && !eos._toSmooth; ++i )
3000 if ( eSub[i]->_cosin > theMinSmoothCosin )
3002 SMDS_ElemIteratorPtr fIt = eSub[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3003 while ( fIt->more() && !eos._toSmooth )
3005 const SMDS_MeshElement* face = fIt->next();
3006 if ( face->getshapeId() == eos._shapeID &&
3007 getDistFromEdge( face, eSub[i]->_nodes[0], faceSize ))
3009 eos._toSmooth = needSmoothing( eSub[i]->_cosin,
3010 tgtThick * eSub[i]->_lenFactor,
3016 if ( eos._toSmooth )
3018 for ( TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
3019 edgesOfSmooFaces.Add( eExp.Current() );
3021 data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3023 data._nbShapesToSmooth += eos._toSmooth;
3027 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3029 _EdgesOnShape& eos = edgesByGeom[iS];
3030 eos._edgeSmoother = NULL;
3031 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3032 if ( !eos._hyp.ToSmooth() ) continue;
3034 const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3035 if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3038 double tgtThick = eos._hyp.GetTotalThickness();
3039 for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3041 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3042 vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3043 if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3044 gp_Vec eDir = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
3045 double angle = eDir.Angle( eV[0]->_normal );
3046 double cosin = Cos( angle );
3047 double cosinAbs = Abs( cosin );
3048 if ( cosinAbs > theMinSmoothCosin )
3050 // always smooth analytic EDGEs
3051 Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3052 eos._toSmooth = ! curve.IsNull();
3054 // compare tgtThick with the length of an end segment
3055 SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3056 while ( eIt->more() && !eos._toSmooth )
3058 const SMDS_MeshElement* endSeg = eIt->next();
3059 if ( endSeg->getshapeId() == (int) iS )
3062 SMESH_TNodeXYZ( endSeg->GetNode( 0 )).Distance( endSeg->GetNode( 1 ));
3063 eos._toSmooth = needSmoothing( cosinAbs, tgtThick * eV[0]->_lenFactor, segLen );
3066 if ( eos._toSmooth )
3068 eos._edgeSmoother = new _Smoother1D( curve, eos );
3070 // for ( size_t i = 0; i < eos._edges.size(); ++i )
3071 // eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3075 data._nbShapesToSmooth += eos._toSmooth;
3079 // Reset _cosin if no smooth is allowed by the user
3080 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3082 _EdgesOnShape& eos = edgesByGeom[iS];
3083 if ( eos._edges.empty() ) continue;
3085 if ( !eos._hyp.ToSmooth() )
3086 for ( size_t i = 0; i < eos._edges.size(); ++i )
3087 //eos._edges[i]->SetCosin( 0 ); // keep _cosin to use in limitMaxLenByCurvature()
3088 eos._edges[i]->_lenFactor = 1;
3092 // Fill _eosC1 to make that C1 FACEs and EDGEs between them to be smoothed as a whole
3094 TopTools_MapOfShape c1VV;
3096 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3098 _EdgesOnShape& eos = edgesByGeom[iS];
3099 if ( eos._edges.empty() ||
3100 eos.ShapeType() != TopAbs_FACE ||
3104 // check EDGEs of a FACE
3105 TopTools_MapOfShape checkedEE, allVV;
3106 list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3107 while ( !smQueue.empty() )
3109 SMESH_subMesh* sm = smQueue.front();
3110 smQueue.pop_front();
3111 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3112 while ( smIt->more() )
3115 if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3116 allVV.Add( sm->GetSubShape() );
3117 if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3118 !checkedEE.Add( sm->GetSubShape() ))
3121 _EdgesOnShape* eoe = data.GetShapeEdges( sm->GetId() );
3122 vector<_LayerEdge*>& eE = eoe->_edges;
3123 if ( eE.empty() || !eoe->_sWOL.IsNull() )
3126 bool isC1 = true; // check continuity along an EDGE
3127 for ( size_t i = 0; i < eE.size() && isC1; ++i )
3128 isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3132 // check that mesh faces are C1 as well
3134 gp_XYZ norm1, norm2;
3135 const SMDS_MeshNode* n = eE[ eE.size() / 2 ]->_nodes[0];
3136 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3137 if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3139 while ( fIt->more() && isC1 )
3140 isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3141 Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3146 // add the EDGE and an adjacent FACE to _eosC1
3147 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3148 while ( const TopoDS_Shape* face = fIt->next() )
3150 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3151 if ( !eof ) continue; // other solid
3152 if ( eos._shapeID == eof->_shapeID ) continue;
3153 if ( !eos.HasC1( eof ))
3156 eos._eosC1.push_back( eof );
3157 eof->_toSmooth = false;
3158 data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3159 smQueue.push_back( eof->_subMesh );
3161 if ( !eos.HasC1( eoe ))
3163 eos._eosC1.push_back( eoe );
3164 eoe->_toSmooth = false;
3165 data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3170 if ( eos._eosC1.empty() )
3173 // check VERTEXes of C1 FACEs
3174 TopTools_MapIteratorOfMapOfShape vIt( allVV );
3175 for ( ; vIt.More(); vIt.Next() )
3177 _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3178 if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3181 bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3182 PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3183 while ( const TopoDS_Shape* face = fIt->next() )
3185 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3186 if ( !eof ) continue; // other solid
3187 isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3193 eos._eosC1.push_back( eov );
3194 data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3195 c1VV.Add( eov->_shape );
3199 } // fill _eosC1 of FACEs
3204 vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3206 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3208 _EdgesOnShape& eov = edgesByGeom[iS];
3209 if ( eov._edges.empty() ||
3210 eov.ShapeType() != TopAbs_VERTEX ||
3211 c1VV.Contains( eov._shape ))
3213 const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3215 // get directions of surrounding EDGEs
3217 PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3218 while ( const TopoDS_Shape* e = fIt->next() )
3220 _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3221 if ( !eoe ) continue; // other solid
3222 gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3223 if ( !Precision::IsInfinite( eDir.X() ))
3224 dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3227 // find EDGEs with C1 directions
3228 for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3229 for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3230 if ( dirOfEdges[i].first && dirOfEdges[j].first )
3232 double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3233 bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3236 double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3237 double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3238 double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3239 if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3240 if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3241 dirOfEdges[i].first = 0;
3242 dirOfEdges[j].first = 0;
3245 } // fill _eosC1 of VERTEXes
3252 //================================================================================
3254 * \brief initialize data of _EdgesOnShape
3256 //================================================================================
3258 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3262 if ( !eos._shape.IsNull() ||
3263 sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3266 SMESH_MesherHelper helper( *_mesh );
3269 eos._shapeID = sm->GetId();
3270 eos._shape = sm->GetSubShape();
3271 if ( eos.ShapeType() == TopAbs_FACE )
3272 eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3273 eos._toSmooth = false;
3277 map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3278 data._shrinkShape2Shape.find( eos._shapeID );
3279 if ( s2s != data._shrinkShape2Shape.end() )
3280 eos._sWOL = s2s->second;
3282 eos._isRegularSWOL = true;
3283 if ( eos.SWOLType() == TopAbs_FACE )
3285 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3286 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3287 eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3291 if ( data._hyps.size() == 1 )
3293 eos._hyp = data._hyps.back();
3297 // compute average StdMeshers_ViscousLayers parameters
3298 map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3299 if ( eos.ShapeType() == TopAbs_FACE )
3301 if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3302 eos._hyp = f2hyp->second;
3306 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3307 while ( const TopoDS_Shape* face = fIt->next() )
3309 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3310 if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3311 eos._hyp.Add( f2hyp->second );
3317 if ( ! eos._hyp.UseSurfaceNormal() )
3319 if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3321 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3322 if ( !smDS ) return;
3323 eos._faceNormals.reserve( smDS->NbElements() );
3325 double oriFactor = helper.IsReversedSubMesh( TopoDS::Face( eos._shape )) ? 1.: -1.;
3326 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3327 for ( ; eIt->more(); )
3329 const SMDS_MeshElement* face = eIt->next();
3330 gp_XYZ& norm = eos._faceNormals[face];
3331 if ( !SMESH_MeshAlgos::FaceNormal( face, norm, /*normalized=*/true ))
3332 norm.SetCoord( 0,0,0 );
3336 else // find EOS of adjacent FACEs
3338 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3339 while ( const TopoDS_Shape* face = fIt->next() )
3341 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3342 eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3343 if ( eos._faceEOS.back()->_shape.IsNull() )
3344 // avoid using uninitialised _shapeID in GetNormal()
3345 eos._faceEOS.back()->_shapeID = faceID;
3351 //================================================================================
3353 * \brief Returns normal of a face
3355 //================================================================================
3357 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3360 _EdgesOnShape* eos = 0;
3362 if ( face->getshapeId() == _shapeID )
3368 for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3369 if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3370 eos = _faceEOS[ iF ];
3374 ( ok = ( eos->_faceNormals.count( face ) )))
3376 norm = eos->_faceNormals[ face ];
3380 debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3381 << " on _shape #" << _shapeID );
3387 //================================================================================
3389 * \brief Set data of _LayerEdge needed for smoothing
3391 //================================================================================
3393 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
3395 SMESH_MesherHelper& helper,
3398 const SMDS_MeshNode* node = edge._nodes[0]; // source node
3401 edge._maxLen = Precision::Infinite();
3404 edge._curvature = 0;
3407 // --------------------------
3408 // Compute _normal and _cosin
3409 // --------------------------
3412 edge._lenFactor = 1.;
3413 edge._normal.SetCoord(0,0,0);
3414 _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3416 int totalNbFaces = 0;
3418 std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3422 const bool onShrinkShape = !eos._sWOL.IsNull();
3423 const bool useGeometry = (( eos._hyp.UseSurfaceNormal() ) ||
3424 ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3426 // get geom FACEs the node lies on
3427 //if ( useGeometry )
3429 set<TGeomID> faceIds;
3430 if ( eos.ShapeType() == TopAbs_FACE )
3432 faceIds.insert( eos._shapeID );
3436 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3437 while ( fIt->more() )
3438 faceIds.insert( fIt->next()->getshapeId() );
3440 set<TGeomID>::iterator id = faceIds.begin();
3441 for ( ; id != faceIds.end(); ++id )
3443 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3444 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3446 F = TopoDS::Face( s );
3447 face2Norm[ totalNbFaces ].first = F;
3453 bool fromVonF = false;
3456 fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3457 eos.SWOLType() == TopAbs_FACE &&
3460 if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3462 if ( eos.SWOLType() == TopAbs_EDGE )
3464 // inflate from VERTEX along EDGE
3465 edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3467 else if ( eos.ShapeType() == TopAbs_VERTEX )
3469 // inflate from VERTEX along FACE
3470 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3471 node, helper, normOK, &edge._cosin);
3475 // inflate from EDGE along FACE
3476 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3477 node, helper, normOK);
3480 else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3483 face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3486 for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3488 F = face2Norm[ iF ].first;
3489 geomNorm = getFaceNormal( node, F, helper, normOK );
3490 if ( !normOK ) continue;
3493 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3495 face2Norm[ iF ].second = geomNorm.XYZ();
3496 edge._normal += geomNorm.XYZ();
3498 if ( nbOkNorms == 0 )
3499 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3501 if ( totalNbFaces >= 3 )
3503 edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3506 if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3508 // opposite normals, re-get normals at shifted positions (IPAL 52426)
3509 edge._normal.SetCoord( 0,0,0 );
3510 for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3512 const TopoDS_Face& F = face2Norm[iF].first;
3513 geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3514 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3517 face2Norm[ iF ].second = geomNorm.XYZ();
3518 edge._normal += face2Norm[ iF ].second;
3523 else // !useGeometry - get _normal using surrounding mesh faces
3525 edge._normal = getWeigthedNormal( &edge );
3527 // set<TGeomID> faceIds;
3529 // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3530 // while ( fIt->more() )
3532 // const SMDS_MeshElement* face = fIt->next();
3533 // if ( eos.GetNormal( face, geomNorm ))
3535 // if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3536 // continue; // use only one mesh face on FACE
3537 // edge._normal += geomNorm.XYZ();
3544 //if ( eos._hyp.UseSurfaceNormal() )
3546 switch ( eos.ShapeType() )
3553 TopoDS_Edge E = TopoDS::Edge( eos._shape );
3554 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3555 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3556 edge._cosin = Cos( angle );
3559 case TopAbs_VERTEX: {
3562 getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3563 node, helper, normOK, &edge._cosin );
3565 else if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3567 TopoDS_Vertex V = TopoDS::Vertex( eos._shape );
3568 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3569 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3570 edge._cosin = Cos( angle );
3571 if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3572 for ( int iF = 1; iF < totalNbFaces; ++iF )
3574 F = face2Norm[ iF ].first;
3575 inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3577 double angle = inFaceDir.Angle( edge._normal );
3578 double cosin = Cos( angle );
3579 if ( Abs( cosin ) > Abs( edge._cosin ))
3580 edge._cosin = cosin;
3587 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3591 double normSize = edge._normal.SquareModulus();
3592 if ( normSize < numeric_limits<double>::min() )
3593 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3595 edge._normal /= sqrt( normSize );
3597 if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3599 getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3600 edge._nodes.resize( 1 );
3601 edge._normal.SetCoord( 0,0,0 );
3602 edge.SetMaxLen( 0 );
3605 // Set the rest data
3606 // --------------------
3608 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3610 if ( onShrinkShape )
3612 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3613 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3614 sm->RemoveNode( tgtNode );
3616 // set initial position which is parameters on _sWOL in this case
3617 if ( eos.SWOLType() == TopAbs_EDGE )
3619 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3620 edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3621 if ( edge._nodes.size() > 1 )
3622 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3624 else // eos.SWOLType() == TopAbs_FACE
3626 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3627 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3628 if ( edge._nodes.size() > 1 )
3629 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3632 if ( edge._nodes.size() > 1 )
3634 // check if an angle between a FACE with layers and SWOL is sharp,
3635 // else the edge should not inflate
3637 for ( int iF = 0; iF < totalNbFaces && F.IsNull(); ++iF ) // find a FACE with VL
3638 if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3639 F = face2Norm[iF].first;
3642 geomNorm = getFaceNormal( node, F, helper, normOK );
3643 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3644 geomNorm.Reverse(); // inside the SOLID
3645 if ( geomNorm * edge._normal < -0.001 )
3647 getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3648 edge._nodes.resize( 1 );
3650 else if ( edge._lenFactor > 3 )
3652 edge._lenFactor = 2;
3653 edge.Set( _LayerEdge::RISKY_SWOL );
3660 edge._pos.push_back( SMESH_TNodeXYZ( node ));
3662 if ( eos.ShapeType() == TopAbs_FACE )
3665 for ( size_t i = 0; i < edge._simplices.size(); ++i )
3667 edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3668 edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3673 // Set neighbor nodes for a _LayerEdge based on EDGE
3675 if ( eos.ShapeType() == TopAbs_EDGE /*||
3676 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3678 edge._2neibors = new _2NearEdges;
3679 // target nodes instead of source ones will be set later
3685 //================================================================================
3687 * \brief Return normal to a FACE at a node
3688 * \param [in] n - node
3689 * \param [in] face - FACE
3690 * \param [in] helper - helper
3691 * \param [out] isOK - true or false
3692 * \param [in] shiftInside - to find normal at a position shifted inside the face
3693 * \return gp_XYZ - normal
3695 //================================================================================
3697 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3698 const TopoDS_Face& face,
3699 SMESH_MesherHelper& helper,
3706 // get a shifted position
3707 gp_Pnt p = SMESH_TNodeXYZ( node );
3708 gp_XYZ shift( 0,0,0 );
3709 TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3710 switch ( S.ShapeType() ) {
3713 shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3718 shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3726 p.Translate( shift * 1e-5 );
3728 TopLoc_Location loc;
3729 GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3731 if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3733 projector.Perform( p );
3734 if ( !projector.IsDone() || projector.NbPoints() < 1 )
3740 projector.LowerDistanceParameters(U,V);
3745 uv = helper.GetNodeUV( face, node, 0, &isOK );
3751 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3753 if ( !shiftInside &&
3754 helper.IsDegenShape( node->getshapeId() ) &&
3755 getFaceNormalAtSingularity( uv, face, helper, normal ))
3758 return normal.XYZ();
3761 int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3762 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3764 if ( pointKind == IMPOSSIBLE &&
3765 node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3767 // probably NormEstim() failed due to a too high tolerance
3768 pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3769 isOK = ( pointKind < IMPOSSIBLE );
3771 if ( pointKind < IMPOSSIBLE )
3773 if ( pointKind != REGULAR &&
3775 node->GetPosition()->GetDim() < 2 ) // FACE boundary
3777 gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3778 if ( normShift * normal.XYZ() < 0. )
3784 if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3786 const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3788 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3789 while ( fIt->more() )
3791 const SMDS_MeshElement* f = fIt->next();
3792 if ( f->getshapeId() == faceID )
3794 isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3797 TopoDS_Face ff = face;
3798 ff.Orientation( TopAbs_FORWARD );
3799 if ( helper.IsReversedSubMesh( ff ))
3806 return normal.XYZ();
3809 //================================================================================
3811 * \brief Try to get normal at a singularity of a surface basing on it's nature
3813 //================================================================================
3815 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY& uv,
3816 const TopoDS_Face& face,
3817 SMESH_MesherHelper& helper,
3820 BRepAdaptor_Surface surface( face );
3822 if ( !getRovolutionAxis( surface, axis ))
3825 double f,l, d, du, dv;
3826 f = surface.FirstUParameter();
3827 l = surface.LastUParameter();
3828 d = ( uv.X() - f ) / ( l - f );
3829 du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3830 f = surface.FirstVParameter();
3831 l = surface.LastVParameter();
3832 d = ( uv.Y() - f ) / ( l - f );
3833 dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3836 gp_Pnt2d testUV = uv;
3837 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3839 Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3840 for ( int iLoop = 0; true ; ++iLoop )
3842 testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3843 if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3850 if ( axis * refDir < 0. )
3858 //================================================================================
3860 * \brief Return a normal at a node weighted with angles taken by faces
3862 //================================================================================
3864 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3866 const SMDS_MeshNode* n = edge->_nodes[0];
3868 gp_XYZ resNorm(0,0,0);
3869 SMESH_TNodeXYZ p0( n ), pP, pN;
3870 for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3872 pP.Set( edge->_simplices[i]._nPrev );
3873 pN.Set( edge->_simplices[i]._nNext );
3874 gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3875 double l0P = v0P.SquareMagnitude();
3876 double l0N = v0N.SquareMagnitude();
3877 double lPN = vPN.SquareMagnitude();
3878 if ( l0P < std::numeric_limits<double>::min() ||
3879 l0N < std::numeric_limits<double>::min() ||
3880 lPN < std::numeric_limits<double>::min() )
3882 double lNorm = norm.SquareMagnitude();
3883 double sin2 = lNorm / l0P / l0N;
3884 double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3886 double weight = sin2 * angle / lPN;
3887 resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3893 //================================================================================
3895 * \brief Return a normal at a node by getting a common point of offset planes
3896 * defined by the FACE normals
3898 //================================================================================
3900 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge* edge,
3901 std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3905 SMESH_TNodeXYZ p0 = edge->_nodes[0];
3907 gp_XYZ resNorm(0,0,0);
3908 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3909 if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3911 for ( int i = 0; i < nbFaces; ++i )
3912 resNorm += f2Normal[i].second;
3916 // prepare _OffsetPlane's
3917 vector< _OffsetPlane > pln( nbFaces );
3918 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3920 pln[i]._faceIndex = i;
3921 pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3925 pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3926 pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3929 // intersect neighboring OffsetPlane's
3930 PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3931 while ( const TopoDS_Shape* edge = edgeIt->next() )
3933 int f1 = -1, f2 = -1;
3934 for ( int i = 0; i < nbFaces && f2 < 0; ++i )
3935 if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3936 (( f1 < 0 ) ? f1 : f2 ) = i;
3939 pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3942 // get a common point
3943 gp_XYZ commonPnt( 0, 0, 0 );
3946 for ( int i = 0; i < nbFaces; ++i )
3948 commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3949 nbPoints += isPointFound;
3951 gp_XYZ wgtNorm = getWeigthedNormal( edge );
3952 if ( nbPoints == 0 )
3955 commonPnt /= nbPoints;
3956 resNorm = commonPnt - p0;
3960 // choose the best among resNorm and wgtNorm
3961 resNorm.Normalize();
3962 wgtNorm.Normalize();
3963 double resMinDot = std::numeric_limits<double>::max();
3964 double wgtMinDot = std::numeric_limits<double>::max();
3965 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3967 resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3968 wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3971 if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3973 edge->Set( _LayerEdge::MULTI_NORMAL );
3976 return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3979 //================================================================================
3981 * \brief Compute line of intersection of 2 planes
3983 //================================================================================
3985 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane& pln,
3986 const TopoDS_Edge& E,
3987 const TopoDS_Vertex& V )
3989 int iNext = bool( _faceIndexNext[0] >= 0 );
3990 _faceIndexNext[ iNext ] = pln._faceIndex;
3992 gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3993 gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3995 gp_XYZ lineDir = n1 ^ n2;
3997 double x = Abs( lineDir.X() );
3998 double y = Abs( lineDir.Y() );
3999 double z = Abs( lineDir.Z() );
4001 int cooMax; // max coordinate
4003 if (x > z) cooMax = 1;
4007 if (y > z) cooMax = 2;
4012 if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
4014 // parallel planes - intersection is an offset of the common EDGE
4015 gp_Pnt p = BRep_Tool::Pnt( V );
4016 linePos = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
4017 lineDir = getEdgeDir( E, V );
4021 // the constants in the 2 plane equations
4022 double d1 = - ( _plane.Axis().Direction().XYZ() * _plane.Location().XYZ() );
4023 double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
4028 linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
4029 linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
4032 linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4034 linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4037 linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4038 linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4042 gp_Lin& line = _lines[ iNext ];
4043 line.SetDirection( lineDir );
4044 line.SetLocation ( linePos );
4046 _isLineOK[ iNext ] = true;
4049 iNext = bool( pln._faceIndexNext[0] >= 0 );
4050 pln._lines [ iNext ] = line;
4051 pln._faceIndexNext[ iNext ] = this->_faceIndex;
4052 pln._isLineOK [ iNext ] = true;
4055 //================================================================================
4057 * \brief Computes intersection point of two _lines
4059 //================================================================================
4061 gp_XYZ _OffsetPlane::GetCommonPoint(bool& isFound,
4062 const TopoDS_Vertex & V) const
4067 if ( NbLines() == 2 )
4069 gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4070 double dot01 = lPerp0 * _lines[1].Direction().XYZ();
4071 if ( Abs( dot01 ) > 0.05 )
4073 gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4074 double u1 = - ( lPerp0 * l0l1 ) / dot01;
4075 p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4080 gp_Pnt pV ( BRep_Tool::Pnt( V ));
4081 gp_Vec lv0( _lines[0].Location(), pV ), lv1(_lines[1].Location(), pV );
4082 double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4083 p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4084 p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4092 //================================================================================
4094 * \brief Find 2 neighbor nodes of a node on EDGE
4096 //================================================================================
4098 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
4099 const SMDS_MeshNode*& n1,
4100 const SMDS_MeshNode*& n2,
4104 const SMDS_MeshNode* node = edge->_nodes[0];
4105 const int shapeInd = eos._shapeID;
4106 SMESHDS_SubMesh* edgeSM = 0;
4107 if ( eos.ShapeType() == TopAbs_EDGE )
4109 edgeSM = eos._subMesh->GetSubMeshDS();
4110 if ( !edgeSM || edgeSM->NbElements() == 0 )
4111 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4115 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4116 while ( eIt->more() && !n2 )
4118 const SMDS_MeshElement* e = eIt->next();
4119 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
4120 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4123 if (!edgeSM->Contains(e)) continue;
4127 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4128 if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4130 ( iN++ ? n2 : n1 ) = nNeibor;
4133 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4137 //================================================================================
4139 * \brief Set _curvature and _2neibors->_plnNorm by 2 neighbor nodes residing the same EDGE
4141 //================================================================================
4143 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4144 const SMDS_MeshNode* n2,
4145 const _EdgesOnShape& eos,
4146 SMESH_MesherHelper& helper)
4148 if ( eos.ShapeType() != TopAbs_EDGE )
4150 if ( _curvature && Is( SMOOTHED_C1 ))
4153 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
4154 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4155 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4159 double sumLen = vec1.Modulus() + vec2.Modulus();
4160 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4161 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4162 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4163 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4164 if ( _curvature ) delete _curvature;
4165 _curvature = _Curvature::New( avgNormProj, avgLen );
4166 // if ( _curvature )
4167 // debugMsg( _nodes[0]->GetID()
4168 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4169 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4170 // << _curvature->lenDelta(0) );
4174 if ( eos._sWOL.IsNull() )
4176 TopoDS_Edge E = TopoDS::Edge( eos._shape );
4177 // if ( SMESH_Algo::isDegenerated( E ))
4179 gp_XYZ dirE = getEdgeDir( E, _nodes[0], helper );
4180 gp_XYZ plnNorm = dirE ^ _normal;
4181 double proj0 = plnNorm * vec1;
4182 double proj1 = plnNorm * vec2;
4183 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4185 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4186 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4191 //================================================================================
4193 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4194 * this and the other _LayerEdge are inflated along a FACE or an EDGE
4196 //================================================================================
4198 gp_XYZ _LayerEdge::Copy( _LayerEdge& other,
4200 SMESH_MesherHelper& helper )
4202 _nodes = other._nodes;
4203 _normal = other._normal;
4205 _lenFactor = other._lenFactor;
4206 _cosin = other._cosin;
4207 _2neibors = other._2neibors;
4208 _curvature = 0; std::swap( _curvature, other._curvature );
4209 _2neibors = 0; std::swap( _2neibors, other._2neibors );
4211 gp_XYZ lastPos( 0,0,0 );
4212 if ( eos.SWOLType() == TopAbs_EDGE )
4214 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4215 _pos.push_back( gp_XYZ( u, 0, 0));
4217 u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4222 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4223 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4225 uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4226 lastPos.SetX( uv.X() );
4227 lastPos.SetY( uv.Y() );
4232 //================================================================================
4234 * \brief Set _cosin and _lenFactor
4236 //================================================================================
4238 void _LayerEdge::SetCosin( double cosin )
4241 cosin = Abs( _cosin );
4242 //_lenFactor = ( cosin < 1.-1e-12 ) ? Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4243 _lenFactor = ( cosin < 1.-1e-12 ) ? 1./sqrt(1-cosin*cosin ) : 1.0;
4246 //================================================================================
4248 * \brief Check if another _LayerEdge is a neighbor on EDGE
4250 //================================================================================
4252 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4254 return (( this->_2neibors && this->_2neibors->include( edge )) ||
4255 ( edge->_2neibors && edge->_2neibors->include( this )));
4258 //================================================================================
4260 * \brief Fills a vector<_Simplex >
4262 //================================================================================
4264 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4265 vector<_Simplex>& simplices,
4266 const set<TGeomID>& ingnoreShapes,
4267 const _SolidData* dataToCheckOri,
4271 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4272 while ( fIt->more() )
4274 const SMDS_MeshElement* f = fIt->next();
4275 const TGeomID shapeInd = f->getshapeId();
4276 if ( ingnoreShapes.count( shapeInd )) continue;
4277 const int nbNodes = f->NbCornerNodes();
4278 const int srcInd = f->GetNodeIndex( node );
4279 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4280 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4281 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4282 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4283 std::swap( nPrev, nNext );
4284 simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4288 SortSimplices( simplices );
4291 //================================================================================
4293 * \brief Set neighbor simplices side by side
4295 //================================================================================
4297 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4299 vector<_Simplex> sortedSimplices( simplices.size() );
4300 sortedSimplices[0] = simplices[0];
4302 for ( size_t i = 1; i < simplices.size(); ++i )
4304 for ( size_t j = 1; j < simplices.size(); ++j )
4305 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4307 sortedSimplices[i] = simplices[j];
4312 if ( nbFound == simplices.size() - 1 )
4313 simplices.swap( sortedSimplices );
4316 //================================================================================
4318 * \brief DEBUG. Create groups containing temporary data of _LayerEdge's
4320 //================================================================================
4322 void _ViscousBuilder::makeGroupOfLE()
4325 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4327 if ( _sdVec[i]._n2eMap.empty() ) continue;
4329 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4330 TNode2Edge::iterator n2e;
4331 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4333 _LayerEdge* le = n2e->second;
4334 // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4335 // dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4336 // << ", " << le->_nodes[iN]->GetID() <<"])");
4338 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4339 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4344 dumpFunction( SMESH_Comment("makeNormals") << i );
4345 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4347 _LayerEdge* edge = n2e->second;
4348 SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4349 nXYZ += edge->_normal * _sdVec[i]._stepSize;
4350 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4351 << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4355 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4356 dumpCmd( "faceId1 = mesh.NbElements()" );
4357 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4358 for ( ; fExp.More(); fExp.Next() )
4360 if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4362 if ( sm->NbElements() == 0 ) continue;
4363 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4364 while ( fIt->more())
4366 const SMDS_MeshElement* e = fIt->next();
4367 SMESH_Comment cmd("mesh.AddFace([");
4368 for ( int j = 0; j < e->NbCornerNodes(); ++j )
4369 cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4374 dumpCmd( "faceId2 = mesh.NbElements()" );
4375 dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4376 << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4377 << "'%s-%s' % (faceId1+1, faceId2))");
4383 //================================================================================
4385 * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4387 //================================================================================
4389 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4391 data._geomSize = Precision::Infinite();
4392 double intersecDist;
4393 const SMDS_MeshElement* face;
4394 SMESH_MesherHelper helper( *_mesh );
4396 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4397 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4398 data._proxyMesh->GetFaces( data._solid )));
4400 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4402 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4403 if ( eos._edges.empty() )
4405 // get neighbor faces, intersection with which should not be considered since
4406 // collisions are avoided by means of smoothing
4407 set< TGeomID > neighborFaces;
4408 if ( eos._hyp.ToSmooth() )
4410 SMESH_subMeshIteratorPtr subIt =
4411 eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4412 while ( subIt->more() )
4414 SMESH_subMesh* sm = subIt->next();
4415 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4416 while ( const TopoDS_Shape* face = fIt->next() )
4417 neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4420 // find intersections
4421 double thinkness = eos._hyp.GetTotalThickness();
4422 for ( size_t i = 0; i < eos._edges.size(); ++i )
4424 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4425 eos._edges[i]->SetMaxLen( thinkness );
4426 eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4427 if ( intersecDist > 0 && face )
4429 data._geomSize = Min( data._geomSize, intersecDist );
4430 if ( !neighborFaces.count( face->getshapeId() ))
4431 eos[i]->SetMaxLen( Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. )));
4436 data._maxThickness = 0;
4437 data._minThickness = 1e100;
4438 list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
4439 for ( ; hyp != data._hyps.end(); ++hyp )
4441 data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
4442 data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
4445 // Limit inflation step size by geometry size found by intersecting
4446 // normals of _LayerEdge's with mesh faces
4447 if ( data._stepSize > 0.3 * data._geomSize )
4448 limitStepSize( data, 0.3 * data._geomSize );
4450 if ( data._stepSize > data._minThickness )
4451 limitStepSize( data, data._minThickness );
4454 // -------------------------------------------------------------------------
4455 // Detect _LayerEdge which can't intersect with opposite or neighbor layer,
4456 // so no need in detecting intersection at each inflation step
4457 // -------------------------------------------------------------------------
4459 int nbSteps = data._maxThickness / data._stepSize;
4460 if ( nbSteps < 3 || nbSteps * data._n2eMap.size() < 100000 )
4463 vector< const SMDS_MeshElement* > closeFaces;
4466 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4468 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4469 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
4472 for ( size_t i = 0; i < eos.size(); ++i )
4474 SMESH_NodeXYZ p( eos[i]->_nodes[0] );
4475 double radius = data._maxThickness + 2 * eos[i]->_maxLen;
4477 searcher->GetElementsInSphere( p, radius, SMDSAbs_Face, closeFaces );
4479 bool toIgnore = true;
4480 for ( size_t iF = 0; iF < closeFaces.size() && toIgnore; ++iF )
4481 if ( !( toIgnore = ( closeFaces[ iF ]->getshapeId() == eos._shapeID ||
4482 data._ignoreFaceIds.count( closeFaces[ iF ]->getshapeId() ))))
4484 // check if a _LayerEdge will inflate in a direction opposite to a direction
4485 // toward a close face
4486 bool allBehind = true;
4487 for ( int iN = 0; iN < closeFaces[ iF ]->NbCornerNodes() && allBehind; ++iN )
4489 SMESH_NodeXYZ pi( closeFaces[ iF ]->GetNode( iN ));
4490 allBehind = (( pi - p ) * eos[i]->_normal < 0.1 * data._stepSize );
4492 toIgnore = allBehind;
4496 if ( toIgnore ) // no need to detect intersection
4498 eos[i]->Set( _LayerEdge::INTERSECTED );
4504 debugMsg( "Nb LE to intersect " << data._n2eMap.size()-nbDetected << ", ignore " << nbDetected );
4509 //================================================================================
4511 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4513 //================================================================================
4515 bool _ViscousBuilder::inflate(_SolidData& data)
4517 SMESH_MesherHelper helper( *_mesh );
4519 const double tgtThick = data._maxThickness;
4521 if ( data._stepSize < 1. )
4522 data._epsilon = data._stepSize * 1e-7;
4524 debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4527 findCollisionEdges( data, helper );
4529 limitMaxLenByCurvature( data, helper );
4533 // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4534 for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4535 if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4536 data._edgesOnShape[i]._edges.size() > 0 &&
4537 data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4539 data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4540 data._edgesOnShape[i]._edges[0]->Block( data );
4543 const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4545 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4546 int nbSteps = 0, nbRepeats = 0;
4547 while ( avgThick < 0.99 )
4549 // new target length
4550 double prevThick = curThick;
4551 curThick += data._stepSize;
4552 if ( curThick > tgtThick )
4554 curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4558 double stepSize = curThick - prevThick;
4559 updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4561 // Elongate _LayerEdge's
4562 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4563 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4565 _EdgesOnShape& eos = data._edgesOnShape[iS];
4566 if ( eos._edges.empty() ) continue;
4568 const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4569 for ( size_t i = 0; i < eos._edges.size(); ++i )
4571 eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4576 if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4579 // Improve and check quality
4580 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4584 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4585 debugMsg("NOT INVALIDATED STEP!");
4586 return error("Smoothing failed", data._index);
4588 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4589 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4591 _EdgesOnShape& eos = data._edgesOnShape[iS];
4592 for ( size_t i = 0; i < eos._edges.size(); ++i )
4593 eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4597 break; // no more inflating possible
4601 // Evaluate achieved thickness
4603 int nbActiveEdges = 0;
4604 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4606 _EdgesOnShape& eos = data._edgesOnShape[iS];
4607 if ( eos._edges.empty() ) continue;
4609 const double shapeTgtThick = eos._hyp.GetTotalThickness();
4610 for ( size_t i = 0; i < eos._edges.size(); ++i )
4612 if ( eos._edges[i]->_nodes.size() > 1 )
4613 avgThick += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4615 avgThick += shapeTgtThick;
4616 nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4619 avgThick /= data._n2eMap.size();
4620 debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4622 #ifdef BLOCK_INFLATION
4623 if ( nbActiveEdges == 0 )
4625 debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4629 if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4631 debugMsg( "-- Stop inflation since "
4632 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4633 << tgtThick * avgThick << " ) * " << safeFactor );
4639 limitStepSize( data, 0.25 * distToIntersection );
4640 if ( data._stepSizeNodes[0] )
4641 data._stepSize = data._stepSizeCoeff *
4642 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4644 } // while ( avgThick < 0.99 )
4647 return error("failed at the very first inflation step", data._index);
4649 if ( avgThick < 0.99 )
4651 if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4653 data._proxyMesh->_warning.reset
4654 ( new SMESH_ComputeError (COMPERR_WARNING,
4655 SMESH_Comment("Thickness ") << tgtThick <<
4656 " of viscous layers not reached,"
4657 " average reached thickness is " << avgThick*tgtThick));
4661 // Restore position of src nodes moved by inflation on _noShrinkShapes
4662 dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4663 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4665 _EdgesOnShape& eos = data._edgesOnShape[iS];
4666 if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4667 for ( size_t i = 0; i < eos._edges.size(); ++i )
4669 restoreNoShrink( *eos._edges[ i ] );
4674 return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4677 //================================================================================
4679 * \brief Improve quality of layer inner surface and check intersection
4681 //================================================================================
4683 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4685 double & distToIntersection)
4687 if ( data._nbShapesToSmooth == 0 )
4688 return true; // no shapes needing smoothing
4690 bool moved, improved;
4692 vector< _LayerEdge* > movedEdges, badEdges;
4693 vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4694 vector< bool > isConcaveFace;
4696 SMESH_MesherHelper helper(*_mesh);
4697 Handle(ShapeAnalysis_Surface) surface;
4700 for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4702 const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4704 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4706 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4707 if ( !eos._toSmooth ||
4708 eos.ShapeType() != shapeType ||
4709 eos._edges.empty() )
4712 // already smoothed?
4713 // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4714 // if ( !toSmooth ) continue;
4716 if ( !eos._hyp.ToSmooth() )
4718 // smooth disabled by the user; check validy only
4719 if ( !isFace ) continue;
4721 for ( size_t i = 0; i < eos._edges.size(); ++i )
4723 _LayerEdge* edge = eos._edges[i];
4724 for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4725 if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4727 // debugMsg( "-- Stop inflation. Bad simplex ("
4728 // << " "<< edge->_nodes[0]->GetID()
4729 // << " "<< edge->_nodes.back()->GetID()
4730 // << " "<< edge->_simplices[iF]._nPrev->GetID()
4731 // << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4733 badEdges.push_back( edge );
4736 if ( !badEdges.empty() )
4740 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4744 continue; // goto the next EDGE or FACE
4748 if ( eos.SWOLType() == TopAbs_FACE )
4750 if ( !F.IsSame( eos._sWOL )) {
4751 F = TopoDS::Face( eos._sWOL );
4752 helper.SetSubShape( F );
4753 surface = helper.GetSurface( F );
4758 F.Nullify(); surface.Nullify();
4760 const TGeomID sInd = eos._shapeID;
4762 // perform smoothing
4764 if ( eos.ShapeType() == TopAbs_EDGE )
4766 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4768 if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4770 // smooth on EDGE's (normally we should not get here)
4774 for ( size_t i = 0; i < eos._edges.size(); ++i )
4776 moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4778 dumpCmd( SMESH_Comment("# end step ")<<step);
4780 while ( moved && step++ < 5 );
4785 else // smooth on FACE
4788 eosC1.push_back( & eos );
4789 eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4792 isConcaveFace.resize( eosC1.size() );
4793 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4795 isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID );
4796 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4797 for ( size_t i = 0; i < edges.size(); ++i )
4798 if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4799 edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4800 movedEdges.push_back( edges[i] );
4802 makeOffsetSurface( *eosC1[ iEOS ], helper );
4805 int step = 0, stepLimit = 5, nbBad = 0;
4806 while (( ++step <= stepLimit ) || improved )
4808 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4809 <<"_InfStep"<<infStep<<"_"<<step); // debug
4810 int oldBadNb = nbBad;
4813 #ifdef INCREMENTAL_SMOOTH
4814 bool findBest = false; // ( step == stepLimit );
4815 for ( size_t i = 0; i < movedEdges.size(); ++i )
4817 movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4818 if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4819 badEdges.push_back( movedEdges[i] );
4822 bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4823 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4825 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4826 for ( size_t i = 0; i < edges.size(); ++i )
4828 edges[i]->Unset( _LayerEdge::SMOOTHED );
4829 if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4830 badEdges.push_back( eos._edges[i] );
4834 nbBad = badEdges.size();
4837 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4839 if ( !badEdges.empty() && step >= stepLimit / 2 )
4841 if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4844 // resolve hard smoothing situation around concave VERTEXes
4845 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4847 vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4848 for ( size_t i = 0; i < eosCoVe.size(); ++i )
4849 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4852 // look for the best smooth of _LayerEdge's neighboring badEdges
4854 for ( size_t i = 0; i < badEdges.size(); ++i )
4856 _LayerEdge* ledge = badEdges[i];
4857 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4859 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4860 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4862 ledge->Unset( _LayerEdge::SMOOTHED );
4863 nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4865 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4868 if ( nbBad == oldBadNb &&
4870 step < stepLimit ) // smooth w/o check of validity
4873 dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4874 <<"_InfStep"<<infStep<<"_"<<step); // debug
4875 for ( size_t i = 0; i < movedEdges.size(); ++i )
4877 movedEdges[i]->SmoothWoCheck();
4879 if ( stepLimit < 9 )
4883 improved = ( nbBad < oldBadNb );
4887 if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4888 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4890 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4893 } // smoothing steps
4895 // project -- to prevent intersections or fix bad simplices
4896 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4898 if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4899 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4902 //if ( !badEdges.empty() )
4905 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4907 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4909 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4911 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4912 edge->CheckNeiborsOnBoundary( & badEdges );
4913 if (( nbBad > 0 ) ||
4914 ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4916 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4917 gp_XYZ prevXYZ = edge->PrevCheckPos();
4918 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4919 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4921 debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4922 << " "<< tgtXYZ._node->GetID()
4923 << " "<< edge->_simplices[j]._nPrev->GetID()
4924 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4925 badEdges.push_back( edge );
4932 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4933 nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4939 } // // smooth on FACE's
4941 } // smooth on [ EDGEs, FACEs ]
4943 // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4945 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4947 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4948 if ( eos.ShapeType() == TopAbs_FACE ||
4949 eos._edges.empty() ||
4950 !eos._sWOL.IsNull() )
4954 for ( size_t i = 0; i < eos._edges.size(); ++i )
4956 _LayerEdge* edge = eos._edges[i];
4957 if ( edge->_nodes.size() < 2 ) continue;
4958 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4959 //SMESH_TNodeXYZ prevXYZ = edge->_nodes[0];
4960 gp_XYZ prevXYZ = edge->PrevCheckPos( &eos );
4961 //const gp_XYZ& prevXYZ = edge->PrevPos();
4962 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4963 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4965 debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4966 << " "<< tgtXYZ._node->GetID()
4967 << " "<< edge->_simplices[j]._nPrev->GetID()
4968 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4969 badEdges.push_back( edge );
4974 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4976 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4982 // Check if the last segments of _LayerEdge intersects 2D elements;
4983 // checked elements are either temporary faces or faces on surfaces w/o the layers
4985 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4986 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4987 data._proxyMesh->GetFaces( data._solid )) );
4989 #ifdef BLOCK_INFLATION
4990 const bool toBlockInfaltion = true;
4992 const bool toBlockInfaltion = false;
4994 distToIntersection = Precision::Infinite();
4996 const SMDS_MeshElement* intFace = 0;
4997 const SMDS_MeshElement* closestFace = 0;
4999 bool is1stBlocked = true; // dbg
5000 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5002 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5003 if ( eos._edges.empty() || !eos._sWOL.IsNull() )
5005 for ( size_t i = 0; i < eos._edges.size(); ++i )
5007 if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
5008 eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
5010 if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5013 // commented due to "Illegal hash-positionPosition" error in NETGEN
5014 // on Debian60 on viscous_layers_01/B2 case
5015 // Collision; try to deflate _LayerEdge's causing it
5016 // badEdges.clear();
5017 // badEdges.push_back( eos._edges[i] );
5018 // eosC1[0] = & eos;
5019 // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5023 // badEdges.clear();
5024 // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5026 // if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5028 // const SMDS_MeshElement* srcFace =
5029 // eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5030 // SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5031 // while ( nIt->more() )
5033 // const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5034 // TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5035 // if ( n2e != data._n2eMap.end() )
5036 // badEdges.push_back( n2e->second );
5039 // nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5044 // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5051 SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
5056 const bool isShorterDist = ( distToIntersection > dist );
5057 if ( toBlockInfaltion || isShorterDist )
5059 // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
5060 // lying on this _ConvexFace
5061 if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
5062 if ( convFace->_isTooCurved && convFace->_subIdToEOS.count ( eos._shapeID ))
5065 // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
5066 // ( avoid limiting the thickness on the case of issue 22576)
5067 if ( intFace->getshapeId() == eos._shapeID )
5070 // ignore intersection with intFace of an adjacent FACE
5071 if ( dist > 0.1 * eos._edges[i]->_len )
5073 bool toIgnore = false;
5074 if ( eos._toSmooth )
5076 const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
5077 if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
5079 TopExp_Explorer sub( eos._shape,
5080 eos.ShapeType() == TopAbs_FACE ? TopAbs_EDGE : TopAbs_VERTEX );
5081 for ( ; !toIgnore && sub.More(); sub.Next() )
5082 // is adjacent - has a common EDGE or VERTEX
5083 toIgnore = ( helper.IsSubShape( sub.Current(), S ));
5085 if ( toIgnore ) // check angle between normals
5088 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
5089 toIgnore = ( normal * eos._edges[i]->_normal > -0.5 );
5093 if ( !toIgnore ) // check if the edge is a neighbor of intFace
5095 for ( size_t iN = 0; !toIgnore && iN < eos._edges[i]->_neibors.size(); ++iN )
5097 int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
5098 toIgnore = ( nInd >= 0 );
5105 // intersection not ignored
5107 if ( toBlockInfaltion &&
5108 dist < ( eos._edges[i]->_len * theThickToIntersection ))
5110 if ( is1stBlocked ) { is1stBlocked = false; // debug
5111 dumpFunction(SMESH_Comment("blockIntersected") <<data._index<<"_InfStep"<<infStep);
5113 eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5114 eos._edges[i]->Block( data ); // not to inflate
5116 //if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5118 // block _LayerEdge's, on top of which intFace is
5119 if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5121 const SMDS_MeshElement* srcFace = f->_srcFace;
5122 SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5123 while ( nIt->more() )
5125 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5126 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5127 if ( n2e != data._n2eMap.end() )
5128 n2e->second->Block( data );
5134 if ( isShorterDist )
5136 distToIntersection = dist;
5138 closestFace = intFace;
5141 } // if ( toBlockInfaltion || isShorterDist )
5142 } // loop on eos._edges
5143 } // loop on data._edgesOnShape
5145 if ( !is1stBlocked )
5148 if ( closestFace && le )
5151 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5152 cout << "#Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5153 << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5154 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5155 << ") distance = " << distToIntersection<< endl;
5162 //================================================================================
5164 * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5165 * \param [in,out] badSmooEdges - _LayerEdge's to fix
5166 * \return int - resulting nb of bad _LayerEdge's
5168 //================================================================================
5170 int _ViscousBuilder::invalidateBadSmooth( _SolidData& data,
5171 SMESH_MesherHelper& helper,
5172 vector< _LayerEdge* >& badSmooEdges,
5173 vector< _EdgesOnShape* >& eosC1,
5176 if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5178 dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5181 INVALIDATED = _LayerEdge::UNUSED_FLAG,
5182 TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5183 ADDED = _LayerEdge::UNUSED_FLAG * 4
5185 data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5188 bool haveInvalidated = true;
5189 while ( haveInvalidated )
5191 haveInvalidated = false;
5192 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5194 _LayerEdge* edge = badSmooEdges[i];
5195 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5197 bool invalidated = false;
5198 if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5200 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5201 edge->Block( data );
5202 edge->Set( INVALIDATED );
5203 edge->Unset( TO_INVALIDATE );
5205 haveInvalidated = true;
5208 // look for _LayerEdge's of bad _simplices
5210 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5211 gp_XYZ prevXYZ1 = edge->PrevCheckPos( eos );
5212 //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5213 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5215 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5216 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5220 _LayerEdge* ee[2] = { 0,0 };
5221 for ( size_t iN = 0; iN < edge->_neibors.size() && !ee[1] ; ++iN )
5222 if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5223 ee[ ee[0] != 0 ] = edge->_neibors[iN];
5225 int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5226 while ( maxNbSteps > edge->NbSteps() && isBad )
5229 for ( int iE = 0; iE < 2; ++iE )
5231 if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5232 ee[ iE ]->NbSteps() > 1 )
5234 _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5235 ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5236 ee[ iE ]->Block( data );
5237 ee[ iE ]->Set( INVALIDATED );
5238 haveInvalidated = true;
5241 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5242 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5246 if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5247 if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5248 ee[0]->Set( ADDED );
5249 ee[1]->Set( ADDED );
5252 ee[0]->Set( TO_INVALIDATE );
5253 ee[1]->Set( TO_INVALIDATE );
5257 if ( !invalidated && nbBad > 0 && edge->NbSteps() > 1 )
5259 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5260 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5261 edge->Block( data );
5262 edge->Set( INVALIDATED );
5263 edge->Unset( TO_INVALIDATE );
5264 haveInvalidated = true;
5266 } // loop on badSmooEdges
5267 } // while ( haveInvalidated )
5269 // re-smooth on analytical EDGEs
5270 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5272 _LayerEdge* edge = badSmooEdges[i];
5273 if ( !edge->Is( INVALIDATED )) continue;
5275 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5276 if ( eos->ShapeType() == TopAbs_VERTEX )
5278 PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5279 while ( const TopoDS_Shape* e = eIt->next() )
5280 if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5281 if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5283 // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5284 // if ( eoe->SWOLType() == TopAbs_FACE ) {
5285 // F = TopoDS::Face( eoe->_sWOL );
5286 // surface = helper.GetSurface( F );
5288 // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5289 eoe->_edgeSmoother->_anaCurve.Nullify();
5295 // check result of invalidation
5298 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5300 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5302 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5303 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5304 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5305 gp_XYZ prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5306 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5307 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5310 debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5311 << " "<< tgtXYZ._node->GetID()
5312 << " "<< edge->_simplices[j]._nPrev->GetID()
5313 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5322 //================================================================================
5324 * \brief Create an offset surface
5326 //================================================================================
5328 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5330 if ( eos._offsetSurf.IsNull() ||
5331 eos._edgeForOffset == 0 ||
5332 eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5335 Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5338 gp_Pnt tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5339 /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5340 double offset = baseSurface->Gap();
5342 eos._offsetSurf.Nullify();
5346 BRepOffsetAPI_MakeOffsetShape offsetMaker;
5347 offsetMaker.PerformByJoin( eos._shape, -offset, Precision::Confusion() );
5348 if ( !offsetMaker.IsDone() ) return;
5350 TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5351 if ( !fExp.More() ) return;
5353 TopoDS_Face F = TopoDS::Face( fExp.Current() );
5354 Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5355 if ( surf.IsNull() ) return;
5357 eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5359 catch ( Standard_Failure )
5364 //================================================================================
5366 * \brief Put nodes of a curved FACE to its offset surface
5368 //================================================================================
5370 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape& eos,
5372 vector< _EdgesOnShape* >& eosC1,
5376 _EdgesOnShape * eof = & eos;
5377 if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5380 for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5382 if ( eosC1[i]->_offsetSurf.IsNull() ||
5383 eosC1[i]->ShapeType() != TopAbs_FACE ||
5384 eosC1[i]->_edgeForOffset == 0 ||
5385 eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5387 if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5392 eof->_offsetSurf.IsNull() ||
5393 eof->ShapeType() != TopAbs_FACE ||
5394 eof->_edgeForOffset == 0 ||
5395 eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5398 double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5399 for ( size_t i = 0; i < eos._edges.size(); ++i )
5401 _LayerEdge* edge = eos._edges[i];
5402 edge->Unset( _LayerEdge::MARKED );
5403 if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5405 if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5407 if ( !edge->Is( _LayerEdge::UPD_NORMAL_CONV ))
5410 else if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5413 int nbBlockedAround = 0;
5414 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5415 nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5416 if ( nbBlockedAround > 1 )
5419 gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5420 gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5421 if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5422 edge->_curvature->_uv = uv;
5423 if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5425 gp_XYZ newP = eof->_offsetSurf->Value( uv ).XYZ();
5426 gp_XYZ prevP = edge->PrevCheckPos();
5429 for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5431 ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5435 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5436 n->setXYZ( newP.X(), newP.Y(), newP.Z());
5437 edge->_pos.back() = newP;
5439 edge->Set( _LayerEdge::MARKED );
5440 if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5442 edge->_normal = ( newP - prevP ).Normalized();
5450 // dumpMove() for debug
5452 for ( ; i < eos._edges.size(); ++i )
5453 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5455 if ( i < eos._edges.size() )
5457 dumpFunction(SMESH_Comment("putOnOffsetSurface_S") << eos._shapeID
5458 << "_InfStep" << infStep << "_" << smooStep );
5459 for ( ; i < eos._edges.size(); ++i )
5461 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5462 dumpMove( eos._edges[i]->_nodes.back() );
5468 _ConvexFace* cnvFace;
5469 if ( moveAll != _LayerEdge::UPD_NORMAL_CONV &&
5470 eos.ShapeType() == TopAbs_FACE &&
5471 (cnvFace = eos.GetData().GetConvexFace( eos._shapeID )) &&
5472 !cnvFace->_normalsFixedOnBorders )
5474 // put on the surface nodes built on FACE boundaries
5475 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5476 while ( smIt->more() )
5478 SMESH_subMesh* sm = smIt->next();
5479 _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5480 if ( !subEOS->_sWOL.IsNull() ) continue;
5481 if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5483 putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::UPD_NORMAL_CONV );
5485 cnvFace->_normalsFixedOnBorders = true;
5489 //================================================================================
5491 * \brief Return a curve of the EDGE to be used for smoothing and arrange
5492 * _LayerEdge's to be in a consequent order
5494 //================================================================================
5496 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge& E,
5498 SMESH_MesherHelper& helper)
5500 SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5502 TopLoc_Location loc; double f,l;
5504 Handle(Geom_Line) line;
5505 Handle(Geom_Circle) circle;
5506 bool isLine, isCirc;
5507 if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5509 // check if the EDGE is a line
5510 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5511 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5512 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5514 line = Handle(Geom_Line)::DownCast( curve );
5515 circle = Handle(Geom_Circle)::DownCast( curve );
5516 isLine = (!line.IsNull());
5517 isCirc = (!circle.IsNull());
5519 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5521 isLine = SMESH_Algo::IsStraight( E );
5524 line = new Geom_Line( gp::OX() ); // only type does matter
5526 if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5531 else //////////////////////////////////////////////////////////////////////// 2D case
5533 if ( !eos._isRegularSWOL ) // 23190
5536 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5538 // check if the EDGE is a line
5539 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5540 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5541 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5543 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
5544 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5545 isLine = (!line2d.IsNull());
5546 isCirc = (!circle2d.IsNull());
5548 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5551 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5552 while ( nIt->more() )
5553 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5554 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5556 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5557 for ( int i = 0; i < 2 && !isLine; ++i )
5558 isLine = ( size.Coord( i+1 ) <= lineTol );
5560 if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5566 line = new Geom_Line( gp::OX() ); // only type does matter
5570 gp_Pnt2d p = circle2d->Location();
5571 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5572 circle = new Geom_Circle( ax, 1.); // only center position does matter
5581 return Handle(Geom_Curve)();
5584 //================================================================================
5586 * \brief Smooth edges on EDGE
5588 //================================================================================
5590 bool _Smoother1D::Perform(_SolidData& data,
5591 Handle(ShapeAnalysis_Surface)& surface,
5592 const TopoDS_Face& F,
5593 SMESH_MesherHelper& helper )
5595 if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
5598 findEdgesToSmooth();
5600 return smoothAnalyticEdge( data, surface, F, helper );
5602 return smoothComplexEdge ( data, surface, F, helper );
5605 //================================================================================
5607 * \brief Find edges to smooth
5609 //================================================================================
5611 void _Smoother1D::findEdgesToSmooth()
5613 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5614 for ( int iEnd = 0; iEnd < 2; ++iEnd )
5615 if ( leOnV[iEnd]->Is( _LayerEdge::NORMAL_UPDATED ))
5616 _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
5618 _eToSmooth[0].first = _eToSmooth[0].second = 0;
5620 for ( size_t i = 0; i < _eos.size(); ++i )
5622 if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5624 if ( needSmoothing( _leOnV[0]._cosin,
5625 _eos[i]->_len * leOnV[0]->_lenFactor, _curveLen * _leParams[i] ) ||
5628 _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5632 _eToSmooth[0].second = i+1;
5635 _eToSmooth[1].first = _eToSmooth[1].second = _eos.size();
5637 for ( int i = _eos.size() - 1; i >= _eToSmooth[0].second; --i )
5639 if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5641 if ( needSmoothing( _leOnV[1]._cosin,
5642 _eos[i]->_len * leOnV[1]->_lenFactor, _curveLen * ( 1.-_leParams[i] )) ||
5644 _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5648 _eToSmooth[1].first = i;
5652 //================================================================================
5654 * \brief Check if iE-th _LayerEdge needs smoothing
5656 //================================================================================
5658 bool _Smoother1D::isToSmooth( int iE )
5660 SMESH_NodeXYZ pi( _eos[iE]->_nodes[0] );
5661 SMESH_NodeXYZ p0( _eos[iE]->_2neibors->srcNode(0) );
5662 SMESH_NodeXYZ p1( _eos[iE]->_2neibors->srcNode(1) );
5663 gp_XYZ seg0 = pi - p0;
5664 gp_XYZ seg1 = p1 - pi;
5665 gp_XYZ tangent = seg0 + seg1;
5666 double tangentLen = tangent.Modulus();
5667 double segMinLen = Min( seg0.Modulus(), seg1.Modulus() );
5668 if ( tangentLen < std::numeric_limits<double>::min() )
5670 tangent /= tangentLen;
5672 for ( size_t i = 0; i < _eos[iE]->_neibors.size(); ++i )
5674 _LayerEdge* ne = _eos[iE]->_neibors[i];
5675 if ( !ne->Is( _LayerEdge::TO_SMOOTH ) ||
5676 ne->_nodes.size() < 2 ||
5677 ne->_nodes[0]->GetPosition()->GetDim() != 2 )
5679 gp_XYZ edgeVec = SMESH_NodeXYZ( ne->_nodes.back() ) - SMESH_NodeXYZ( ne->_nodes[0] );
5680 double proj = edgeVec * tangent;
5681 if ( needSmoothing( 1., proj, segMinLen ))
5687 //================================================================================
5689 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5691 //================================================================================
5693 bool _Smoother1D::smoothAnalyticEdge( _SolidData& data,
5694 Handle(ShapeAnalysis_Surface)& surface,
5695 const TopoDS_Face& F,
5696 SMESH_MesherHelper& helper)
5698 if ( !isAnalytic() ) return false;
5700 size_t iFrom = 0, iTo = _eos._edges.size();
5702 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5704 if ( F.IsNull() ) // 3D
5706 SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5707 SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5708 //const gp_XYZ lineDir = pSrc1 - pSrc0;
5709 //_LayerEdge* vLE0 = getLEdgeOnV( 0 );
5710 //_LayerEdge* vLE1 = getLEdgeOnV( 1 );
5711 // bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5712 // vLE0->Is( _LayerEdge::BLOCKED ) ||
5713 // vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5714 // vLE1->Is( _LayerEdge::BLOCKED ));
5715 for ( int iEnd = 0; iEnd < 2; ++iEnd )
5717 iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5718 if ( iFrom >= iTo ) continue;
5719 SMESH_TNodeXYZ p0( _eos[iFrom]->_2neibors->tgtNode(0) );
5720 SMESH_TNodeXYZ p1( _eos[iTo-1]->_2neibors->tgtNode(1) );
5721 double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5722 double param1 = _leParams[ iTo ];
5723 for ( size_t i = iFrom; i < iTo; ++i )
5725 _LayerEdge* edge = _eos[i];
5726 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5727 double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5728 gp_XYZ newPos = p0 * ( 1. - param ) + p1 * param;
5730 // if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5732 // gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5733 // double shift = ( lineDir * ( newPos - pSrc0 ) -
5734 // lineDir * ( curPos - pSrc0 ));
5735 // newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5737 if ( edge->Is( _LayerEdge::BLOCKED ))
5739 SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5740 double curThick = pSrc.SquareDistance( tgtNode );
5741 double newThink = ( pSrc - newPos ).SquareModulus();
5742 if ( newThink > curThick )
5745 edge->_pos.back() = newPos;
5746 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5747 dumpMove( tgtNode );
5753 _LayerEdge* eV0 = getLEdgeOnV( 0 );
5754 _LayerEdge* eV1 = getLEdgeOnV( 1 );
5755 gp_XY uvV0 = eV0->LastUV( F, *data.GetShapeEdges( eV0 ));
5756 gp_XY uvV1 = eV1->LastUV( F, *data.GetShapeEdges( eV1 ));
5757 if ( eV0->_nodes.back() == eV1->_nodes.back() ) // closed edge
5759 int iPeriodic = helper.GetPeriodicIndex();
5760 if ( iPeriodic == 1 || iPeriodic == 2 )
5762 uvV1.SetCoord( iPeriodic, helper.GetOtherParam( uvV1.Coord( iPeriodic )));
5763 if ( uvV0.Coord( iPeriodic ) > uvV1.Coord( iPeriodic ))
5764 std::swap( uvV0, uvV1 );
5767 for ( int iEnd = 0; iEnd < 2; ++iEnd )
5769 iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5770 if ( iFrom >= iTo ) continue;
5771 _LayerEdge* e0 = _eos[iFrom]->_2neibors->_edges[0];
5772 _LayerEdge* e1 = _eos[iTo-1]->_2neibors->_edges[1];
5773 gp_XY uv0 = ( e0 == eV0 ) ? uvV0 : e0->LastUV( F, _eos );
5774 gp_XY uv1 = ( e1 == eV1 ) ? uvV1 : e1->LastUV( F, _eos );
5775 double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5776 double param1 = _leParams[ iTo ];
5777 gp_XY rangeUV = uv1 - uv0;
5778 for ( size_t i = iFrom; i < iTo; ++i )
5780 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5781 double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5782 gp_XY newUV = uv0 + param * rangeUV;
5784 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5785 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
5786 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5787 dumpMove( tgtNode );
5789 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
5790 pos->SetUParameter( newUV.X() );
5791 pos->SetVParameter( newUV.Y() );
5793 gp_XYZ newUV0( newUV.X(), newUV.Y(), 0 );
5795 if ( !_eos[i]->Is( _LayerEdge::SMOOTHED ))
5797 _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5798 if ( _eos[i]->_pos.size() > 2 )
5800 // modify previous positions to make _LayerEdge less sharply bent
5801 vector<gp_XYZ>& uvVec = _eos[i]->_pos;
5802 const gp_XYZ uvShift = newUV0 - uvVec.back();
5803 const double len2 = ( uvVec.back() - uvVec[ 0 ] ).SquareModulus();
5804 int iPrev = uvVec.size() - 2;
5807 double r = ( uvVec[ iPrev ] - uvVec[0] ).SquareModulus() / len2;
5808 uvVec[ iPrev ] += uvShift * r;
5813 _eos[i]->_pos.back() = newUV0;
5820 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5822 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5823 gp_Pnt center3D = circle->Location();
5825 if ( F.IsNull() ) // 3D
5827 if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5828 return true; // closed EDGE - nothing to do
5830 // circle is a real curve of EDGE
5831 gp_Circ circ = circle->Circ();
5833 // new center is shifted along its axis
5834 const gp_Dir& axis = circ.Axis().Direction();
5835 _LayerEdge* e0 = getLEdgeOnV(0);
5836 _LayerEdge* e1 = getLEdgeOnV(1);
5837 SMESH_TNodeXYZ p0 = e0->_nodes.back();
5838 SMESH_TNodeXYZ p1 = e1->_nodes.back();
5839 double shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5840 double shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5841 gp_Pnt newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5843 double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5845 gp_Ax2 newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5846 gp_Circ newCirc( newAxis, newRadius );
5847 gp_Vec vecC1 ( newCenter, p1 );
5849 double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5853 for ( size_t i = 0; i < _eos.size(); ++i )
5855 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5856 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5857 double u = uLast * _leParams[i];
5858 gp_Pnt p = ElCLib::Value( u, newCirc );
5859 _eos._edges[i]->_pos.back() = p.XYZ();
5861 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5862 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5863 dumpMove( tgtNode );
5869 const gp_XY center( center3D.X(), center3D.Y() );
5871 _LayerEdge* e0 = getLEdgeOnV(0);
5872 _LayerEdge* eM = _eos._edges[ 0 ];
5873 _LayerEdge* e1 = getLEdgeOnV(1);
5874 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5875 gp_XY uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5876 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5877 gp_Vec2d vec0( center, uv0 );
5878 gp_Vec2d vecM( center, uvM );
5879 gp_Vec2d vec1( center, uv1 );
5880 double uLast = vec0.Angle( vec1 ); // -PI - +PI
5881 double uMidl = vec0.Angle( vecM );
5882 if ( uLast * uMidl <= 0. )
5883 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5884 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5886 gp_Ax2d axis( center, vec0 );
5887 gp_Circ2d circ( axis, radius );
5888 for ( size_t i = 0; i < _eos.size(); ++i )
5890 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5891 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5892 double newU = uLast * _leParams[i];
5893 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5894 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5896 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5897 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5898 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5899 dumpMove( tgtNode );
5901 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
5902 pos->SetUParameter( newUV.X() );
5903 pos->SetVParameter( newUV.Y() );
5905 _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5914 //================================================================================
5916 * \brief smooth _LayerEdge's on a an EDGE
5918 //================================================================================
5920 bool _Smoother1D::smoothComplexEdge( _SolidData& data,
5921 Handle(ShapeAnalysis_Surface)& surface,
5922 const TopoDS_Face& F,
5923 SMESH_MesherHelper& helper)
5925 if ( _offPoints.empty() )
5928 // ----------------------------------------------
5929 // move _offPoints along normals of _LayerEdge's
5930 // ----------------------------------------------
5932 _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5933 if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5934 _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5935 if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED ))
5936 _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5937 _leOnV[0]._len = e[0]->_len;
5938 _leOnV[1]._len = e[1]->_len;
5939 for ( size_t i = 0; i < _offPoints.size(); i++ )
5941 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
5942 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
5943 const double w0 = _offPoints[i]._2edges._wgt[0];
5944 const double w1 = _offPoints[i]._2edges._wgt[1];
5945 gp_XYZ avgNorm = ( e0->_normal * w0 + e1->_normal * w1 ).Normalized();
5946 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
5947 double avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5948 if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5949 e1->Is( _LayerEdge::NORMAL_UPDATED ))
5950 avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5952 _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5953 _offPoints[i]._len = avgLen;
5957 if ( !surface.IsNull() ) // project _offPoints to the FACE
5959 fTol = 100 * BRep_Tool::Tolerance( F );
5960 //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5962 gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5963 //if ( surface->Gap() < 0.5 * segLen )
5964 _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5966 for ( size_t i = 1; i < _offPoints.size(); ++i )
5968 uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5969 //if ( surface->Gap() < 0.5 * segLen )
5970 _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5974 // -----------------------------------------------------------------
5975 // project tgt nodes of extreme _LayerEdge's to the offset segments
5976 // -----------------------------------------------------------------
5978 const int updatedOrBlocked = _LayerEdge::NORMAL_UPDATED | _LayerEdge::BLOCKED;
5979 if ( e[0]->Is( updatedOrBlocked )) _iSeg[0] = 0;
5980 if ( e[1]->Is( updatedOrBlocked )) _iSeg[1] = _offPoints.size()-2;
5982 gp_Pnt pExtreme[2], pProj[2];
5983 bool isProjected[2];
5984 for ( int is2nd = 0; is2nd < 2; ++is2nd )
5986 pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5987 int i = _iSeg[ is2nd ];
5988 int di = is2nd ? -1 : +1;
5989 bool & projected = isProjected[ is2nd ];
5991 double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5994 gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ] );
5995 gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5996 uOnSeg = ( v0p * v01 ) / v01.SquareMagnitude(); // param [0,1] along v01
5997 projected = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5998 dist = pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5999 if ( dist < distMin || projected )
6002 pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
6005 else if ( dist > distPrev )
6007 if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
6013 while ( !projected &&
6014 i >= 0 && i+1 < (int)_offPoints.size() );
6018 if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
6021 _iSeg[1] = _offPoints.size()-2;
6022 debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
6027 if ( _iSeg[0] > _iSeg[1] )
6029 debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
6033 // adjust length of extreme LE (test viscous_layers_01/B7)
6034 gp_Vec vDiv0( pExtreme[0], pProj[0] );
6035 gp_Vec vDiv1( pExtreme[1], pProj[1] );
6036 double d0 = vDiv0.Magnitude();
6037 double d1 = isProjected[1] ? vDiv1.Magnitude() : 0;
6038 if ( e[0]->Is( _LayerEdge::BLOCKED )) {
6039 if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
6040 else e[0]->_len -= d0;
6042 if ( e[1]->Is( _LayerEdge::BLOCKED )) {
6043 if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
6044 else e[1]->_len -= d1;
6047 // ---------------------------------------------------------------------------------
6048 // compute normalized length of the offset segments located between the projections
6049 // ---------------------------------------------------------------------------------
6051 // temporary replace extreme _offPoints by pExtreme
6052 gp_XYZ opXYZ[2] = { _offPoints[ _iSeg[0] ]._xyz,
6053 _offPoints[ _iSeg[1]+1 ]._xyz };
6054 _offPoints[ _iSeg[0] ]._xyz = pExtreme[0].XYZ();
6055 _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
6057 size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
6058 vector< double > len( nbSeg + 1 );
6060 len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
6061 for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
6063 len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
6065 // if ( isProjected[ 1 ])
6066 // len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6068 // len[ nbSeg ] += pExtreme[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6070 double fullLen = len.back() - d0 - d1;
6071 for ( iSeg = 0; iSeg < len.size(); ++iSeg )
6072 len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
6074 // -------------------------------------------------------------
6075 // distribute tgt nodes of _LayerEdge's between the projections
6076 // -------------------------------------------------------------
6079 for ( size_t i = 0; i < _eos.size(); ++i )
6081 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6082 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6083 while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
6085 double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
6086 gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0] ]._xyz * ( 1 - r ) +
6087 _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
6089 if ( surface.IsNull() )
6091 _eos[i]->_pos.back() = p;
6093 else // project a new node position to a FACE
6095 gp_Pnt2d uv ( _eos[i]->_pos.back().X(), _eos[i]->_pos.back().Y() );
6096 gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
6098 p = surface->Value( uv2 ).XYZ();
6099 _eos[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
6101 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6102 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6103 dumpMove( tgtNode );
6106 _offPoints[ _iSeg[0] ]._xyz = opXYZ[0];
6107 _offPoints[ _iSeg[1]+1 ]._xyz = opXYZ[1];
6112 //================================================================================
6114 * \brief Prepare for smoothing
6116 //================================================================================
6118 void _Smoother1D::prepare(_SolidData& data)
6120 const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
6121 _curveLen = SMESH_Algo::EdgeLength( E );
6123 // sort _LayerEdge's by position on the EDGE
6124 data.SortOnEdge( E, _eos._edges );
6126 // compute normalized param of _eos._edges on EDGE
6127 _leParams.resize( _eos._edges.size() + 1 );
6130 gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
6132 for ( size_t i = 0; i < _eos._edges.size(); ++i )
6134 gp_Pnt p = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
6135 curLen = p.Distance( pPrev );
6136 _leParams[i+1] = _leParams[i] + curLen;
6139 double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
6140 for ( size_t i = 0; i < _leParams.size()-1; ++i )
6141 _leParams[i] = _leParams[i+1] / fullLen;
6142 _leParams.back() = 1.;
6145 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6147 // get cosin to use in findEdgesToSmooth()
6148 _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
6149 _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
6150 _leOnV[0]._cosin = Abs( leOnV[0]->_cosin );
6151 _leOnV[1]._cosin = Abs( leOnV[1]->_cosin );
6152 if ( _eos._sWOL.IsNull() ) // 3D
6153 for ( int iEnd = 0; iEnd < 2; ++iEnd )
6154 _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6159 // divide E to have offset segments with low deflection
6160 BRepAdaptor_Curve c3dAdaptor( E );
6161 const double curDeflect = 0.1; //0.01; // Curvature deflection == |p1p2]*sin(p1p2,p1pM)
6162 const double angDeflect = 0.1; //0.09; // Angular deflection == sin(p1pM,pMp2)
6163 GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
6164 if ( discret.NbPoints() <= 2 )
6166 _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
6170 const double u0 = c3dAdaptor.FirstParameter();
6171 gp_Pnt p; gp_Vec tangent;
6172 if ( discret.NbPoints() >= (int) _eos.size() + 2 )
6174 _offPoints.resize( discret.NbPoints() );
6175 for ( size_t i = 0; i < _offPoints.size(); i++ )
6177 double u = discret.Parameter( i+1 );
6178 c3dAdaptor.D1( u, p, tangent );
6179 _offPoints[i]._xyz = p.XYZ();
6180 _offPoints[i]._edgeDir = tangent.XYZ();
6181 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6186 std::vector< double > params( _eos.size() + 2 );
6188 params[0] = data.GetHelper().GetNodeU( E, leOnV[0]->_nodes[0] );
6189 params.back() = data.GetHelper().GetNodeU( E, leOnV[1]->_nodes[0] );
6190 for ( size_t i = 0; i < _eos.size(); i++ )
6191 params[i+1] = data.GetHelper().GetNodeU( E, _eos[i]->_nodes[0] );
6193 if ( params[1] > params[ _eos.size() ] )
6194 std::reverse( params.begin() + 1, params.end() - 1 );
6196 _offPoints.resize( _eos.size() + 2 );
6197 for ( size_t i = 0; i < _offPoints.size(); i++ )
6199 const double u = params[i];
6200 c3dAdaptor.D1( u, p, tangent );
6201 _offPoints[i]._xyz = p.XYZ();
6202 _offPoints[i]._edgeDir = tangent.XYZ();
6203 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6208 _offPoints [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
6209 _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
6210 _2NearEdges tmp2edges;
6211 tmp2edges._edges[1] = _eos._edges[0];
6212 _leOnV[0]._2neibors = & tmp2edges;
6213 _leOnV[0]._nodes = leOnV[0]->_nodes;
6214 _leOnV[1]._nodes = leOnV[1]->_nodes;
6215 _LayerEdge* eNext, *ePrev = & _leOnV[0];
6216 for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
6218 // find _LayerEdge's located before and after an offset point
6219 // (_eos._edges[ iLE ] is next after ePrev)
6220 while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
6221 ePrev = _eos._edges[ iLE++ ];
6222 eNext = ePrev->_2neibors->_edges[1];
6224 gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
6225 gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
6226 double r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
6227 _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
6230 // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
6231 for ( size_t i = 0; i < _offPoints.size(); i++ )
6232 if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
6233 _offPoints[i]._2edges._edges[0] = & _leOnV[0];
6235 for ( size_t i = _offPoints.size()-1; i > 0; i-- )
6236 if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
6237 _offPoints[i]._2edges._edges[1] = & _leOnV[1];
6240 // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
6242 int iLBO = _offPoints.size() - 2; // last but one
6244 if ( leOnV[ 0 ]->Is( _LayerEdge::MULTI_NORMAL ))
6245 _leOnV[ 0 ]._normal = getNormalNormal( _eos._edges[1]->_normal, _edgeDir[0] );
6247 _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
6248 if ( leOnV[ 1 ]->Is( _LayerEdge::MULTI_NORMAL ))
6249 _leOnV[ 1 ]._normal = getNormalNormal( _eos._edges.back()->_normal, _edgeDir[1] );
6251 _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
6252 _leOnV[ 0 ]._len = 0;
6253 _leOnV[ 1 ]._len = 0;
6254 _leOnV[ 0 ]._lenFactor = _offPoints[1 ]._2edges._edges[1]->_lenFactor;
6255 _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
6258 _iSeg[1] = _offPoints.size()-2;
6260 // initialize OffPnt::_len
6261 for ( size_t i = 0; i < _offPoints.size(); ++i )
6262 _offPoints[i]._len = 0;
6264 if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
6266 _leOnV[0]._len = leOnV[0]->_len;
6267 _leOnV[1]._len = leOnV[1]->_len;
6268 for ( size_t i = 0; i < _offPoints.size(); i++ )
6270 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
6271 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
6272 const double w0 = _offPoints[i]._2edges._wgt[0];
6273 const double w1 = _offPoints[i]._2edges._wgt[1];
6274 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
6275 gp_XYZ avgXYZ = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
6276 SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
6277 _offPoints[i]._xyz = avgXYZ;
6278 _offPoints[i]._len = avgLen;
6283 //================================================================================
6285 * \brief return _normal of _leOnV[is2nd] normal to the EDGE
6287 //================================================================================
6289 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
6290 const gp_XYZ& edgeDir)
6292 gp_XYZ cross = normal ^ edgeDir;
6293 gp_XYZ norm = edgeDir ^ cross;
6294 double size = norm.Modulus();
6296 // if ( size == 0 ) // MULTI_NORMAL _LayerEdge
6297 // return gp_XYZ( 1e-100, 1e-100, 1e-100 );
6302 //================================================================================
6304 * \brief Writes a script creating a mesh composed of _offPoints
6306 //================================================================================
6308 void _Smoother1D::offPointsToPython() const
6310 const char* fname = "/tmp/offPoints.py";
6311 cout << "execfile('"<<fname<<"')"<<endl;
6313 py << "import SMESH" << endl
6314 << "from salome.smesh import smeshBuilder" << endl
6315 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
6316 << "mesh = smesh.Mesh( 'offPoints' )"<<endl;
6317 for ( size_t i = 0; i < _offPoints.size(); i++ )
6319 py << "mesh.AddNode( "
6320 << _offPoints[i]._xyz.X() << ", "
6321 << _offPoints[i]._xyz.Y() << ", "
6322 << _offPoints[i]._xyz.Z() << " )" << endl;
6326 //================================================================================
6328 * \brief Sort _LayerEdge's by a parameter on a given EDGE
6330 //================================================================================
6332 void _SolidData::SortOnEdge( const TopoDS_Edge& E,
6333 vector< _LayerEdge* >& edges)
6335 map< double, _LayerEdge* > u2edge;
6336 for ( size_t i = 0; i < edges.size(); ++i )
6337 u2edge.insert( u2edge.end(),
6338 make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
6340 ASSERT( u2edge.size() == edges.size() );
6341 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
6342 for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
6343 edges[i] = u2e->second;
6345 Sort2NeiborsOnEdge( edges );
6348 //================================================================================
6350 * \brief Set _2neibors according to the order of _LayerEdge on EDGE
6352 //================================================================================
6354 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
6356 if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
6358 for ( size_t i = 0; i < edges.size()-1; ++i )
6359 if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
6360 edges[i]->_2neibors->reverse();
6362 const size_t iLast = edges.size() - 1;
6363 if ( edges.size() > 1 &&
6364 edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
6365 edges[iLast]->_2neibors->reverse();
6368 //================================================================================
6370 * \brief Return _EdgesOnShape* corresponding to the shape
6372 //================================================================================
6374 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6376 if ( shapeID < (int)_edgesOnShape.size() &&
6377 _edgesOnShape[ shapeID ]._shapeID == shapeID )
6378 return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6380 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6381 if ( _edgesOnShape[i]._shapeID == shapeID )
6382 return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6387 //================================================================================
6389 * \brief Return _EdgesOnShape* corresponding to the shape
6391 //================================================================================
6393 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6395 SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6396 return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6399 //================================================================================
6401 * \brief Prepare data of the _LayerEdge for smoothing on FACE
6403 //================================================================================
6405 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6407 SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6409 set< TGeomID > vertices;
6411 if ( eos->ShapeType() == TopAbs_FACE )
6413 // check FACE concavity and get concave VERTEXes
6414 F = TopoDS::Face( eos->_shape );
6415 if ( isConcave( F, helper, &vertices ))
6416 _concaveFaces.insert( eos->_shapeID );
6418 // set eos._eosConcaVer
6419 eos->_eosConcaVer.clear();
6420 eos->_eosConcaVer.reserve( vertices.size() );
6421 for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6423 _EdgesOnShape* eov = GetShapeEdges( *v );
6424 if ( eov && eov->_edges.size() == 1 )
6426 eos->_eosConcaVer.push_back( eov );
6427 for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6428 eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6432 // SetSmooLen() to _LayerEdge's on FACE
6433 // for ( size_t i = 0; i < eos->_edges.size(); ++i )
6435 // eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6437 // SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6438 // while ( smIt->more() ) // loop on sub-shapes of the FACE
6440 // _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6441 // if ( !eoe ) continue;
6443 // vector<_LayerEdge*>& eE = eoe->_edges;
6444 // for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6446 // if ( eE[iE]->_cosin <= theMinSmoothCosin )
6449 // SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6450 // while ( segIt->more() )
6452 // const SMDS_MeshElement* seg = segIt->next();
6453 // if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6455 // if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6456 // continue; // not to check a seg twice
6457 // for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6459 // _LayerEdge* eN = eE[iE]->_neibors[iN];
6460 // if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6462 // double dist = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6463 // double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6464 // eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6465 // eN->Set( _LayerEdge::NEAR_BOUNDARY );
6470 } // if ( eos->ShapeType() == TopAbs_FACE )
6472 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6474 eos->_edges[i]->_smooFunction = 0;
6475 eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6477 bool isCurved = false;
6478 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6480 _LayerEdge* edge = eos->_edges[i];
6482 // get simplices sorted
6483 _Simplex::SortSimplices( edge->_simplices );
6485 // smoothing function
6486 edge->ChooseSmooFunction( vertices, _n2eMap );
6489 double avgNormProj = 0, avgLen = 0;
6490 for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6492 _Simplex& s = edge->_simplices[iS];
6494 gp_XYZ vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6495 avgNormProj += edge->_normal * vec;
6496 avgLen += vec.Modulus();
6497 if ( substituteSrcNodes )
6499 s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6500 s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6503 avgNormProj /= edge->_simplices.size();
6504 avgLen /= edge->_simplices.size();
6505 if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6507 edge->Set( _LayerEdge::SMOOTHED_C1 );
6509 SMDS_FacePositionPtr fPos = edge->_nodes[0]->GetPosition();
6511 for ( size_t iS = 0; iS < edge->_simplices.size() && !fPos; ++iS )
6512 fPos = edge->_simplices[iS]._nPrev->GetPosition();
6514 edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6518 // prepare for putOnOffsetSurface()
6519 if (( eos->ShapeType() == TopAbs_FACE ) &&
6520 ( isCurved || !eos->_eosConcaVer.empty() ))
6522 eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6523 eos->_edgeForOffset = 0;
6525 double maxCosin = -1;
6526 for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6528 _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6529 if ( !eoe || eoe->_edges.empty() ) continue;
6531 vector<_LayerEdge*>& eE = eoe->_edges;
6532 _LayerEdge* e = eE[ eE.size() / 2 ];
6533 if ( e->_cosin > maxCosin )
6535 eos->_edgeForOffset = e;
6536 maxCosin = e->_cosin;
6542 //================================================================================
6544 * \brief Add faces for smoothing
6546 //================================================================================
6548 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6549 const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6551 set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6552 for ( ; eos != eosToSmooth.end(); ++eos )
6554 if ( !*eos || (*eos)->_toSmooth ) continue;
6556 (*eos)->_toSmooth = true;
6558 if ( (*eos)->ShapeType() == TopAbs_FACE )
6560 PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6561 (*eos)->_toSmooth = true;
6565 // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6566 if ( edgesNoAnaSmooth )
6567 for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6569 if ( (*eos)->_edgeSmoother )
6570 (*eos)->_edgeSmoother->_anaCurve.Nullify();
6574 //================================================================================
6576 * \brief Limit _LayerEdge::_maxLen according to local curvature
6578 //================================================================================
6580 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6582 // find intersection of neighbor _LayerEdge's to limit _maxLen
6583 // according to local curvature (IPAL52648)
6585 // This method must be called after findCollisionEdges() where _LayerEdge's
6586 // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6588 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6590 _EdgesOnShape& eosI = data._edgesOnShape[iS];
6591 if ( eosI._edges.empty() ) continue;
6592 if ( !eosI._hyp.ToSmooth() )
6594 for ( size_t i = 0; i < eosI._edges.size(); ++i )
6596 _LayerEdge* eI = eosI._edges[i];
6597 for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6599 _LayerEdge* eN = eI->_neibors[iN];
6600 if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6602 _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6603 limitMaxLenByCurvature( eI, eN, eosI, *eosN, eosI._hyp.ToSmooth() );
6608 else if ( eosI.ShapeType() == TopAbs_EDGE )
6610 const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6611 if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6613 _LayerEdge* e0 = eosI._edges[0];
6614 for ( size_t i = 1; i < eosI._edges.size(); ++i )
6616 _LayerEdge* eI = eosI._edges[i];
6617 limitMaxLenByCurvature( eI, e0, eosI, eosI, eosI._hyp.ToSmooth() );
6624 //================================================================================
6626 * \brief Limit _LayerEdge::_maxLen according to local curvature
6628 //================================================================================
6630 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge* e1,
6632 _EdgesOnShape& eos1,
6633 _EdgesOnShape& eos2,
6634 const bool isSmoothable )
6636 if (( e1->_nodes[0]->GetPosition()->GetDim() !=
6637 e2->_nodes[0]->GetPosition()->GetDim() ) &&
6638 ( e1->_cosin < 0.75 ))
6639 return; // angle > 90 deg at e1
6641 gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6642 double norSize = plnNorm.SquareModulus();
6643 if ( norSize < std::numeric_limits<double>::min() )
6644 return; // parallel normals
6646 // find closest points of skew _LayerEdge's
6647 SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6648 gp_XYZ dir12 = src2 - src1;
6649 gp_XYZ perp1 = e1->_normal ^ plnNorm;
6650 gp_XYZ perp2 = e2->_normal ^ plnNorm;
6651 double dot1 = perp2 * e1->_normal;
6652 double dot2 = perp1 * e2->_normal;
6653 double u1 = ( perp2 * dir12 ) / dot1;
6654 double u2 = - ( perp1 * dir12 ) / dot2;
6655 if ( u1 > 0 && u2 > 0 )
6657 double ovl = ( u1 * e1->_normal * dir12 -
6658 u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6659 if ( ovl > theSmoothThickToElemSizeRatio )
6661 const double coef = 0.75;
6662 e1->SetMaxLen( Min( e1->_maxLen, coef * u1 / e1->_lenFactor ));
6663 e2->SetMaxLen( Min( e2->_maxLen, coef * u2 / e2->_lenFactor ));
6668 //================================================================================
6670 * \brief Fill data._collisionEdges
6672 //================================================================================
6674 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6676 data._collisionEdges.clear();
6678 // set the full thickness of the layers to LEs
6679 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6681 _EdgesOnShape& eos = data._edgesOnShape[iS];
6682 if ( eos._edges.empty() ) continue;
6683 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6684 if ( !eos._sWOL.IsNull() ) continue; // PAL23566
6686 for ( size_t i = 0; i < eos._edges.size(); ++i )
6688 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6689 double maxLen = eos._edges[i]->_maxLen;
6690 eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6691 eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6692 eos._edges[i]->_maxLen = maxLen;
6696 // make temporary quadrangles got by extrusion of
6697 // mesh edges along _LayerEdge._normal's
6699 vector< const SMDS_MeshElement* > tmpFaces;
6701 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6703 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6704 if ( eos.ShapeType() != TopAbs_EDGE )
6706 if ( eos._edges.empty() )
6708 _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6709 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6710 while ( smIt->more() )
6711 if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6712 if ( eov->_edges.size() == 1 )
6713 edge[ bool( edge[0]) ] = eov->_edges[0];
6717 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6718 tmpFaces.push_back( f );
6721 for ( size_t i = 0; i < eos._edges.size(); ++i )
6723 _LayerEdge* edge = eos._edges[i];
6724 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6726 const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6727 if ( src2->GetPosition()->GetDim() > 0 &&
6728 src2->GetID() < edge->_nodes[0]->GetID() )
6729 continue; // avoid using same segment twice
6731 // a _LayerEdge containing tgt2
6732 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6734 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6735 tmpFaces.push_back( f );
6740 // Find _LayerEdge's intersecting tmpFaces.
6742 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6744 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6745 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6747 double dist1, dist2, segLen, eps = 0.5;
6748 _CollisionEdges collEdges;
6749 vector< const SMDS_MeshElement* > suspectFaces;
6750 const double angle45 = Cos( 45. * M_PI / 180. );
6752 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6754 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6755 if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6757 // find sub-shapes whose VL can influence VL on eos
6758 set< TGeomID > neighborShapes;
6759 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6760 while ( const TopoDS_Shape* face = fIt->next() )
6762 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6763 if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6765 SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6766 while ( subIt->more() )
6767 neighborShapes.insert( subIt->next()->GetId() );
6770 if ( eos.ShapeType() == TopAbs_VERTEX )
6772 PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6773 while ( const TopoDS_Shape* edge = eIt->next() )
6774 neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6776 // find intersecting _LayerEdge's
6777 for ( size_t i = 0; i < eos._edges.size(); ++i )
6779 if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6780 _LayerEdge* edge = eos._edges[i];
6781 gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6784 gp_Vec eSegDir0, eSegDir1;
6785 if ( edge->IsOnEdge() )
6787 SMESH_TNodeXYZ eP( edge->_nodes[0] );
6788 eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6789 eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6791 suspectFaces.clear();
6792 searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6793 SMDSAbs_Face, suspectFaces );
6794 collEdges._intEdges.clear();
6795 for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6797 const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6798 if ( f->_le1 == edge || f->_le2 == edge ) continue;
6799 if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6800 if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6801 if ( edge->IsOnEdge() ) {
6802 if ( edge->_2neibors->include( f->_le1 ) ||
6803 edge->_2neibors->include( f->_le2 )) continue;
6806 if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6807 ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge ))) continue;
6809 dist1 = dist2 = Precision::Infinite();
6810 if ( !edge->SegTriaInter( lastSegment, f->n(0), f->n(1), f->n(2), dist1, eps ))
6811 dist1 = Precision::Infinite();
6812 if ( !edge->SegTriaInter( lastSegment, f->n(3), f->n(2), f->n(0), dist2, eps ))
6813 dist2 = Precision::Infinite();
6814 if (( dist1 > segLen ) && ( dist2 > segLen ))
6817 if ( edge->IsOnEdge() )
6819 // skip perpendicular EDGEs
6820 gp_Vec fSegDir = SMESH_TNodeXYZ( f->n(0) ) - SMESH_TNodeXYZ( f->n(3) );
6821 bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6822 isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6823 isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6824 isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6829 // either limit inflation of edges or remember them for updating _normal
6830 // double dot = edge->_normal * f->GetDir();
6833 collEdges._intEdges.push_back( f->_le1 );
6834 collEdges._intEdges.push_back( f->_le2 );
6838 // double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6839 // edge->SetMaxLen( Min( shortLen, edge->_maxLen ));
6843 if ( !collEdges._intEdges.empty() )
6845 collEdges._edge = edge;
6846 data._collisionEdges.push_back( collEdges );
6851 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6854 // restore the zero thickness
6855 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6857 _EdgesOnShape& eos = data._edgesOnShape[iS];
6858 if ( eos._edges.empty() ) continue;
6859 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6861 for ( size_t i = 0; i < eos._edges.size(); ++i )
6863 eos._edges[i]->InvalidateStep( 1, eos );
6864 eos._edges[i]->_len = 0;
6869 //================================================================================
6871 * \brief Find _LayerEdge's located on boundary of a convex FACE whose normal
6872 * will be updated at each inflation step
6874 //================================================================================
6876 void _ViscousBuilder::findEdgesToUpdateNormalNearConvexFace( _ConvexFace & convFace,
6878 SMESH_MesherHelper& helper )
6880 const TGeomID convFaceID = getMeshDS()->ShapeToIndex( convFace._face );
6881 const double preci = BRep_Tool::Tolerance( convFace._face );
6882 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( convFace._face );
6884 bool edgesToUpdateFound = false;
6886 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6887 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6889 _EdgesOnShape& eos = * id2eos->second;
6890 if ( !eos._sWOL.IsNull() ) continue;
6891 if ( !eos._hyp.ToSmooth() ) continue;
6892 for ( size_t i = 0; i < eos._edges.size(); ++i )
6894 _LayerEdge* ledge = eos._edges[ i ];
6895 if ( ledge->Is( _LayerEdge::UPD_NORMAL_CONV )) continue; // already checked
6896 if ( ledge->Is( _LayerEdge::MULTI_NORMAL )) continue; // not inflatable
6898 gp_XYZ tgtPos = ( SMESH_NodeXYZ( ledge->_nodes[0] ) +
6899 ledge->_normal * ledge->_lenFactor * ledge->_maxLen );
6901 // the normal must be updated if distance from tgtPos to surface is less than
6904 // find an initial UV for search of a projection of tgtPos to surface
6905 const SMDS_MeshNode* nodeInFace = 0;
6906 SMDS_ElemIteratorPtr fIt = ledge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6907 while ( fIt->more() && !nodeInFace )
6909 const SMDS_MeshElement* f = fIt->next();
6910 if ( convFaceID != f->getshapeId() ) continue;
6912 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
6913 while ( nIt->more() && !nodeInFace )
6915 const SMDS_MeshElement* n = nIt->next();
6916 if ( n->getshapeId() == convFaceID )
6917 nodeInFace = static_cast< const SMDS_MeshNode* >( n );
6922 gp_XY uv = helper.GetNodeUV( convFace._face, nodeInFace );
6925 surface->NextValueOfUV( uv, tgtPos, preci );
6926 double dist = surface->Gap();
6927 if ( dist < 0.95 * ledge->_maxLen )
6929 ledge->Set( _LayerEdge::UPD_NORMAL_CONV );
6930 if ( !ledge->_curvature ) ledge->_curvature = new _Curvature;
6931 ledge->_curvature->_uv.SetCoord( uv.X(), uv.Y() );
6932 edgesToUpdateFound = true;
6937 if ( !convFace._isTooCurved && edgesToUpdateFound )
6939 data._convexFaces.insert( make_pair( convFaceID, convFace )).first->second;
6943 //================================================================================
6945 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6946 * _LayerEdge's on neighbor EDGE's
6948 //================================================================================
6950 bool _ViscousBuilder::updateNormals( _SolidData& data,
6951 SMESH_MesherHelper& helper,
6955 updateNormalsOfC1Vertices( data );
6957 if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6960 // map to store new _normal and _cosin for each intersected edge
6961 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp > edge2newEdge;
6962 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6963 _LayerEdge zeroEdge;
6964 zeroEdge._normal.SetCoord( 0,0,0 );
6965 zeroEdge._maxLen = Precision::Infinite();
6966 zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6968 set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6970 double segLen, dist1, dist2, dist;
6971 vector< pair< _LayerEdge*, double > > intEdgesDist;
6972 _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6974 for ( int iter = 0; iter < 5; ++iter )
6976 edge2newEdge.clear();
6978 for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6980 _CollisionEdges& ce = data._collisionEdges[iE];
6981 _LayerEdge* edge1 = ce._edge;
6982 if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6983 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6984 if ( !eos1 ) continue;
6986 // detect intersections
6987 gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6988 double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6990 intEdgesDist.clear();
6991 double minIntDist = Precision::Infinite();
6992 for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6994 if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6995 ce._intEdges[i ]->Is( _LayerEdge::BLOCKED ) &&
6996 ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6998 double dot = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6999 double fact = ( 1.1 + dot * dot );
7000 SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
7001 SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
7002 gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
7003 gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
7004 dist1 = dist2 = Precision::Infinite();
7005 if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1, dist1, eps ) &&
7006 !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
7009 if ( dist > testLen || dist <= 0 )
7012 if ( dist > testLen || dist <= 0 )
7015 // choose a closest edge
7016 gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
7017 double d1 = intP.SquareDistance( pSrc0 );
7018 double d2 = intP.SquareDistance( pSrc1 );
7019 int iClose = i + ( d2 < d1 );
7020 _LayerEdge* edge2 = ce._intEdges[iClose];
7021 edge2->Unset( _LayerEdge::MARKED );
7023 // choose a closest edge among neighbors
7024 gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
7025 d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
7026 for ( size_t j = 0; j < intEdgesDist.size(); ++j )
7028 _LayerEdge * edgeJ = intEdgesDist[j].first;
7029 if ( edge2->IsNeiborOnEdge( edgeJ ))
7031 d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
7032 ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
7035 intEdgesDist.push_back( make_pair( edge2, dist ));
7036 // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
7038 // iClose = i + !( d2 < d1 );
7039 // intEdges.push_back( ce._intEdges[iClose] );
7040 // ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
7042 minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
7047 // compute new _normals
7048 for ( size_t i = 0; i < intEdgesDist.size(); ++i )
7050 _LayerEdge* edge2 = intEdgesDist[i].first;
7051 double distWgt = edge1->_len / intEdgesDist[i].second;
7052 // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7053 // edge2->Is( _LayerEdge::BLOCKED )) continue;
7054 if ( edge2->Is( _LayerEdge::MARKED )) continue;
7055 edge2->Set( _LayerEdge::MARKED );
7058 gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
7060 double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7061 double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7062 double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7063 // double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7064 // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
7065 // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7066 // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7067 gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
7068 newNormal.Normalize();
7072 double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
7073 if ( cos1 < theMinSmoothCosin )
7075 newCos = cos2 * sgn1;
7077 else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
7079 newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
7083 newCos = edge1->_cosin;
7086 e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
7087 e2neIt->second._normal += distWgt * newNormal;
7088 e2neIt->second._cosin = newCos;
7089 e2neIt->second.SetMaxLen( 0.7 * minIntDist / edge1->_lenFactor );
7090 if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
7091 e2neIt->second._normal += dir2;
7093 e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
7094 e2neIt->second._normal += distWgt * newNormal;
7095 if ( Precision::IsInfinite( zeroEdge._maxLen ))
7097 e2neIt->second._cosin = edge2->_cosin;
7098 e2neIt->second.SetMaxLen( 1.3 * minIntDist / edge1->_lenFactor );
7100 if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
7101 e2neIt->second._normal += dir1;
7105 if ( edge2newEdge.empty() )
7106 break; //return true;
7108 dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
7110 // Update data of edges depending on a new _normal
7113 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7115 _LayerEdge* edge = e2neIt->first;
7116 _LayerEdge& newEdge = e2neIt->second;
7117 _EdgesOnShape* eos = data.GetShapeEdges( edge );
7118 if ( edge->Is( _LayerEdge::BLOCKED && newEdge._maxLen > edge->_len ))
7121 // Check if a new _normal is OK:
7122 newEdge._normal.Normalize();
7123 if ( !isNewNormalOk( data, *edge, newEdge._normal ))
7125 if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
7127 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7128 edge->SetMaxLen( newEdge._maxLen );
7129 edge->SetNewLength( newEdge._maxLen, *eos, helper );
7131 continue; // the new _normal is bad
7133 // the new _normal is OK
7135 // find shapes that need smoothing due to change of _normal
7136 if ( edge->_cosin < theMinSmoothCosin &&
7137 newEdge._cosin > theMinSmoothCosin )
7139 if ( eos->_sWOL.IsNull() )
7141 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7142 while ( fIt->more() )
7143 shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
7145 else // edge inflates along a FACE
7147 TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
7148 PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
7149 while ( const TopoDS_Shape* E = eIt->next() )
7151 gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
7152 double angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
7153 if ( angle < M_PI / 2 )
7154 shapesToSmooth.insert( data.GetShapeEdges( *E ));
7159 double len = edge->_len;
7160 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7161 edge->SetNormal( newEdge._normal );
7162 edge->SetCosin( newEdge._cosin );
7163 edge->SetNewLength( len, *eos, helper );
7164 edge->Set( _LayerEdge::MARKED );
7165 edge->Set( _LayerEdge::NORMAL_UPDATED );
7166 edgesNoAnaSmooth.insert( eos );
7169 // Update normals and other dependent data of not intersecting _LayerEdge's
7170 // neighboring the intersecting ones
7172 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7174 _LayerEdge* edge1 = e2neIt->first;
7175 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7176 if ( !edge1->Is( _LayerEdge::MARKED ))
7179 if ( edge1->IsOnEdge() )
7181 const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
7182 const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
7183 edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
7186 if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
7188 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
7190 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
7191 if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
7192 continue; // j-th neighbor is also intersected
7193 _LayerEdge* prevEdge = edge1;
7194 const int nbSteps = 10;
7195 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
7197 if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
7198 neighbor->Is( _LayerEdge::MARKED ))
7200 _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
7201 if ( !eos ) continue;
7202 _LayerEdge* nextEdge = neighbor;
7203 if ( neighbor->_2neibors )
7206 nextEdge = neighbor->_2neibors->_edges[iNext];
7207 if ( nextEdge == prevEdge )
7208 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
7210 double r = double(step-1)/nbSteps/(iter+1);
7211 if ( !nextEdge->_2neibors )
7214 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
7215 newNorm.Normalize();
7216 if ( !isNewNormalOk( data, *neighbor, newNorm ))
7219 double len = neighbor->_len;
7220 neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7221 neighbor->SetNormal( newNorm );
7222 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
7223 if ( neighbor->_2neibors )
7224 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
7225 neighbor->SetNewLength( len, *eos, helper );
7226 neighbor->Set( _LayerEdge::MARKED );
7227 neighbor->Set( _LayerEdge::NORMAL_UPDATED );
7228 edgesNoAnaSmooth.insert( eos );
7230 if ( !neighbor->_2neibors )
7231 break; // neighbor is on VERTEX
7233 // goto the next neighbor
7234 prevEdge = neighbor;
7235 neighbor = nextEdge;
7242 data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
7247 //================================================================================
7249 * \brief Check if a new normal is OK
7251 //================================================================================
7253 bool _ViscousBuilder::isNewNormalOk( _SolidData& data,
7255 const gp_XYZ& newNormal)
7257 // check a min angle between the newNormal and surrounding faces
7258 vector<_Simplex> simplices;
7259 SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
7260 _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
7261 double newMinDot = 1, curMinDot = 1;
7262 for ( size_t i = 0; i < simplices.size(); ++i )
7264 n1.Set( simplices[i]._nPrev );
7265 n2.Set( simplices[i]._nNext );
7266 gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
7267 double normLen2 = normFace.SquareModulus();
7268 if ( normLen2 < std::numeric_limits<double>::min() )
7270 normFace /= Sqrt( normLen2 );
7271 newMinDot = Min( newNormal * normFace, newMinDot );
7272 curMinDot = Min( edge._normal * normFace, curMinDot );
7275 if ( newMinDot < 0.5 )
7277 ok = ( newMinDot >= curMinDot * 0.9 );
7278 //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
7279 // double initMinDot2 = 1. - edge._cosin * edge._cosin;
7280 // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
7286 //================================================================================
7288 * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
7290 //================================================================================
7292 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData& data,
7293 SMESH_MesherHelper& helper,
7295 const double stepSize )
7297 if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
7298 return true; // no shapes needing smoothing
7300 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7302 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7303 if ( //!eos._toSmooth || _eosC1 have _toSmooth == false
7304 !eos._hyp.ToSmooth() ||
7305 eos.ShapeType() != TopAbs_FACE ||
7306 eos._edges.empty() )
7309 bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
7310 if ( !toSmooth ) continue;
7312 for ( size_t i = 0; i < eos._edges.size(); ++i )
7314 _LayerEdge* edge = eos._edges[i];
7315 if ( !edge->Is( _LayerEdge::SMOOTHED ))
7317 if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
7320 const gp_XYZ& pPrev = edge->PrevPos();
7321 const gp_XYZ& pLast = edge->_pos.back();
7322 gp_XYZ stepVec = pLast - pPrev;
7323 double realStepSize = stepVec.Modulus();
7324 if ( realStepSize < numeric_limits<double>::min() )
7327 edge->_lenFactor = realStepSize / stepSize;
7328 edge->_normal = stepVec / realStepSize;
7329 edge->Set( _LayerEdge::NORMAL_UPDATED );
7336 //================================================================================
7338 * \brief Modify normals of _LayerEdge's on C1 VERTEXes
7340 //================================================================================
7342 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
7344 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7346 _EdgesOnShape& eov = data._edgesOnShape[ iS ];
7347 if ( eov._eosC1.empty() ||
7348 eov.ShapeType() != TopAbs_VERTEX ||
7349 eov._edges.empty() )
7352 gp_XYZ newNorm = eov._edges[0]->_normal;
7353 double curThick = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
7354 bool normChanged = false;
7356 for ( size_t i = 0; i < eov._eosC1.size(); ++i )
7358 _EdgesOnShape* eoe = eov._eosC1[i];
7359 const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
7360 const double eLen = SMESH_Algo::EdgeLength( e );
7361 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
7362 if ( oppV.IsSame( eov._shape ))
7363 oppV = SMESH_MesherHelper::IthVertex( 1, e );
7364 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
7365 if ( !eovOpp || eovOpp->_edges.empty() ) continue;
7366 if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
7368 double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
7369 if ( curThickOpp + curThick < eLen )
7372 double wgt = 2. * curThick / eLen;
7373 newNorm += wgt * eovOpp->_edges[0]->_normal;
7378 eov._edges[0]->SetNormal( newNorm.Normalized() );
7379 eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
7384 //================================================================================
7386 * \brief Modify normals of _LayerEdge's on _ConvexFace's
7388 //================================================================================
7390 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData& data,
7391 SMESH_MesherHelper& helper,
7394 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
7397 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
7398 for ( ; id2face != data._convexFaces.end(); ++id2face )
7400 _ConvexFace & convFace = (*id2face).second;
7401 convFace._normalsFixedOnBorders = false; // to update at each inflation step
7403 if ( convFace._normalsFixed )
7404 continue; // already fixed
7405 if ( convFace.CheckPrisms() )
7406 continue; // nothing to fix
7408 convFace._normalsFixed = true;
7410 BRepAdaptor_Surface surface ( convFace._face, false );
7411 BRepLProp_SLProps surfProp( surface, 2, 1e-6 );
7413 // check if the convex FACE is of spherical shape
7415 Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
7419 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7420 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7422 _EdgesOnShape& eos = *(id2eos->second);
7423 if ( eos.ShapeType() == TopAbs_VERTEX )
7425 _LayerEdge* ledge = eos._edges[ 0 ];
7426 if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7427 centersBox.Add( center );
7429 for ( size_t i = 0; i < eos._edges.size(); ++i )
7430 nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
7432 if ( centersBox.IsVoid() )
7434 debugMsg( "Error: centersBox.IsVoid()" );
7437 const bool isSpherical =
7438 ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7440 int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
7441 vector < _CentralCurveOnEdge > centerCurves( nbEdges );
7445 // set _LayerEdge::_normal as average of all normals
7447 // WARNING: different density of nodes on EDGEs is not taken into account that
7448 // can lead to an improper new normal
7450 gp_XYZ avgNormal( 0,0,0 );
7452 id2eos = convFace._subIdToEOS.begin();
7453 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7455 _EdgesOnShape& eos = *(id2eos->second);
7456 // set data of _CentralCurveOnEdge
7457 if ( eos.ShapeType() == TopAbs_EDGE )
7459 _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
7460 ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
7461 if ( !eos._sWOL.IsNull() )
7462 ceCurve._adjFace.Nullify();
7464 ceCurve._ledges.insert( ceCurve._ledges.end(),
7465 eos._edges.begin(), eos._edges.end());
7467 // summarize normals
7468 for ( size_t i = 0; i < eos._edges.size(); ++i )
7469 avgNormal += eos._edges[ i ]->_normal;
7471 double normSize = avgNormal.SquareModulus();
7472 if ( normSize < 1e-200 )
7474 debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7477 avgNormal /= Sqrt( normSize );
7479 // compute new _LayerEdge::_cosin on EDGEs
7480 double avgCosin = 0;
7483 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7485 _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7486 if ( ceCurve._adjFace.IsNull() )
7488 for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7490 const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7491 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7494 double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7495 ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7496 avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7502 avgCosin /= nbCosin;
7504 // set _LayerEdge::_normal = avgNormal
7505 id2eos = convFace._subIdToEOS.begin();
7506 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7508 _EdgesOnShape& eos = *(id2eos->second);
7509 if ( eos.ShapeType() != TopAbs_EDGE )
7510 for ( size_t i = 0; i < eos._edges.size(); ++i )
7511 eos._edges[ i ]->_cosin = avgCosin;
7513 for ( size_t i = 0; i < eos._edges.size(); ++i )
7515 eos._edges[ i ]->SetNormal( avgNormal );
7516 eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7520 else // if ( isSpherical )
7522 // We suppose that centers of curvature at all points of the FACE
7523 // lie on some curve, let's call it "central curve". For all _LayerEdge's
7524 // having a common center of curvature we define the same new normal
7525 // as a sum of normals of _LayerEdge's on EDGEs among them.
7527 // get all centers of curvature for each EDGE
7529 helper.SetSubShape( convFace._face );
7530 _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7532 TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7533 for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7535 const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7537 // set adjacent FACE
7538 centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7540 // get _LayerEdge's of the EDGE
7541 TGeomID edgeID = meshDS->ShapeToIndex( edge );
7542 _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7543 if ( !eos || eos->_edges.empty() )
7545 // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7546 for ( int iV = 0; iV < 2; ++iV )
7548 TopoDS_Vertex v = helper.IthVertex( iV, edge );
7549 TGeomID vID = meshDS->ShapeToIndex( v );
7550 eos = data.GetShapeEdges( vID );
7551 vertexLEdges[ iV ] = eos->_edges[ 0 ];
7553 edgeLEdge = &vertexLEdges[0];
7554 edgeLEdgeEnd = edgeLEdge + 2;
7556 centerCurves[ iE ]._adjFace.Nullify();
7560 if ( ! eos->_toSmooth )
7561 data.SortOnEdge( edge, eos->_edges );
7562 edgeLEdge = &eos->_edges[ 0 ];
7563 edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7564 vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7565 vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7567 if ( ! eos->_sWOL.IsNull() )
7568 centerCurves[ iE ]._adjFace.Nullify();
7571 // Get curvature centers
7575 if ( edgeLEdge[0]->IsOnEdge() &&
7576 convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7578 centerCurves[ iE ].Append( center, vertexLEdges[0] );
7579 centersBox.Add( center );
7581 for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7582 if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7583 { // EDGE or VERTEXes
7584 centerCurves[ iE ].Append( center, *edgeLEdge );
7585 centersBox.Add( center );
7587 if ( edgeLEdge[-1]->IsOnEdge() &&
7588 convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7590 centerCurves[ iE ].Append( center, vertexLEdges[1] );
7591 centersBox.Add( center );
7593 centerCurves[ iE ]._isDegenerated =
7594 ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7596 } // loop on EDGES of convFace._face to set up data of centerCurves
7598 // Compute new normals for _LayerEdge's on EDGEs
7600 double avgCosin = 0;
7603 for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7605 _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7606 if ( ceCurve._isDegenerated )
7608 const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7609 vector< gp_XYZ > & newNormals = ceCurve._normals;
7610 for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7613 for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7616 isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7618 if ( isOK && !ceCurve._adjFace.IsNull() )
7620 // compute new _LayerEdge::_cosin
7621 const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7622 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7625 double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7626 ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7627 avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7633 // set new normals to _LayerEdge's of NOT degenerated central curves
7634 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7636 if ( centerCurves[ iE ]._isDegenerated )
7638 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7640 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7641 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7644 // set new normals to _LayerEdge's of degenerated central curves
7645 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7647 if ( !centerCurves[ iE ]._isDegenerated ||
7648 centerCurves[ iE ]._ledges.size() < 3 )
7650 // new normal is an average of new normals at VERTEXes that
7651 // was computed on non-degenerated _CentralCurveOnEdge's
7652 gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7653 centerCurves[ iE ]._ledges.back ()->_normal );
7654 double sz = newNorm.Modulus();
7658 double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7659 0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7660 for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7662 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7663 centerCurves[ iE ]._ledges[ iLE ]->_cosin = newCosin;
7664 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7668 // Find new normals for _LayerEdge's based on FACE
7671 avgCosin /= nbCosin;
7672 const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7673 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7674 if ( id2eos != convFace._subIdToEOS.end() )
7678 _EdgesOnShape& eos = * ( id2eos->second );
7679 for ( size_t i = 0; i < eos._edges.size(); ++i )
7681 _LayerEdge* ledge = eos._edges[ i ];
7682 if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7684 for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7686 iE = iE % centerCurves.size();
7687 if ( centerCurves[ iE ]._isDegenerated )
7689 newNorm.SetCoord( 0,0,0 );
7690 if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7692 ledge->SetNormal( newNorm );
7693 ledge->_cosin = avgCosin;
7694 ledge->Set( _LayerEdge::NORMAL_UPDATED );
7701 } // not a quasi-spherical FACE
7703 // Update _LayerEdge's data according to a new normal
7705 dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7706 <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7708 id2eos = convFace._subIdToEOS.begin();
7709 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7711 _EdgesOnShape& eos = * ( id2eos->second );
7712 for ( size_t i = 0; i < eos._edges.size(); ++i )
7714 _LayerEdge* & ledge = eos._edges[ i ];
7715 double len = ledge->_len;
7716 ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7717 ledge->SetCosin( ledge->_cosin );
7718 ledge->SetNewLength( len, eos, helper );
7720 if ( eos.ShapeType() != TopAbs_FACE )
7721 for ( size_t i = 0; i < eos._edges.size(); ++i )
7723 _LayerEdge* ledge = eos._edges[ i ];
7724 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7726 _LayerEdge* neibor = ledge->_neibors[iN];
7727 if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7729 neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7730 neibor->Set( _LayerEdge::MOVED );
7731 neibor->SetSmooLen( neibor->_len );
7735 } // loop on sub-shapes of convFace._face
7737 // Find FACEs adjacent to convFace._face that got necessity to smooth
7738 // as a result of normals modification
7740 set< _EdgesOnShape* > adjFacesToSmooth;
7741 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7743 if ( centerCurves[ iE ]._adjFace.IsNull() ||
7744 centerCurves[ iE ]._adjFaceToSmooth )
7746 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7748 if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7750 adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7755 data.AddShapesToSmooth( adjFacesToSmooth );
7760 } // loop on data._convexFaces
7765 //================================================================================
7767 * \brief Return max curvature of a FACE
7769 //================================================================================
7771 double _ConvexFace::GetMaxCurvature( _SolidData& data,
7773 BRepLProp_SLProps& surfProp,
7774 SMESH_MesherHelper& helper)
7776 double maxCurvature = 0;
7778 TopoDS_Face F = TopoDS::Face( eof._shape );
7780 const int nbTestPnt = 5;
7781 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7782 SMESH_subMeshIteratorPtr smIt = eof._subMesh->getDependsOnIterator(/*includeSelf=*/true);
7783 while ( smIt->more() )
7785 SMESH_subMesh* sm = smIt->next();
7786 const TGeomID subID = sm->GetId();
7788 // find _LayerEdge's of a sub-shape
7790 if (( eos = data.GetShapeEdges( subID )))
7791 this->_subIdToEOS.insert( make_pair( subID, eos ));
7795 // check concavity and curvature and limit data._stepSize
7796 const double minCurvature =
7797 1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
7798 size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
7799 for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
7801 gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
7802 surfProp.SetParameters( uv.X(), uv.Y() );
7803 if ( surfProp.IsCurvatureDefined() )
7805 double curvature = Max( surfProp.MaxCurvature() * oriFactor,
7806 surfProp.MinCurvature() * oriFactor );
7807 maxCurvature = Max( maxCurvature, curvature );
7809 if ( curvature > minCurvature )
7810 this->_isTooCurved = true;
7813 } // loop on sub-shapes of the FACE
7815 return maxCurvature;
7818 //================================================================================
7820 * \brief Finds a center of curvature of a surface at a _LayerEdge
7822 //================================================================================
7824 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge* ledge,
7825 BRepLProp_SLProps& surfProp,
7826 SMESH_MesherHelper& helper,
7827 gp_Pnt & center ) const
7829 gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7830 surfProp.SetParameters( uv.X(), uv.Y() );
7831 if ( !surfProp.IsCurvatureDefined() )
7834 const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7835 double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7836 double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7837 if ( surfCurvatureMin > surfCurvatureMax )
7838 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7840 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7845 //================================================================================
7847 * \brief Check that prisms are not distorted
7849 //================================================================================
7851 bool _ConvexFace::CheckPrisms() const
7854 for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7856 const _LayerEdge* edge = _simplexTestEdges[i];
7857 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7858 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7859 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7861 debugMsg( "Bad simplex of _simplexTestEdges ("
7862 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7863 << " "<< edge->_simplices[j]._nPrev->GetID()
7864 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7871 //================================================================================
7873 * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7874 * stored in this _CentralCurveOnEdge.
7875 * \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7876 * \param [in,out] newNormal - current normal at this point, to be redefined
7877 * \return bool - true if succeeded.
7879 //================================================================================
7881 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7883 if ( this->_isDegenerated )
7886 // find two centers the given one lies between
7888 for ( size_t i = 0, nb = _curvaCenters.size()-1; i < nb; ++i )
7890 double sl2 = 1.001 * _segLength2[ i ];
7892 double d1 = center.SquareDistance( _curvaCenters[ i ]);
7896 double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7897 if ( d2 > sl2 || d2 + d1 < 1e-100 )
7902 double r = d1 / ( d1 + d2 );
7903 gp_XYZ norm = (( 1. - r ) * _ledges[ i ]->_normal +
7904 ( r ) * _ledges[ i+1 ]->_normal );
7908 double sz = newNormal.Modulus();
7917 //================================================================================
7919 * \brief Set shape members
7921 //================================================================================
7923 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge& edge,
7924 const _ConvexFace& convFace,
7926 SMESH_MesherHelper& helper)
7930 PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7931 while ( const TopoDS_Shape* F = fIt->next())
7932 if ( !convFace._face.IsSame( *F ))
7934 _adjFace = TopoDS::Face( *F );
7935 _adjFaceToSmooth = false;
7936 // _adjFace already in a smoothing queue ?
7937 if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7938 _adjFaceToSmooth = eos->_toSmooth;
7943 //================================================================================
7945 * \brief Looks for intersection of it's last segment with faces
7946 * \param distance - returns shortest distance from the last node to intersection
7948 //================================================================================
7950 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
7952 const double& epsilon,
7954 const SMDS_MeshElement** intFace)
7956 vector< const SMDS_MeshElement* > suspectFaces;
7958 gp_Ax1 lastSegment = LastSegment( segLen, eos );
7959 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7961 bool segmentIntersected = false;
7962 distance = Precision::Infinite();
7963 int iFace = -1; // intersected face
7964 for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7966 const SMDS_MeshElement* face = suspectFaces[j];
7967 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7968 face->GetNodeIndex( _nodes[0] ) >= 0 )
7969 continue; // face sharing _LayerEdge node
7970 const int nbNodes = face->NbCornerNodes();
7971 bool intFound = false;
7973 SMDS_MeshElement::iterator nIt = face->begin_nodes();
7976 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7980 const SMDS_MeshNode* tria[3];
7983 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7986 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7992 if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7993 segmentIntersected = true;
7994 if ( distance > dist )
7995 distance = dist, iFace = j;
7998 if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
8002 if ( segmentIntersected )
8005 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
8006 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
8007 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
8008 << ", intersection with face ("
8009 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
8010 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
8011 << ") distance = " << distance << endl;
8015 return segmentIntersected;
8018 //================================================================================
8020 * \brief Returns a point used to check orientation of _simplices
8022 //================================================================================
8024 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
8026 size_t i = Is( NORMAL_UPDATED ) && IsOnFace() ? _pos.size()-2 : 0;
8028 if ( !eos || eos->_sWOL.IsNull() )
8031 if ( eos->SWOLType() == TopAbs_EDGE )
8033 return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
8035 //else // TopAbs_FACE
8037 return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
8040 //================================================================================
8042 * \brief Returns size and direction of the last segment
8044 //================================================================================
8046 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
8048 // find two non-coincident positions
8049 gp_XYZ orig = _pos.back();
8051 int iPrev = _pos.size() - 2;
8052 //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
8053 const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
8054 while ( iPrev >= 0 )
8056 vec = orig - _pos[iPrev];
8057 if ( vec.SquareModulus() > tol*tol )
8067 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
8068 segDir.SetDirection( _normal );
8073 gp_Pnt pPrev = _pos[ iPrev ];
8074 if ( !eos._sWOL.IsNull() )
8076 TopLoc_Location loc;
8077 if ( eos.SWOLType() == TopAbs_EDGE )
8080 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8081 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
8085 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
8086 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
8088 vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
8090 segDir.SetLocation( pPrev );
8091 segDir.SetDirection( vec );
8092 segLen = vec.Modulus();
8098 //================================================================================
8100 * \brief Return the last (or \a which) position of the target node on a FACE.
8101 * \param [in] F - the FACE this _LayerEdge is inflated along
8102 * \param [in] which - index of position
8103 * \return gp_XY - result UV
8105 //================================================================================
8107 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which ) const
8109 if ( F.IsSame( eos._sWOL )) // F is my FACE
8110 return gp_XY( _pos.back().X(), _pos.back().Y() );
8112 if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
8113 return gp_XY( 1e100, 1e100 );
8115 // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
8116 double f, l, u = _pos[ which < 0 ? _pos.size()-1 : which ].X();
8117 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
8118 if ( !C2d.IsNull() && f <= u && u <= l )
8119 return C2d->Value( u ).XY();
8121 return gp_XY( 1e100, 1e100 );
8124 //================================================================================
8126 * \brief Test intersection of the last segment with a given triangle
8127 * using Moller-Trumbore algorithm
8128 * Intersection is detected if distance to intersection is less than _LayerEdge._len
8130 //================================================================================
8132 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
8133 const gp_XYZ& vert0,
8134 const gp_XYZ& vert1,
8135 const gp_XYZ& vert2,
8137 const double& EPSILON) const
8139 const gp_Pnt& orig = lastSegment.Location();
8140 const gp_Dir& dir = lastSegment.Direction();
8142 /* calculate distance from vert0 to ray origin */
8143 //gp_XYZ tvec = orig.XYZ() - vert0;
8145 //if ( tvec * dir > EPSILON )
8146 // intersected face is at back side of the temporary face this _LayerEdge belongs to
8149 gp_XYZ edge1 = vert1 - vert0;
8150 gp_XYZ edge2 = vert2 - vert0;
8152 /* begin calculating determinant - also used to calculate U parameter */
8153 gp_XYZ pvec = dir.XYZ() ^ edge2;
8155 /* if determinant is near zero, ray lies in plane of triangle */
8156 double det = edge1 * pvec;
8158 const double ANGL_EPSILON = 1e-12;
8159 if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
8162 /* calculate distance from vert0 to ray origin */
8163 gp_XYZ tvec = orig.XYZ() - vert0;
8165 /* calculate U parameter and test bounds */
8166 double u = ( tvec * pvec ) / det;
8167 //if (u < 0.0 || u > 1.0)
8168 if ( u < -EPSILON || u > 1.0 + EPSILON )
8171 /* prepare to test V parameter */
8172 gp_XYZ qvec = tvec ^ edge1;
8174 /* calculate V parameter and test bounds */
8175 double v = (dir.XYZ() * qvec) / det;
8176 //if ( v < 0.0 || u + v > 1.0 )
8177 if ( v < -EPSILON || u + v > 1.0 + EPSILON )
8180 /* calculate t, ray intersects triangle */
8181 t = (edge2 * qvec) / det;
8187 //================================================================================
8189 * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
8190 * neighbor _LayerEdge's by it's own inflation vector.
8191 * \param [in] eov - EOS of the VERTEX
8192 * \param [in] eos - EOS of the FACE
8193 * \param [in] step - inflation step
8194 * \param [in,out] badSmooEdges - tangled _LayerEdge's
8196 //================================================================================
8198 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape* eov,
8199 const _EdgesOnShape* eos,
8201 vector< _LayerEdge* > & badSmooEdges )
8203 // check if any of _neibors is in badSmooEdges
8204 if ( std::find_first_of( _neibors.begin(), _neibors.end(),
8205 badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
8208 // get all edges to move
8210 set< _LayerEdge* > edges;
8212 // find a distance between _LayerEdge on VERTEX and its neighbors
8213 gp_XYZ curPosV = SMESH_TNodeXYZ( _nodes.back() );
8215 for ( size_t i = 0; i < _neibors.size(); ++i )
8217 _LayerEdge* nEdge = _neibors[i];
8218 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
8220 edges.insert( nEdge );
8221 dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
8224 // add _LayerEdge's close to curPosV
8228 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8230 _LayerEdge* edgeF = *e;
8231 for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
8233 _LayerEdge* nEdge = edgeF->_neibors[i];
8234 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
8235 dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
8236 edges.insert( nEdge );
8240 while ( nbE < edges.size() );
8242 // move the target node of the got edges
8244 gp_XYZ prevPosV = PrevPos();
8245 if ( eov->SWOLType() == TopAbs_EDGE )
8247 BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
8248 prevPosV = curve.Value( prevPosV.X() ).XYZ();
8250 else if ( eov->SWOLType() == TopAbs_FACE )
8252 BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
8253 prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
8256 SMDS_FacePositionPtr fPos;
8257 //double r = 1. - Min( 0.9, step / 10. );
8258 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8260 _LayerEdge* edgeF = *e;
8261 const gp_XYZ prevVF = edgeF->PrevPos() - prevPosV;
8262 const gp_XYZ newPosF = curPosV + prevVF;
8263 SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8264 tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
8265 edgeF->_pos.back() = newPosF;
8266 dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
8268 // set _curvature to make edgeF updated by putOnOffsetSurface()
8269 if ( !edgeF->_curvature )
8270 if (( fPos = edgeF->_nodes[0]->GetPosition() ))
8272 edgeF->_curvature = new _Curvature;
8273 edgeF->_curvature->_r = 0;
8274 edgeF->_curvature->_k = 0;
8275 edgeF->_curvature->_h2lenRatio = 0;
8276 edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
8279 // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
8280 // SMESH_TNodeXYZ( _nodes[0] ));
8281 // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8283 // _LayerEdge* edgeF = *e;
8284 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8285 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8286 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8287 // edgeF->_pos.back() = newPosF;
8288 // dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
8291 // smooth _LayerEdge's around moved nodes
8292 //size_t nbBadBefore = badSmooEdges.size();
8293 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8295 _LayerEdge* edgeF = *e;
8296 for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
8297 if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
8298 //&& !edges.count( edgeF->_neibors[j] ))
8300 _LayerEdge* edgeFN = edgeF->_neibors[j];
8301 edgeFN->Unset( SMOOTHED );
8302 int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
8305 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
8306 // const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
8307 // int nbBadAfter = edgeFN->_simplices.size();
8309 // for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
8311 // nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
8313 // if ( nbBadAfter <= nbBad )
8315 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
8316 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8317 // edgeF->_pos.back() = newPosF;
8318 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8319 // nbBad = nbBadAfter;
8323 badSmooEdges.push_back( edgeFN );
8326 // move a bit not smoothed around moved nodes
8327 // for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
8329 // _LayerEdge* edgeF = badSmooEdges[i];
8330 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8331 // gp_XYZ newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8332 // gp_XYZ newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
8333 // tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
8334 // edgeF->_pos.back() = newPosF;
8335 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8339 //================================================================================
8341 * \brief Perform smooth of _LayerEdge's based on EDGE's
8342 * \retval bool - true if node has been moved
8344 //================================================================================
8346 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
8347 const TopoDS_Face& F,
8348 SMESH_MesherHelper& helper)
8350 ASSERT( IsOnEdge() );
8352 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
8353 SMESH_TNodeXYZ oldPos( tgtNode );
8354 double dist01, distNewOld;
8356 SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
8357 SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
8358 dist01 = p0.Distance( _2neibors->tgtNode(1) );
8360 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
8361 double lenDelta = 0;
8364 //lenDelta = _curvature->lenDelta( _len );
8365 lenDelta = _curvature->lenDeltaByDist( dist01 );
8366 newPos.ChangeCoord() += _normal * lenDelta;
8369 distNewOld = newPos.Distance( oldPos );
8373 if ( _2neibors->_plnNorm )
8375 // put newPos on the plane defined by source node and _plnNorm
8376 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
8377 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
8378 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
8380 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8381 _pos.back() = newPos.XYZ();
8385 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8386 gp_XY uv( Precision::Infinite(), 0 );
8387 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
8388 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8390 newPos = surface->Value( uv );
8391 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8394 // commented for IPAL0052478
8395 // if ( _curvature && lenDelta < 0 )
8397 // gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
8398 // _len -= prevPos.Distance( oldPos );
8399 // _len += prevPos.Distance( newPos );
8401 bool moved = distNewOld > dist01/50;
8403 dumpMove( tgtNode ); // debug
8408 //================================================================================
8410 * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
8412 //================================================================================
8414 void _LayerEdge::SmoothWoCheck()
8416 if ( Is( DIFFICULT ))
8419 bool moved = Is( SMOOTHED );
8420 for ( size_t i = 0; i < _neibors.size() && !moved; ++i )
8421 moved = _neibors[i]->Is( SMOOTHED );
8425 gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8427 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8428 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8429 _pos.back() = newPos;
8431 dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
8434 //================================================================================
8436 * \brief Checks validity of _neibors on EDGEs and VERTEXes
8438 //================================================================================
8440 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
8442 if ( ! Is( NEAR_BOUNDARY ))
8447 for ( size_t iN = 0; iN < _neibors.size(); ++iN )
8449 _LayerEdge* eN = _neibors[iN];
8450 if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
8453 *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
8454 eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
8455 eN->_pos.size() != _pos.size() );
8457 SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
8458 SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
8459 for ( size_t i = 0; i < eN->_simplices.size(); ++i )
8460 if ( eN->_nodes.size() > 1 &&
8461 eN->_simplices[i].Includes( _nodes.back() ) &&
8462 !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
8467 badNeibors->push_back( eN );
8468 debugMsg("Bad boundary simplex ( "
8469 << " "<< eN->_nodes[0]->GetID()
8470 << " "<< eN->_nodes.back()->GetID()
8471 << " "<< eN->_simplices[i]._nPrev->GetID()
8472 << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
8483 //================================================================================
8485 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8486 * \retval int - nb of bad simplices around this _LayerEdge
8488 //================================================================================
8490 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
8492 if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
8493 return 0; // shape of simplices not changed
8494 if ( _simplices.size() < 2 )
8495 return 0; // _LayerEdge inflated along EDGE or FACE
8497 if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
8500 const gp_XYZ& curPos = _pos.back();
8501 const gp_XYZ& prevPos = _pos[0]; //PrevPos();
8503 // quality metrics (orientation) of tetras around _tgtNode
8505 double vol, minVolBefore = 1e100;
8506 for ( size_t i = 0; i < _simplices.size(); ++i )
8508 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8509 minVolBefore = Min( minVolBefore, vol );
8511 int nbBad = _simplices.size() - nbOkBefore;
8513 bool bndNeedSmooth = false;
8515 nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
8519 // evaluate min angle
8520 if ( nbBad == 0 && !findBest && !bndNeedSmooth )
8522 size_t nbGoodAngles = _simplices.size();
8524 for ( size_t i = 0; i < _simplices.size(); ++i )
8526 if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
8529 if ( nbGoodAngles == _simplices.size() )
8535 if ( Is( ON_CONCAVE_FACE ))
8538 if ( step % 2 == 0 )
8541 if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8543 if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8544 _smooFunction = _funs[ FUN_CENTROIDAL ];
8546 _smooFunction = _funs[ FUN_LAPLACIAN ];
8549 // compute new position for the last _pos using different _funs
8552 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8555 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8556 else if ( _funs[ iFun ] == _smooFunction )
8557 continue; // _smooFunction again
8558 else if ( step > 1 )
8559 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8561 break; // let "easy" functions improve elements around distorted ones
8565 double delta = _curvature->lenDelta( _len );
8567 newPos += _normal * delta;
8570 double segLen = _normal * ( newPos - prevPos );
8571 if ( segLen + delta > 0 )
8572 newPos += _normal * delta;
8574 // double segLenChange = _normal * ( curPos - newPos );
8575 // newPos += 0.5 * _normal * segLenChange;
8579 double minVolAfter = 1e100;
8580 for ( size_t i = 0; i < _simplices.size(); ++i )
8582 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8583 minVolAfter = Min( minVolAfter, vol );
8586 if ( nbOkAfter < nbOkBefore )
8590 ( nbOkAfter == nbOkBefore ) &&
8591 ( minVolAfter <= minVolBefore ))
8594 nbBad = _simplices.size() - nbOkAfter;
8595 minVolBefore = minVolAfter;
8596 nbOkBefore = nbOkAfter;
8599 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8600 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8601 _pos.back() = newPos;
8603 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8604 << (nbBad ? " --BAD" : ""));
8608 continue; // look for a better function
8614 } // loop on smoothing functions
8616 if ( moved ) // notify _neibors
8619 for ( size_t i = 0; i < _neibors.size(); ++i )
8620 if ( !_neibors[i]->Is( MOVED ))
8622 _neibors[i]->Set( MOVED );
8623 toSmooth.push_back( _neibors[i] );
8630 //================================================================================
8632 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8633 * \retval int - nb of bad simplices around this _LayerEdge
8635 //================================================================================
8637 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8639 if ( !_smooFunction )
8640 return 0; // _LayerEdge inflated along EDGE or FACE
8642 return 0; // not inflated
8644 const gp_XYZ& curPos = _pos.back();
8645 const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8647 // quality metrics (orientation) of tetras around _tgtNode
8649 double vol, minVolBefore = 1e100;
8650 for ( size_t i = 0; i < _simplices.size(); ++i )
8652 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8653 minVolBefore = Min( minVolBefore, vol );
8655 int nbBad = _simplices.size() - nbOkBefore;
8657 if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8659 if ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8660 _smooFunction = _funs[ FUN_LAPLACIAN ];
8661 else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8662 _smooFunction = _funs[ FUN_CENTROIDAL ];
8665 // compute new position for the last _pos using different _funs
8667 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8670 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8671 else if ( _funs[ iFun ] == _smooFunction )
8672 continue; // _smooFunction again
8673 else if ( step > 1 )
8674 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8676 break; // let "easy" functions improve elements around distorted ones
8680 double delta = _curvature->lenDelta( _len );
8682 newPos += _normal * delta;
8685 double segLen = _normal * ( newPos - prevPos );
8686 if ( segLen + delta > 0 )
8687 newPos += _normal * delta;
8689 // double segLenChange = _normal * ( curPos - newPos );
8690 // newPos += 0.5 * _normal * segLenChange;
8694 double minVolAfter = 1e100;
8695 for ( size_t i = 0; i < _simplices.size(); ++i )
8697 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8698 minVolAfter = Min( minVolAfter, vol );
8701 if ( nbOkAfter < nbOkBefore )
8703 if (( isConcaveFace || findBest ) &&
8704 ( nbOkAfter == nbOkBefore ) &&
8705 ( minVolAfter <= minVolBefore )
8709 nbBad = _simplices.size() - nbOkAfter;
8710 minVolBefore = minVolAfter;
8711 nbOkBefore = nbOkAfter;
8713 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8714 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8715 _pos.back() = newPos;
8717 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8718 << ( nbBad ? "--BAD" : ""));
8720 // commented for IPAL0052478
8721 // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8722 // _len += prevPos.Distance(newPos);
8724 if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8726 //_smooFunction = _funs[ iFun ];
8727 // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8728 // << "\t nbBad: " << _simplices.size() - nbOkAfter
8729 // << " minVol: " << minVolAfter
8730 // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8732 continue; // look for a better function
8738 } // loop on smoothing functions
8743 //================================================================================
8745 * \brief Chooses a smoothing technique giving a position most close to an initial one.
8746 * For a correct result, _simplices must contain nodes lying on geometry.
8748 //================================================================================
8750 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8751 const TNode2Edge& n2eMap)
8753 if ( _smooFunction ) return;
8755 // use smoothNefPolygon() near concaveVertices
8756 if ( !concaveVertices.empty() )
8758 _smooFunction = _funs[ FUN_CENTROIDAL ];
8760 Set( ON_CONCAVE_FACE );
8762 for ( size_t i = 0; i < _simplices.size(); ++i )
8764 if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8766 _smooFunction = _funs[ FUN_NEFPOLY ];
8768 // set FUN_CENTROIDAL to neighbor edges
8769 for ( i = 0; i < _neibors.size(); ++i )
8771 if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8773 _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8780 // // this choice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8781 // // where the nodes are smoothed too far along a sphere thus creating
8782 // // inverted _simplices
8783 // double dist[theNbSmooFuns];
8784 // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8785 // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8787 // double minDist = Precision::Infinite();
8788 // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8789 // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8791 // gp_Pnt newP = (this->*_funs[i])();
8792 // dist[i] = p.SquareDistance( newP );
8793 // if ( dist[i]*coef[i] < minDist )
8795 // _smooFunction = _funs[i];
8796 // minDist = dist[i]*coef[i];
8802 _smooFunction = _funs[ FUN_LAPLACIAN ];
8805 // for ( size_t i = 0; i < _simplices.size(); ++i )
8806 // minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8807 // if ( minDim == 0 )
8808 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8809 // else if ( minDim == 1 )
8810 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8814 // for ( int i = 0; i < FUN_NB; ++i )
8816 // //cout << dist[i] << " ";
8817 // if ( _smooFunction == _funs[i] ) {
8819 // //debugMsg( fNames[i] );
8823 // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8826 //================================================================================
8828 * \brief Returns a name of _SmooFunction
8830 //================================================================================
8832 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8835 fun = _smooFunction;
8836 for ( int i = 0; i < theNbSmooFuns; ++i )
8837 if ( fun == _funs[i] )
8840 return theNbSmooFuns;
8843 //================================================================================
8845 * \brief Computes a new node position using Laplacian smoothing
8847 //================================================================================
8849 gp_XYZ _LayerEdge::smoothLaplacian()
8851 gp_XYZ newPos (0,0,0);
8852 for ( size_t i = 0; i < _simplices.size(); ++i )
8853 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8854 newPos /= _simplices.size();
8859 //================================================================================
8861 * \brief Computes a new node position using angular-based smoothing
8863 //================================================================================
8865 gp_XYZ _LayerEdge::smoothAngular()
8867 vector< gp_Vec > edgeDir; edgeDir. reserve( _simplices.size() + 1 );
8868 vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
8869 vector< gp_XYZ > points; points. reserve( _simplices.size() + 1 );
8871 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8873 for ( size_t i = 0; i < _simplices.size(); ++i )
8875 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8876 edgeDir.push_back( p - pPrev );
8877 edgeSize.push_back( edgeDir.back().Magnitude() );
8878 if ( edgeSize.back() < numeric_limits<double>::min() )
8881 edgeSize.pop_back();
8885 edgeDir.back() /= edgeSize.back();
8886 points.push_back( p );
8891 edgeDir.push_back ( edgeDir[0] );
8892 edgeSize.push_back( edgeSize[0] );
8893 pN /= points.size();
8895 gp_XYZ newPos(0,0,0);
8897 for ( size_t i = 0; i < points.size(); ++i )
8899 gp_Vec toN = pN - points[i];
8900 double toNLen = toN.Magnitude();
8901 if ( toNLen < numeric_limits<double>::min() )
8906 gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
8907 double bisecLen = bisec.SquareMagnitude();
8908 if ( bisecLen < numeric_limits<double>::min() )
8910 gp_Vec norm = edgeDir[i] ^ toN;
8911 bisec = norm ^ edgeDir[i];
8912 bisecLen = bisec.SquareMagnitude();
8914 bisecLen = Sqrt( bisecLen );
8918 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8919 sumSize += bisecLen;
8921 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8922 sumSize += ( edgeSize[i] + edgeSize[i+1] );
8928 // project newPos to an average plane
8930 gp_XYZ norm(0,0,0); // plane normal
8931 points.push_back( points[0] );
8932 for ( size_t i = 1; i < points.size(); ++i )
8934 gp_XYZ vec1 = points[ i-1 ] - pN;
8935 gp_XYZ vec2 = points[ i ] - pN;
8936 gp_XYZ cross = vec1 ^ vec2;
8939 if ( cross * norm < numeric_limits<double>::min() )
8940 norm += cross.Reversed();
8944 catch (Standard_Failure) { // if |cross| == 0.
8947 gp_XYZ vec = newPos - pN;
8948 double r = ( norm * vec ) / norm.SquareModulus(); // param [0,1] on norm
8949 newPos = newPos - r * norm;
8954 //================================================================================
8956 * \brief Computes a new node position using weigthed node positions
8958 //================================================================================
8960 gp_XYZ _LayerEdge::smoothLengthWeighted()
8962 vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8963 vector< gp_XYZ > points; points. reserve( _simplices.size() );
8965 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8966 for ( size_t i = 0; i < _simplices.size(); ++i )
8968 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8969 edgeSize.push_back( ( p - pPrev ).Modulus() );
8970 if ( edgeSize.back() < numeric_limits<double>::min() )
8972 edgeSize.pop_back();
8976 points.push_back( p );
8980 edgeSize.push_back( edgeSize[0] );
8982 gp_XYZ newPos(0,0,0);
8984 for ( size_t i = 0; i < points.size(); ++i )
8986 newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8987 sumSize += edgeSize[i] + edgeSize[i+1];
8993 //================================================================================
8995 * \brief Computes a new node position using angular-based smoothing
8997 //================================================================================
8999 gp_XYZ _LayerEdge::smoothCentroidal()
9001 gp_XYZ newPos(0,0,0);
9002 gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
9004 for ( size_t i = 0; i < _simplices.size(); ++i )
9006 gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9007 gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
9008 gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
9009 double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
9012 newPos += gc * size;
9019 //================================================================================
9021 * \brief Computes a new node position located inside a Nef polygon
9023 //================================================================================
9025 gp_XYZ _LayerEdge::smoothNefPolygon()
9026 #ifdef OLD_NEF_POLYGON
9028 gp_XYZ newPos(0,0,0);
9030 // get a plane to search a solution on
9032 vector< gp_XYZ > vecs( _simplices.size() + 1 );
9034 const double tol = numeric_limits<double>::min();
9035 gp_XYZ center(0,0,0);
9036 for ( i = 0; i < _simplices.size(); ++i )
9038 vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
9039 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
9040 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9042 vecs.back() = vecs[0];
9043 center /= _simplices.size();
9045 gp_XYZ zAxis(0,0,0);
9046 for ( i = 0; i < _simplices.size(); ++i )
9047 zAxis += vecs[i] ^ vecs[i+1];
9050 for ( i = 0; i < _simplices.size(); ++i )
9053 if ( yAxis.SquareModulus() > tol )
9056 gp_XYZ xAxis = yAxis ^ zAxis;
9057 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9058 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9059 // p0.Distance( _simplices[2]._nPrev ));
9060 // gp_XYZ center = smoothLaplacian();
9061 // gp_XYZ xAxis, yAxis, zAxis;
9062 // for ( i = 0; i < _simplices.size(); ++i )
9064 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9065 // if ( xAxis.SquareModulus() > tol*tol )
9068 // for ( i = 1; i < _simplices.size(); ++i )
9070 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9071 // zAxis = xAxis ^ yAxis;
9072 // if ( zAxis.SquareModulus() > tol*tol )
9075 // if ( i == _simplices.size() ) return newPos;
9077 yAxis = zAxis ^ xAxis;
9078 xAxis /= xAxis.Modulus();
9079 yAxis /= yAxis.Modulus();
9081 // get half-planes of _simplices
9083 vector< _halfPlane > halfPlns( _simplices.size() );
9085 for ( size_t i = 0; i < _simplices.size(); ++i )
9087 gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9088 gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
9089 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
9090 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
9091 gp_XY vec12 = p2 - p1;
9092 double dist12 = vec12.Modulus();
9096 halfPlns[ nbHP ]._pos = p1;
9097 halfPlns[ nbHP ]._dir = vec12;
9098 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9102 // intersect boundaries of half-planes, define state of intersection points
9103 // in relation to all half-planes and calculate internal point of a 2D polygon
9106 gp_XY newPos2D (0,0);
9108 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9109 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9110 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9112 vector< vector< TIntPntState > > allIntPnts( nbHP );
9113 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9115 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9116 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9118 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9119 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9122 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9124 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9126 if ( iHP1 == iHP2 ) continue;
9128 TIntPntState & ips1 = intPnts1[ iHP2 ];
9129 if ( ips1.second == UNDEF )
9131 // find an intersection point of boundaries of iHP1 and iHP2
9133 if ( iHP2 == iPrev ) // intersection with neighbors is known
9134 ips1.first = halfPlns[ iHP1 ]._pos;
9135 else if ( iHP2 == iNext )
9136 ips1.first = halfPlns[ iHP2 ]._pos;
9137 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9138 ips1.second = NO_INT;
9140 // classify the found intersection point
9141 if ( ips1.second != NO_INT )
9143 ips1.second = NOT_OUT;
9144 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9145 if ( i != iHP1 && i != iHP2 &&
9146 halfPlns[ i ].IsOut( ips1.first, tol ))
9147 ips1.second = IS_OUT;
9149 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9150 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9151 TIntPntState & ips2 = intPnts2[ iHP1 ];
9154 if ( ips1.second == NOT_OUT )
9157 segEnds[ bool(segEnds[0]) ] = & ips1.first;
9161 // find a NOT_OUT segment of boundary which is located between
9162 // two NOT_OUT int points
9165 continue; // no such a segment
9169 // sort points along the boundary
9170 map< double, TIntPntState* > ipsByParam;
9171 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9173 TIntPntState & ips1 = intPnts1[ iHP2 ];
9174 if ( ips1.second != NO_INT )
9176 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
9177 double param = op * halfPlns[ iHP1 ]._dir;
9178 ipsByParam.insert( make_pair( param, & ips1 ));
9181 // look for two neighboring NOT_OUT points
9183 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9184 for ( ; u2ips != ipsByParam.end(); ++u2ips )
9186 TIntPntState & ips1 = *(u2ips->second);
9187 if ( ips1.second == NOT_OUT )
9188 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9189 else if ( nbNotOut >= 2 )
9196 if ( nbNotOut >= 2 )
9198 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9201 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9208 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9217 #else // OLD_NEF_POLYGON
9218 { ////////////////////////////////// NEW
9219 gp_XYZ newPos(0,0,0);
9221 // get a plane to search a solution on
9224 gp_XYZ center(0,0,0);
9225 for ( i = 0; i < _simplices.size(); ++i )
9226 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9227 center /= _simplices.size();
9229 vector< gp_XYZ > vecs( _simplices.size() + 1 );
9230 for ( i = 0; i < _simplices.size(); ++i )
9231 vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9232 vecs.back() = vecs[0];
9234 const double tol = numeric_limits<double>::min();
9235 gp_XYZ zAxis(0,0,0);
9236 for ( i = 0; i < _simplices.size(); ++i )
9238 gp_XYZ cross = vecs[i] ^ vecs[i+1];
9241 if ( cross * zAxis < tol )
9242 zAxis += cross.Reversed();
9246 catch (Standard_Failure) { // if |cross| == 0.
9251 for ( i = 0; i < _simplices.size(); ++i )
9254 if ( yAxis.SquareModulus() > tol )
9257 gp_XYZ xAxis = yAxis ^ zAxis;
9258 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9259 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9260 // p0.Distance( _simplices[2]._nPrev ));
9261 // gp_XYZ center = smoothLaplacian();
9262 // gp_XYZ xAxis, yAxis, zAxis;
9263 // for ( i = 0; i < _simplices.size(); ++i )
9265 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9266 // if ( xAxis.SquareModulus() > tol*tol )
9269 // for ( i = 1; i < _simplices.size(); ++i )
9271 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9272 // zAxis = xAxis ^ yAxis;
9273 // if ( zAxis.SquareModulus() > tol*tol )
9276 // if ( i == _simplices.size() ) return newPos;
9278 yAxis = zAxis ^ xAxis;
9279 xAxis /= xAxis.Modulus();
9280 yAxis /= yAxis.Modulus();
9282 // get half-planes of _simplices
9284 vector< _halfPlane > halfPlns( _simplices.size() );
9286 for ( size_t i = 0; i < _simplices.size(); ++i )
9288 const gp_XYZ& OP1 = vecs[ i ];
9289 const gp_XYZ& OP2 = vecs[ i+1 ];
9290 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
9291 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
9292 gp_XY vec12 = p2 - p1;
9293 double dist12 = vec12.Modulus();
9297 halfPlns[ nbHP ]._pos = p1;
9298 halfPlns[ nbHP ]._dir = vec12;
9299 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9303 // intersect boundaries of half-planes, define state of intersection points
9304 // in relation to all half-planes and calculate internal point of a 2D polygon
9307 gp_XY newPos2D (0,0);
9309 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9310 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9311 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9313 vector< vector< TIntPntState > > allIntPnts( nbHP );
9314 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9316 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9317 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9319 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9320 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9323 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9325 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9327 if ( iHP1 == iHP2 ) continue;
9329 TIntPntState & ips1 = intPnts1[ iHP2 ];
9330 if ( ips1.second == UNDEF )
9332 // find an intersection point of boundaries of iHP1 and iHP2
9334 if ( iHP2 == iPrev ) // intersection with neighbors is known
9335 ips1.first = halfPlns[ iHP1 ]._pos;
9336 else if ( iHP2 == iNext )
9337 ips1.first = halfPlns[ iHP2 ]._pos;
9338 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9339 ips1.second = NO_INT;
9341 // classify the found intersection point
9342 if ( ips1.second != NO_INT )
9344 ips1.second = NOT_OUT;
9345 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9346 if ( i != iHP1 && i != iHP2 &&
9347 halfPlns[ i ].IsOut( ips1.first, tol ))
9348 ips1.second = IS_OUT;
9350 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9351 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9352 TIntPntState & ips2 = intPnts2[ iHP1 ];
9355 if ( ips1.second == NOT_OUT )
9358 segEnds[ bool(segEnds[0]) ] = & ips1.first;
9362 // find a NOT_OUT segment of boundary which is located between
9363 // two NOT_OUT int points
9366 continue; // no such a segment
9370 // sort points along the boundary
9371 map< double, TIntPntState* > ipsByParam;
9372 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9374 TIntPntState & ips1 = intPnts1[ iHP2 ];
9375 if ( ips1.second != NO_INT )
9377 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
9378 double param = op * halfPlns[ iHP1 ]._dir;
9379 ipsByParam.insert( make_pair( param, & ips1 ));
9382 // look for two neighboring NOT_OUT points
9384 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9385 for ( ; u2ips != ipsByParam.end(); ++u2ips )
9387 TIntPntState & ips1 = *(u2ips->second);
9388 if ( ips1.second == NOT_OUT )
9389 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9390 else if ( nbNotOut >= 2 )
9397 if ( nbNotOut >= 2 )
9399 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9402 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9409 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9418 #endif // OLD_NEF_POLYGON
9420 //================================================================================
9422 * \brief Add a new segment to _LayerEdge during inflation
9424 //================================================================================
9426 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
9431 if ( len > _maxLen )
9434 Block( eos.GetData() );
9436 const double lenDelta = len - _len;
9437 if ( lenDelta < len * 1e-3 )
9439 Block( eos.GetData() );
9443 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9444 gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
9446 if ( eos._hyp.IsOffsetMethod() )
9450 SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
9451 while ( faceIt->more() )
9453 const SMDS_MeshElement* face = faceIt->next();
9454 if ( !eos.GetNormal( face, faceNorm ))
9457 // translate plane of a face
9458 gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
9460 // find point of intersection of the face plane located at baryCenter
9461 // and _normal located at newXYZ
9462 double d = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
9463 double dot = ( faceNorm.XYZ() * _normal );
9464 if ( dot < std::numeric_limits<double>::min() )
9465 dot = lenDelta * 1e-3;
9466 double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
9467 newXYZ += step * _normal;
9469 _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
9473 newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
9476 n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
9477 _pos.push_back( newXYZ );
9479 if ( !eos._sWOL.IsNull() )
9483 if ( eos.SWOLType() == TopAbs_EDGE )
9485 double u = Precision::Infinite(); // to force projection w/o distance check
9486 uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
9487 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9488 _pos.back().SetCoord( u, 0, 0 );
9489 if ( _nodes.size() > 1 && uvOK )
9491 SMDS_EdgePositionPtr pos = n->GetPosition();
9492 pos->SetUParameter( u );
9497 gp_XY uv( Precision::Infinite(), 0 );
9498 uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
9499 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9500 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
9501 if ( _nodes.size() > 1 && uvOK )
9503 SMDS_FacePositionPtr pos = n->GetPosition();
9504 pos->SetUParameter( uv.X() );
9505 pos->SetVParameter( uv.Y() );
9510 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
9514 n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
9516 Block( eos.GetData() );
9524 if ( eos.ShapeType() != TopAbs_FACE )
9526 for ( size_t i = 0; i < _neibors.size(); ++i )
9527 //if ( _len > _neibors[i]->GetSmooLen() )
9528 _neibors[i]->Set( MOVED );
9532 dumpMove( n ); //debug
9535 //================================================================================
9537 * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
9539 //================================================================================
9541 void _LayerEdge::Block( _SolidData& data )
9543 //if ( Is( BLOCKED )) return;
9546 SMESH_Comment msg( "#BLOCK shape=");
9547 msg << data.GetShapeEdges( this )->_shapeID
9548 << ", nodes " << _nodes[0]->GetID() << ", " << _nodes.back()->GetID();
9549 dumpCmd( msg + " -- BEGIN");
9552 std::queue<_LayerEdge*> queue;
9555 gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9556 while ( !queue.empty() )
9558 _LayerEdge* edge = queue.front(); queue.pop();
9559 pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9560 pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9561 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9563 _LayerEdge* neibor = edge->_neibors[iN];
9564 if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9566 pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9567 pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9568 double minDist = pSrc.SquareDistance( pSrcN );
9569 minDist = Min( pTgt.SquareDistance( pTgtN ), minDist );
9570 minDist = Min( pSrc.SquareDistance( pTgtN ), minDist );
9571 minDist = Min( pTgt.SquareDistance( pSrcN ), minDist );
9572 double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9573 //if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() ) viscous_layers_00/A3
9575 //newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9576 // newMaxLen *= Min( edge->_lenFactor / neibor->_lenFactor,
9577 // neibor->_lenFactor / edge->_lenFactor );
9579 if ( neibor->_maxLen > newMaxLen )
9581 neibor->SetMaxLen( newMaxLen );
9582 if ( neibor->_maxLen < neibor->_len )
9584 _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9585 int lastStep = neibor->Is( BLOCKED ) ? 1 : 0;
9586 while ( neibor->_len > neibor->_maxLen &&
9587 neibor->NbSteps() > lastStep )
9588 neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9589 neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9590 //neibor->Block( data );
9592 queue.push( neibor );
9596 dumpCmd( msg + " -- END");
9599 //================================================================================
9601 * \brief Remove last inflation step
9603 //================================================================================
9605 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9607 if ( _pos.size() > curStep && _nodes.size() > 1 )
9609 _pos.resize( curStep );
9611 gp_Pnt nXYZ = _pos.back();
9612 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9613 SMESH_TNodeXYZ curXYZ( n );
9614 if ( !eos._sWOL.IsNull() )
9616 TopLoc_Location loc;
9617 if ( eos.SWOLType() == TopAbs_EDGE )
9619 SMDS_EdgePositionPtr pos = n->GetPosition();
9620 pos->SetUParameter( nXYZ.X() );
9622 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9623 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9627 SMDS_FacePositionPtr pos = n->GetPosition();
9628 pos->SetUParameter( nXYZ.X() );
9629 pos->SetVParameter( nXYZ.Y() );
9630 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9631 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9634 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9637 if ( restoreLength )
9639 if ( NbSteps() == 0 )
9641 else if ( IsOnFace() && Is( MOVED ))
9642 _len = ( nXYZ.XYZ() - SMESH_NodeXYZ( _nodes[0] )) * _normal;
9644 _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9650 //================================================================================
9652 * \brief Return index of a _pos distant from _normal
9654 //================================================================================
9656 int _LayerEdge::GetSmoothedPos( const double tol )
9659 for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9661 double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9662 if ( normDist > tol * tol )
9668 //================================================================================
9670 * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9672 //================================================================================
9674 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9676 if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9679 // find the 1st smoothed _pos
9680 int iSmoothed = GetSmoothedPos( tol );
9681 if ( !iSmoothed ) return;
9683 gp_XYZ normal = _normal;
9684 if ( Is( NORMAL_UPDATED ))
9687 for ( size_t i = 0; i < _neibors.size(); ++i )
9689 if ( _neibors[i]->IsOnFace() )
9691 double dot = _normal * _neibors[i]->_normal;
9694 normal = _neibors[i]->_normal;
9700 for ( size_t i = 1; i < _pos.size(); ++i )
9702 normal = _pos[i] - _pos[0];
9703 double size = normal.Modulus();
9704 if ( size > RealSmall() )
9711 const double r = 0.2;
9712 for ( int iter = 0; iter < 50; ++iter )
9715 for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9717 gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9718 gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9720 double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9721 double newLen = ( 1-r ) * midLen + r * segLen[i];
9722 const_cast< double& >( segLen[i] ) = newLen;
9723 // check angle between normal and (_pos[i+1], _pos[i] )
9724 gp_XYZ posDir = _pos[i+1] - _pos[i];
9725 double size = posDir.SquareModulus();
9726 if ( size > RealSmall() )
9727 minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9729 if ( minDot > 0.5 * 0.5 )
9735 //================================================================================
9737 * \brief Print flags
9739 //================================================================================
9741 std::string _LayerEdge::DumpFlags() const
9744 for ( int flag = 1; flag < 0x1000000; flag *= 2 )
9745 if ( _flags & flag )
9747 EFlags f = (EFlags) flag;
9749 case TO_SMOOTH: dump << "TO_SMOOTH"; break;
9750 case MOVED: dump << "MOVED"; break;
9751 case SMOOTHED: dump << "SMOOTHED"; break;
9752 case DIFFICULT: dump << "DIFFICULT"; break;
9753 case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
9754 case BLOCKED: dump << "BLOCKED"; break;
9755 case INTERSECTED: dump << "INTERSECTED"; break;
9756 case NORMAL_UPDATED: dump << "NORMAL_UPDATED"; break;
9757 case UPD_NORMAL_CONV: dump << "UPD_NORMAL_CONV"; break;
9758 case MARKED: dump << "MARKED"; break;
9759 case MULTI_NORMAL: dump << "MULTI_NORMAL"; break;
9760 case NEAR_BOUNDARY: dump << "NEAR_BOUNDARY"; break;
9761 case SMOOTHED_C1: dump << "SMOOTHED_C1"; break;
9762 case DISTORTED: dump << "DISTORTED"; break;
9763 case RISKY_SWOL: dump << "RISKY_SWOL"; break;
9764 case SHRUNK: dump << "SHRUNK"; break;
9765 case UNUSED_FLAG: dump << "UNUSED_FLAG"; break;
9769 cout << dump << endl;
9774 //================================================================================
9776 * \brief Create layers of prisms
9778 //================================================================================
9780 bool _ViscousBuilder::refine(_SolidData& data)
9782 SMESH_MesherHelper& helper = data.GetHelper();
9783 helper.SetElementsOnShape(false);
9785 Handle(Geom_Curve) curve;
9786 Handle(ShapeAnalysis_Surface) surface;
9787 TopoDS_Edge geomEdge;
9788 TopoDS_Face geomFace;
9789 TopLoc_Location loc;
9792 vector< gp_XYZ > pos3D;
9793 bool isOnEdge, isTooConvexFace = false;
9794 TGeomID prevBaseId = -1;
9795 TNode2Edge* n2eMap = 0;
9796 TNode2Edge::iterator n2e;
9798 // Create intermediate nodes on each _LayerEdge
9800 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9802 _EdgesOnShape& eos = data._edgesOnShape[iS];
9803 if ( eos._edges.empty() ) continue;
9805 if ( eos._edges[0]->_nodes.size() < 2 )
9806 continue; // on _noShrinkShapes
9808 // get data of a shrink shape
9810 geomEdge.Nullify(); geomFace.Nullify();
9811 curve.Nullify(); surface.Nullify();
9812 if ( !eos._sWOL.IsNull() )
9814 isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9817 geomEdge = TopoDS::Edge( eos._sWOL );
9818 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
9822 geomFace = TopoDS::Face( eos._sWOL );
9823 surface = helper.GetSurface( geomFace );
9826 else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9828 geomFace = TopoDS::Face( eos._shape );
9829 surface = helper.GetSurface( geomFace );
9830 // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9831 for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9832 eos._eosC1[ i ]->_toSmooth = true;
9834 isTooConvexFace = false;
9835 if ( _ConvexFace* cf = data.GetConvexFace( eos._shapeID ))
9836 isTooConvexFace = cf->_isTooCurved;
9839 vector< double > segLen;
9840 for ( size_t i = 0; i < eos._edges.size(); ++i )
9842 _LayerEdge& edge = *eos._edges[i];
9843 if ( edge._pos.size() < 2 )
9846 // get accumulated length of segments
9847 segLen.resize( edge._pos.size() );
9849 if ( eos._sWOL.IsNull() )
9851 bool useNormal = true;
9852 bool usePos = false;
9853 bool smoothed = false;
9854 double preci = 0.1 * edge._len;
9855 if ( eos._toSmooth && edge._pos.size() > 2 )
9857 smoothed = edge.GetSmoothedPos( preci );
9861 if ( !surface.IsNull() && !isTooConvexFace ) // edge smoothed on FACE
9863 useNormal = usePos = false;
9864 gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9865 for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9867 uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9868 if ( surface->Gap() < 2. * edge._len )
9869 segLen[j] = surface->Gap();
9875 else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9877 #ifndef __NODES_AT_POS
9878 useNormal = usePos = false;
9879 edge._pos[1] = edge._pos.back();
9880 edge._pos.resize( 2 );
9882 segLen[ 1 ] = edge._len;
9885 if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9887 useNormal = usePos = false;
9888 _LayerEdge tmpEdge; // get original _normal
9889 tmpEdge._nodes.push_back( edge._nodes[0] );
9890 if ( !setEdgeData( tmpEdge, eos, helper, data ))
9893 for ( size_t j = 1; j < edge._pos.size(); ++j )
9894 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9898 for ( size_t j = 1; j < edge._pos.size(); ++j )
9899 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9903 for ( size_t j = 1; j < edge._pos.size(); ++j )
9904 segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9908 bool swapped = ( edge._pos.size() > 2 );
9912 for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9913 if ( segLen[j] > segLen.back() )
9915 segLen.erase( segLen.begin() + j );
9916 edge._pos.erase( edge._pos.begin() + j );
9919 else if ( segLen[j] < segLen[j-1] )
9921 std::swap( segLen[j], segLen[j-1] );
9922 std::swap( edge._pos[j], edge._pos[j-1] );
9927 // smooth a path formed by edge._pos
9928 #ifndef __NODES_AT_POS
9929 if (( smoothed ) /*&&
9930 ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9931 edge.SmoothPos( segLen, preci );
9934 else if ( eos._isRegularSWOL ) // usual SWOL
9936 if ( edge.Is( _LayerEdge::SMOOTHED ))
9938 SMESH_NodeXYZ p0( edge._nodes[0] );
9939 for ( size_t j = 1; j < edge._pos.size(); ++j )
9941 gp_XYZ pj = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9942 segLen[j] = ( pj - p0 ) * edge._normal;
9947 for ( size_t j = 1; j < edge._pos.size(); ++j )
9948 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9951 else if ( !surface.IsNull() ) // SWOL surface with singularities
9953 pos3D.resize( edge._pos.size() );
9954 for ( size_t j = 0; j < edge._pos.size(); ++j )
9955 pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9957 for ( size_t j = 1; j < edge._pos.size(); ++j )
9958 segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9961 // allocate memory for new nodes if it is not yet refined
9962 const SMDS_MeshNode* tgtNode = edge._nodes.back();
9963 if ( edge._nodes.size() == 2 )
9965 #ifdef __NODES_AT_POS
9966 int nbNodes = edge._pos.size();
9968 int nbNodes = eos._hyp.GetNumberLayers() + 1;
9970 edge._nodes.resize( nbNodes, 0 );
9972 edge._nodes.back() = tgtNode;
9974 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9975 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9976 if ( baseShapeId != prevBaseId )
9978 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9979 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9980 prevBaseId = baseShapeId;
9982 _LayerEdge* edgeOnSameNode = 0;
9983 bool useExistingPos = false;
9984 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9986 edgeOnSameNode = n2e->second;
9987 useExistingPos = ( edgeOnSameNode->_len < edge._len );
9988 const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9989 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
9992 SMDS_EdgePositionPtr epos = lastPos;
9993 epos->SetUParameter( otherTgtPos.X() );
9997 SMDS_FacePositionPtr fpos = lastPos;
9998 fpos->SetUParameter( otherTgtPos.X() );
9999 fpos->SetVParameter( otherTgtPos.Y() );
10002 // calculate height of the first layer
10004 const double T = segLen.back(); //data._hyp.GetTotalThickness();
10005 const double f = eos._hyp.GetStretchFactor();
10006 const int N = eos._hyp.GetNumberLayers();
10007 const double fPowN = pow( f, N );
10008 if ( fPowN - 1 <= numeric_limits<double>::min() )
10011 h0 = T * ( f - 1 )/( fPowN - 1 );
10013 const double zeroLen = std::numeric_limits<double>::min();
10015 // create intermediate nodes
10016 double hSum = 0, hi = h0/f;
10018 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
10020 // compute an intermediate position
10023 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
10025 int iPrevSeg = iSeg-1;
10026 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
10028 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
10029 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
10030 #ifdef __NODES_AT_POS
10031 pos = edge._pos[ iStep ];
10033 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
10034 if ( !eos._sWOL.IsNull() )
10036 // compute XYZ by parameters <pos>
10041 pos = curve->Value( u ).Transformed(loc);
10043 else if ( eos._isRegularSWOL )
10045 uv.SetCoord( pos.X(), pos.Y() );
10047 pos = surface->Value( pos.X(), pos.Y() );
10051 uv.SetCoord( pos.X(), pos.Y() );
10052 gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
10053 uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
10055 pos = surface->Value( uv );
10058 // create or update the node
10061 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
10062 if ( !eos._sWOL.IsNull() )
10065 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
10067 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
10071 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
10076 if ( !eos._sWOL.IsNull() )
10078 // make average pos from new and current parameters
10081 //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
10082 if ( useExistingPos )
10083 u = helper.GetNodeU( geomEdge, node );
10084 pos = curve->Value( u ).Transformed(loc);
10086 SMDS_EdgePositionPtr epos = node->GetPosition();
10087 epos->SetUParameter( u );
10091 //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
10092 if ( useExistingPos )
10093 uv = helper.GetNodeUV( geomFace, node );
10094 pos = surface->Value( uv );
10096 SMDS_FacePositionPtr fpos = node->GetPosition();
10097 fpos->SetUParameter( uv.X() );
10098 fpos->SetVParameter( uv.Y() );
10101 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
10103 } // loop on edge._nodes
10105 if ( !eos._sWOL.IsNull() ) // prepare for shrink()
10108 edge._pos.back().SetCoord( u, 0,0);
10110 edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
10112 if ( edgeOnSameNode )
10113 edgeOnSameNode->_pos.back() = edge._pos.back();
10116 } // loop on eos._edges to create nodes
10119 if ( !getMeshDS()->IsEmbeddedMode() )
10120 // Log node movement
10121 for ( size_t i = 0; i < eos._edges.size(); ++i )
10123 SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
10124 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
10131 helper.SetElementsOnShape(true);
10133 vector< vector<const SMDS_MeshNode*>* > nnVec;
10134 set< vector<const SMDS_MeshNode*>* > nnSet;
10135 set< int > degenEdgeInd;
10136 vector<const SMDS_MeshElement*> degenVols;
10138 TopExp_Explorer exp( data._solid, TopAbs_FACE );
10139 for ( ; exp.More(); exp.Next() )
10141 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
10142 if ( data._ignoreFaceIds.count( faceID ))
10144 const bool isReversedFace = data._reversedFaceIds.count( faceID );
10145 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
10146 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
10147 while ( fIt->more() )
10149 const SMDS_MeshElement* face = fIt->next();
10150 const int nbNodes = face->NbCornerNodes();
10151 nnVec.resize( nbNodes );
10153 degenEdgeInd.clear();
10154 size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
10155 SMDS_NodeIteratorPtr nIt = face->nodeIterator();
10156 for ( int iN = 0; iN < nbNodes; ++iN )
10158 const SMDS_MeshNode* n = nIt->next();
10159 _LayerEdge* edge = data._n2eMap[ n ];
10160 const int i = isReversedFace ? nbNodes-1-iN : iN;
10161 nnVec[ i ] = & edge->_nodes;
10162 maxZ = std::max( maxZ, nnVec[ i ]->size() );
10163 minZ = std::min( minZ, nnVec[ i ]->size() );
10165 if ( helper.HasDegeneratedEdges() )
10166 nnSet.insert( nnVec[ i ]);
10171 if ( 0 < nnSet.size() && nnSet.size() < 3 )
10179 for ( size_t iZ = 1; iZ < minZ; ++iZ )
10180 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
10181 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
10183 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10185 for ( int iN = 0; iN < nbNodes; ++iN )
10186 if ( nnVec[ iN ]->size() < iZ+1 )
10187 degenEdgeInd.insert( iN );
10189 if ( degenEdgeInd.size() == 1 ) // PYRAM
10191 int i2 = *degenEdgeInd.begin();
10192 int i0 = helper.WrapIndex( i2 - 1, nbNodes );
10193 int i1 = helper.WrapIndex( i2 + 1, nbNodes );
10194 helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
10195 (*nnVec[i1])[iZ ], (*nnVec[i0])[iZ ], (*nnVec[i2]).back());
10199 int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
10200 helper.AddVolume( (*nnVec[ 0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
10201 (*nnVec[ 1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
10202 (*nnVec[ 2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
10203 (*nnVec[ i3 ])[ iZ ]);
10211 for ( size_t iZ = 1; iZ < minZ; ++iZ )
10212 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
10213 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
10214 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
10215 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
10217 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10219 for ( int iN = 0; iN < nbNodes; ++iN )
10220 if ( nnVec[ iN ]->size() < iZ+1 )
10221 degenEdgeInd.insert( iN );
10223 switch ( degenEdgeInd.size() )
10227 int i2 = *degenEdgeInd.begin();
10228 int i3 = *degenEdgeInd.rbegin();
10229 bool ok = ( i3 - i2 == 1 );
10230 if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
10231 int i0 = helper.WrapIndex( i3 + 1, nbNodes );
10232 int i1 = helper.WrapIndex( i0 + 1, nbNodes );
10234 const SMDS_MeshElement* vol =
10235 helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
10236 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
10238 degenVols.push_back( vol );
10242 default: // degen HEX
10244 const SMDS_MeshElement* vol =
10245 helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
10246 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
10247 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
10248 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
10249 nnVec[0]->size() > iZ ? (*nnVec[0])[iZ] : nnVec[0]->back(),
10250 nnVec[1]->size() > iZ ? (*nnVec[1])[iZ] : nnVec[1]->back(),
10251 nnVec[2]->size() > iZ ? (*nnVec[2])[iZ] : nnVec[2]->back(),
10252 nnVec[3]->size() > iZ ? (*nnVec[3])[iZ] : nnVec[3]->back());
10253 degenVols.push_back( vol );
10260 return error("Not supported type of element", data._index);
10262 } // switch ( nbNodes )
10263 } // while ( fIt->more() )
10266 if ( !degenVols.empty() )
10268 SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
10269 if ( !err || err->IsOK() )
10271 SMESH_BadInputElements* badElems =
10272 new SMESH_BadInputElements( getMeshDS(), COMPERR_WARNING, "Bad quality volumes created" );
10273 badElems->myBadElements.insert( badElems->myBadElements.end(),
10274 degenVols.begin(),degenVols.end() );
10275 err.reset( badElems );
10282 //================================================================================
10284 * \brief Shrink 2D mesh on faces to let space for inflated layers
10286 //================================================================================
10288 bool _ViscousBuilder::shrink(_SolidData& theData)
10290 // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
10291 // _LayerEdge's inflated along FACE or EDGE)
10292 map< TGeomID, list< _SolidData* > > f2sdMap;
10293 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10295 _SolidData& data = _sdVec[i];
10296 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
10297 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
10298 if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrinkedFaces.Contains( s2s->second ))
10300 f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
10302 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
10303 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
10304 // by StdMeshers_QuadToTriaAdaptor
10305 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
10307 SMESH_ProxyMesh::SubMesh* proxySub =
10308 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
10309 if ( proxySub->NbElements() == 0 )
10311 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10312 while ( fIt->more() )
10314 const SMDS_MeshElement* f = fIt->next();
10315 // as a result 3D algo will use elements from proxySub and not from smDS
10316 proxySub->AddElement( f );
10317 f->setIsMarked( true );
10319 // Mark nodes on the FACE to discriminate them from nodes
10320 // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
10321 for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
10323 const SMDS_MeshNode* n = f->GetNode( iN );
10324 if ( n->GetPosition()->GetDim() == 2 )
10325 n->setIsMarked( true );
10333 SMESH_MesherHelper helper( *_mesh );
10334 helper.ToFixNodeParameters( true );
10337 map< TGeomID, _Shrinker1D > e2shrMap;
10338 vector< _EdgesOnShape* > subEOS;
10339 vector< _LayerEdge* > lEdges;
10341 // loop on FACEs to shrink mesh on
10342 map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
10343 for ( ; f2sd != f2sdMap.end(); ++f2sd )
10345 list< _SolidData* > & dataList = f2sd->second;
10346 if ( dataList.front()->_n2eMap.empty() ||
10347 dataList.back() ->_n2eMap.empty() )
10348 continue; // not yet computed
10349 if ( dataList.front() != &theData &&
10350 dataList.back() != &theData )
10353 _SolidData& data = *dataList.front();
10354 _SolidData* data2 = dataList.size() > 1 ? dataList.back() : 0;
10355 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
10356 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
10357 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
10359 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
10361 _shrinkedFaces.Add( F );
10362 helper.SetSubShape( F );
10364 // ===========================
10365 // Prepare data for shrinking
10366 // ===========================
10368 // Collect nodes to smooth (they are marked at the beginning of this method)
10369 vector < const SMDS_MeshNode* > smoothNodes;
10371 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
10372 while ( nIt->more() )
10374 const SMDS_MeshNode* n = nIt->next();
10375 if ( n->isMarked() )
10376 smoothNodes.push_back( n );
10379 // Find out face orientation
10380 double refSign = 1;
10381 const set<TGeomID> ignoreShapes;
10383 if ( !smoothNodes.empty() )
10385 vector<_Simplex> simplices;
10386 _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
10387 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
10388 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
10389 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
10390 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
10394 // Find _LayerEdge's inflated along F
10398 SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
10399 /*complexFirst=*/true); //!!!
10400 while ( subIt->more() )
10402 const TGeomID subID = subIt->next()->GetId();
10403 if ( data._noShrinkShapes.count( subID ))
10405 _EdgesOnShape* eos = data.GetShapeEdges( subID );
10406 if ( !eos || eos->_sWOL.IsNull() )
10407 if ( data2 ) // check in adjacent SOLID
10409 eos = data2->GetShapeEdges( subID );
10410 if ( !eos || eos->_sWOL.IsNull() )
10413 subEOS.push_back( eos );
10415 for ( size_t i = 0; i < eos->_edges.size(); ++i )
10417 lEdges.push_back( eos->_edges[ i ] );
10418 prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
10423 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
10424 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10425 while ( fIt->more() )
10426 if ( const SMDS_MeshElement* f = fIt->next() )
10427 dumpChangeNodes( f );
10430 // Replace source nodes by target nodes in mesh faces to shrink
10431 dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
10432 const SMDS_MeshNode* nodes[20];
10433 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10435 _EdgesOnShape& eos = * subEOS[ iS ];
10436 for ( size_t i = 0; i < eos._edges.size(); ++i )
10438 _LayerEdge& edge = *eos._edges[i];
10439 const SMDS_MeshNode* srcNode = edge._nodes[0];
10440 const SMDS_MeshNode* tgtNode = edge._nodes.back();
10441 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
10442 while ( fIt->more() )
10444 const SMDS_MeshElement* f = fIt->next();
10445 if ( !smDS->Contains( f ) || !f->isMarked() )
10447 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
10448 for ( int iN = 0; nIt->more(); ++iN )
10450 const SMDS_MeshNode* n = nIt->next();
10451 nodes[iN] = ( n == srcNode ? tgtNode : n );
10453 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
10454 dumpChangeNodes( f );
10460 // find out if a FACE is concave
10461 const bool isConcaveFace = isConcave( F, helper );
10463 // Create _SmoothNode's on face F
10464 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
10466 dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
10467 const bool sortSimplices = isConcaveFace;
10468 for ( size_t i = 0; i < smoothNodes.size(); ++i )
10470 const SMDS_MeshNode* n = smoothNodes[i];
10471 nodesToSmooth[ i ]._node = n;
10472 // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
10473 _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
10474 // fix up incorrect uv of nodes on the FACE
10475 helper.GetNodeUV( F, n, 0, &isOkUV);
10480 //if ( nodesToSmooth.empty() ) continue;
10482 // Find EDGE's to shrink and set simpices to LayerEdge's
10483 set< _Shrinker1D* > eShri1D;
10485 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10487 _EdgesOnShape& eos = * subEOS[ iS ];
10488 if ( eos.SWOLType() == TopAbs_EDGE )
10490 SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
10491 _Shrinker1D& shrinker = e2shrMap[ edgeSM->GetId() ];
10492 eShri1D.insert( & shrinker );
10493 shrinker.AddEdge( eos._edges[0], eos, helper );
10494 VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
10495 // restore params of nodes on EDGE if the EDGE has been already
10496 // shrinked while shrinking other FACE
10497 shrinker.RestoreParams();
10499 for ( size_t i = 0; i < eos._edges.size(); ++i )
10501 _LayerEdge& edge = * eos._edges[i];
10502 _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
10504 // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
10505 // not-marked nodes are those added by refine()
10506 edge._nodes.back()->setIsMarked( true );
10511 bool toFixTria = false; // to improve quality of trias by diagonal swap
10512 if ( isConcaveFace )
10514 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
10515 if ( hasTria != hasQuad ) {
10516 toFixTria = hasTria;
10519 set<int> nbNodesSet;
10520 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10521 while ( fIt->more() && nbNodesSet.size() < 2 )
10522 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
10523 toFixTria = ( *nbNodesSet.begin() == 3 );
10527 // ==================
10528 // Perform shrinking
10529 // ==================
10531 bool shrinked = true;
10532 int nbBad, shriStep=0, smooStep=0;
10533 _SmoothNode::SmoothType smoothType
10534 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
10535 SMESH_Comment errMsg;
10539 // Move boundary nodes (actually just set new UV)
10540 // -----------------------------------------------
10541 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
10543 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10545 _EdgesOnShape& eos = * subEOS[ iS ];
10546 for ( size_t i = 0; i < eos._edges.size(); ++i )
10548 shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
10553 // Move nodes on EDGE's
10554 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
10555 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
10556 for ( ; shr != eShri1D.end(); ++shr )
10557 (*shr)->Compute( /*set3D=*/false, helper );
10560 // -----------------
10561 int nbNoImpSteps = 0;
10564 while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
10566 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10568 int oldBadNb = nbBad;
10571 // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
10572 _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
10573 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10575 moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
10576 smooTy, /*set3D=*/isConcaveFace);
10578 if ( nbBad < oldBadNb )
10588 errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
10589 if ( shriStep > 200 )
10590 errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
10591 if ( !errMsg.empty() )
10594 // Fix narrow triangles by swapping diagonals
10595 // ---------------------------------------
10598 set<const SMDS_MeshNode*> usedNodes;
10599 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
10601 // update working data
10602 set<const SMDS_MeshNode*>::iterator n;
10603 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
10605 n = usedNodes.find( nodesToSmooth[ i ]._node );
10606 if ( n != usedNodes.end())
10608 _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
10609 nodesToSmooth[ i ]._simplices,
10610 ignoreShapes, NULL,
10611 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
10612 usedNodes.erase( n );
10615 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
10617 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
10618 if ( n != usedNodes.end())
10620 _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
10621 lEdges[i]->_simplices,
10623 usedNodes.erase( n );
10627 // TODO: check effect of this additional smooth
10628 // additional laplacian smooth to increase allowed shrink step
10629 // for ( int st = 1; st; --st )
10631 // dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10632 // for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10634 // nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10635 // _SmoothNode::LAPLACIAN,/*set3D=*/false);
10639 } // while ( shrinked )
10641 if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
10643 debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
10646 SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
10648 vector< const SMDS_MeshElement* > facesToRm;
10651 facesToRm.reserve( psm->NbElements() );
10652 for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
10653 facesToRm.push_back( ite->next() );
10655 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10656 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10659 for ( size_t i = 0; i < facesToRm.size(); ++i )
10660 getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
10664 TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
10665 for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
10666 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10667 nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
10668 subEOS[iS]->_edges[i]->_nodes.end() );
10670 SMDS_NodeIteratorPtr itn = smDS->GetNodes();
10671 while ( itn->more() ) {
10672 const SMDS_MeshNode* n = itn->next();
10673 if ( !nodesToKeep.count( n ))
10674 getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
10677 // restore position and UV of target nodes
10679 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10680 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10682 _LayerEdge* edge = subEOS[iS]->_edges[i];
10683 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
10684 if ( edge->_pos.empty() ||
10685 edge->Is( _LayerEdge::SHRUNK )) continue;
10686 if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
10688 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
10689 pos->SetUParameter( edge->_pos[0].X() );
10690 pos->SetVParameter( edge->_pos[0].Y() );
10691 p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10695 SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
10696 pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10697 p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10699 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10700 dumpMove( tgtNode );
10702 // shrink EDGE sub-meshes and set proxy sub-meshes
10703 UVPtStructVec uvPtVec;
10704 set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10705 for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10707 _Shrinker1D* shr = (*shrIt);
10708 shr->Compute( /*set3D=*/true, helper );
10710 // set proxy mesh of EDGEs w/o layers
10711 map< double, const SMDS_MeshNode* > nodes;
10712 SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10713 // remove refinement nodes
10714 const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10715 const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10716 map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10717 if ( u2n->second == sn0 || u2n->second == sn1 )
10719 while ( u2n->second != tn0 && u2n->second != tn1 )
10721 nodes.erase( nodes.begin(), u2n );
10723 u2n = --nodes.end();
10724 if ( u2n->second == sn0 || u2n->second == sn1 )
10726 while ( u2n->second != tn0 && u2n->second != tn1 )
10728 nodes.erase( ++u2n, nodes.end() );
10730 // set proxy sub-mesh
10731 uvPtVec.resize( nodes.size() );
10732 u2n = nodes.begin();
10733 BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10734 for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10736 uvPtVec[ i ].node = u2n->second;
10737 uvPtVec[ i ].param = u2n->first;
10738 uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10740 StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10741 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10744 // set proxy mesh of EDGEs with layers
10745 vector< _LayerEdge* > edges;
10746 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10748 _EdgesOnShape& eos = * subEOS[ iS ];
10749 if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10751 const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10752 data.SortOnEdge( E, eos._edges );
10755 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10756 if ( !eov->_edges.empty() )
10757 edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10759 edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10761 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10762 if ( !eov->_edges.empty() )
10763 edges.push_back( eov->_edges[0] ); // on last VERTEX
10765 uvPtVec.resize( edges.size() );
10766 for ( size_t i = 0; i < edges.size(); ++i )
10768 uvPtVec[ i ].node = edges[i]->_nodes.back();
10769 uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10770 uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10772 BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10773 StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10774 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10776 // temporary clear the FACE sub-mesh from faces made by refine()
10777 vector< const SMDS_MeshElement* > elems;
10778 elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10779 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10780 elems.push_back( ite->next() );
10781 for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10782 elems.push_back( ite->next() );
10785 // compute the mesh on the FACE
10786 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10787 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10789 // re-fill proxy sub-meshes of the FACE
10790 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10791 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10792 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10793 psm->AddElement( ite->next() );
10796 for ( size_t i = 0; i < elems.size(); ++i )
10797 smDS->AddElement( elems[i] );
10799 if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10800 return error( errMsg );
10802 } // end of re-meshing in case of failed smoothing
10805 // No wrongly shaped faces remain; final smooth. Set node XYZ.
10806 bool isStructuredFixed = false;
10807 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10808 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10809 if ( !isStructuredFixed )
10811 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10812 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10814 for ( int st = 3; st; --st )
10817 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10818 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10819 case 3: smoothType = _SmoothNode::ANGULAR; break;
10821 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10822 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10824 nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10825 smoothType,/*set3D=*/st==1 );
10830 if ( !getMeshDS()->IsEmbeddedMode() )
10831 // Log node movement
10832 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10834 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10835 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10839 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10840 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10842 VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
10844 } // loop on FACES to shrink mesh on
10847 // Replace source nodes by target nodes in shrinked mesh edges
10849 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10850 for ( ; e2shr != e2shrMap.end(); ++e2shr )
10851 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10856 //================================================================================
10858 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10860 //================================================================================
10862 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
10863 _EdgesOnShape& eos,
10864 SMESH_MesherHelper& helper,
10865 const SMESHDS_SubMesh* faceSubMesh)
10867 const SMDS_MeshNode* srcNode = edge._nodes[0];
10868 const SMDS_MeshNode* tgtNode = edge._nodes.back();
10870 if ( eos.SWOLType() == TopAbs_FACE )
10872 if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10875 edge.Set( _LayerEdge::SHRUNK );
10876 return srcNode == tgtNode;
10878 gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() ); //helper.GetNodeUV( F, srcNode );
10879 gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10880 gp_Vec2d uvDir( srcUV, tgtUV );
10881 double uvLen = uvDir.Magnitude();
10883 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10886 //edge._pos.resize(1);
10887 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10889 // set UV of source node to target node
10890 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
10891 pos->SetUParameter( srcUV.X() );
10892 pos->SetVParameter( srcUV.Y() );
10894 else // _sWOL is TopAbs_EDGE
10896 if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10899 edge.Set( _LayerEdge::SHRUNK );
10900 return srcNode == tgtNode;
10902 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
10903 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10904 if ( !edgeSM || edgeSM->NbElements() == 0 )
10905 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10907 const SMDS_MeshNode* n2 = 0;
10908 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10909 while ( eIt->more() && !n2 )
10911 const SMDS_MeshElement* e = eIt->next();
10912 if ( !edgeSM->Contains(e)) continue;
10913 n2 = e->GetNode( 0 );
10914 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10917 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10919 double uSrc = helper.GetNodeU( E, srcNode, n2 );
10920 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10921 double u2 = helper.GetNodeU( E, n2, srcNode );
10923 //edge._pos.clear();
10925 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10927 // tgtNode is located so that it does not make faces with wrong orientation
10928 edge.Set( _LayerEdge::SHRUNK );
10931 //edge._pos.resize(1);
10932 edge._pos[0].SetCoord( U_TGT, uTgt );
10933 edge._pos[0].SetCoord( U_SRC, uSrc );
10934 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10936 edge._simplices.resize( 1 );
10937 edge._simplices[0]._nPrev = n2;
10939 // set U of source node to the target node
10940 SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
10941 pos->SetUParameter( uSrc );
10946 //================================================================================
10948 * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10950 //================================================================================
10952 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10954 if ( edge._nodes.size() == 1 )
10959 const SMDS_MeshNode* srcNode = edge._nodes[0];
10960 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10961 if ( S.IsNull() ) return;
10965 switch ( S.ShapeType() )
10970 TopLoc_Location loc;
10971 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10972 if ( curve.IsNull() ) return;
10973 SMDS_EdgePositionPtr ePos = srcNode->GetPosition();
10974 p = curve->Value( ePos->GetUParameter() );
10977 case TopAbs_VERTEX:
10979 p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10984 getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10985 dumpMove( srcNode );
10989 //================================================================================
10991 * \brief Try to fix triangles with high aspect ratio by swapping diagonals
10993 //================================================================================
10995 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
10996 SMESH_MesherHelper& helper,
10999 set<const SMDS_MeshNode*> * involvedNodes)
11001 SMESH::Controls::AspectRatio qualifier;
11002 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
11003 const double maxAspectRatio = is2D ? 4. : 2;
11004 _NodeCoordHelper xyz( F, helper, is2D );
11006 // find bad triangles
11008 vector< const SMDS_MeshElement* > badTrias;
11009 vector< double > badAspects;
11010 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
11011 SMDS_ElemIteratorPtr fIt = sm->GetElements();
11012 while ( fIt->more() )
11014 const SMDS_MeshElement * f = fIt->next();
11015 if ( f->NbCornerNodes() != 3 ) continue;
11016 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
11017 double aspect = qualifier.GetValue( points );
11018 if ( aspect > maxAspectRatio )
11020 badTrias.push_back( f );
11021 badAspects.push_back( aspect );
11026 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
11027 SMDS_ElemIteratorPtr fIt = sm->GetElements();
11028 while ( fIt->more() )
11030 const SMDS_MeshElement * f = fIt->next();
11031 if ( f->NbCornerNodes() == 3 )
11032 dumpChangeNodes( f );
11036 if ( badTrias.empty() )
11039 // find couples of faces to swap diagonal
11041 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
11042 vector< T2Trias > triaCouples;
11044 TIDSortedElemSet involvedFaces, emptySet;
11045 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
11048 double aspRatio [3];
11051 if ( !involvedFaces.insert( badTrias[iTia] ).second )
11053 for ( int iP = 0; iP < 3; ++iP )
11054 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
11056 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
11057 int bestCouple = -1;
11058 for ( int iSide = 0; iSide < 3; ++iSide )
11060 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
11061 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
11062 trias [iSide].first = badTrias[iTia];
11063 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
11065 if (( ! trias[iSide].second ) ||
11066 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
11067 ( ! sm->Contains( trias[iSide].second )))
11070 // aspect ratio of an adjacent tria
11071 for ( int iP = 0; iP < 3; ++iP )
11072 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
11073 double aspectInit = qualifier.GetValue( points2 );
11075 // arrange nodes as after diag-swaping
11076 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
11077 i3 = helper.WrapIndex( i1-1, 3 );
11079 i3 = helper.WrapIndex( i1+1, 3 );
11081 points1( 1+ iSide ) = points2( 1+ i3 );
11082 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
11084 // aspect ratio after diag-swaping
11085 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
11086 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
11089 // prevent inversion of a triangle
11090 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
11091 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
11092 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
11095 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
11096 bestCouple = iSide;
11099 if ( bestCouple >= 0 )
11101 triaCouples.push_back( trias[bestCouple] );
11102 involvedFaces.insert ( trias[bestCouple].second );
11106 involvedFaces.erase( badTrias[iTia] );
11109 if ( triaCouples.empty() )
11114 SMESH_MeshEditor editor( helper.GetMesh() );
11115 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11116 for ( size_t i = 0; i < triaCouples.size(); ++i )
11118 dumpChangeNodes( triaCouples[i].first );
11119 dumpChangeNodes( triaCouples[i].second );
11120 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
11123 if ( involvedNodes )
11124 for ( size_t i = 0; i < triaCouples.size(); ++i )
11126 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
11127 triaCouples[i].first->end_nodes() );
11128 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
11129 triaCouples[i].second->end_nodes() );
11132 // just for debug dump resulting triangles
11133 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11134 for ( size_t i = 0; i < triaCouples.size(); ++i )
11136 dumpChangeNodes( triaCouples[i].first );
11137 dumpChangeNodes( triaCouples[i].second );
11141 //================================================================================
11143 * \brief Move target node to it's final position on the FACE during shrinking
11145 //================================================================================
11147 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
11148 const TopoDS_Face& F,
11149 _EdgesOnShape& eos,
11150 SMESH_MesherHelper& helper )
11153 return false; // already at the target position
11155 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
11157 if ( eos.SWOLType() == TopAbs_FACE )
11159 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
11160 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
11161 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
11162 const double uvLen = tgtUV.Distance( curUV );
11163 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
11165 // Select shrinking step such that not to make faces with wrong orientation.
11166 double stepSize = 1e100;
11167 for ( size_t i = 0; i < _simplices.size(); ++i )
11169 if ( !_simplices[i]._nPrev->isMarked() ||
11170 !_simplices[i]._nNext->isMarked() )
11171 continue; // simplex of quadrangle created by addBoundaryElements()
11173 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
11174 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
11175 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
11176 gp_XY dirN = uvN2 - uvN1;
11177 double det = uvDir.Crossed( dirN );
11178 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
11179 gp_XY dirN2Cur = curUV - uvN1;
11180 double step = dirN.Crossed( dirN2Cur ) / det;
11182 stepSize = Min( step, stepSize );
11185 if ( uvLen <= stepSize )
11191 else if ( stepSize > 0 )
11193 newUV = curUV + uvDir.XY() * stepSize * kSafe;
11199 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11200 pos->SetUParameter( newUV.X() );
11201 pos->SetVParameter( newUV.Y() );
11204 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11205 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11206 dumpMove( tgtNode );
11209 else // _sWOL is TopAbs_EDGE
11211 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
11212 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
11213 SMDS_EdgePositionPtr tgtPos = tgtNode->GetPosition();
11215 const double u2 = helper.GetNodeU( E, n2, tgtNode );
11216 const double uSrc = _pos[0].Coord( U_SRC );
11217 const double lenTgt = _pos[0].Coord( LEN_TGT );
11219 double newU = _pos[0].Coord( U_TGT );
11220 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
11222 Set( _LayerEdge::SHRUNK );
11227 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
11229 tgtPos->SetUParameter( newU );
11231 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
11232 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11233 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11234 dumpMove( tgtNode );
11241 //================================================================================
11243 * \brief Perform smooth on the FACE
11244 * \retval bool - true if the node has been moved
11246 //================================================================================
11248 bool _SmoothNode::Smooth(int& nbBad,
11249 Handle(Geom_Surface)& surface,
11250 SMESH_MesherHelper& helper,
11251 const double refSign,
11255 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
11257 // get uv of surrounding nodes
11258 vector<gp_XY> uv( _simplices.size() );
11259 for ( size_t i = 0; i < _simplices.size(); ++i )
11260 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
11262 // compute new UV for the node
11263 gp_XY newPos (0,0);
11264 if ( how == TFI && _simplices.size() == 4 )
11267 for ( size_t i = 0; i < _simplices.size(); ++i )
11268 if ( _simplices[i]._nOpp )
11269 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
11271 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
11273 newPos = helper.calcTFI ( 0.5, 0.5,
11274 corners[0], corners[1], corners[2], corners[3],
11275 uv[1], uv[2], uv[3], uv[0] );
11277 else if ( how == ANGULAR )
11279 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
11281 else if ( how == CENTROIDAL && _simplices.size() > 3 )
11283 // average centers of diagonals wieghted with their reciprocal lengths
11284 if ( _simplices.size() == 4 )
11286 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
11287 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
11288 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
11292 double sumWeight = 0;
11293 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
11294 for ( int i = 0; i < nb; ++i )
11297 int iTo = i + _simplices.size() - 1;
11298 for ( int j = iFrom; j < iTo; ++j )
11300 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
11301 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
11303 newPos += w * ( uv[i]+uv[i2] );
11306 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
11311 // Laplacian smooth
11312 for ( size_t i = 0; i < _simplices.size(); ++i )
11314 newPos /= _simplices.size();
11317 // count quality metrics (orientation) of triangles around the node
11318 int nbOkBefore = 0;
11319 gp_XY tgtUV = helper.GetNodeUV( face, _node );
11320 for ( size_t i = 0; i < _simplices.size(); ++i )
11321 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
11324 for ( size_t i = 0; i < _simplices.size(); ++i )
11325 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
11327 if ( nbOkAfter < nbOkBefore )
11329 nbBad += _simplices.size() - nbOkBefore;
11333 SMDS_FacePositionPtr pos = _node->GetPosition();
11334 pos->SetUParameter( newPos.X() );
11335 pos->SetVParameter( newPos.Y() );
11342 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
11343 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
11347 nbBad += _simplices.size() - nbOkAfter;
11348 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
11351 //================================================================================
11353 * \brief Computes new UV using angle based smoothing technique
11355 //================================================================================
11357 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
11358 const gp_XY& uvToFix,
11359 const double refSign)
11361 uv.push_back( uv.front() );
11363 vector< gp_XY > edgeDir ( uv.size() );
11364 vector< double > edgeSize( uv.size() );
11365 for ( size_t i = 1; i < edgeDir.size(); ++i )
11367 edgeDir [i-1] = uv[i] - uv[i-1];
11368 edgeSize[i-1] = edgeDir[i-1].Modulus();
11369 if ( edgeSize[i-1] < numeric_limits<double>::min() )
11370 edgeDir[i-1].SetX( 100 );
11372 edgeDir[i-1] /= edgeSize[i-1] * refSign;
11374 edgeDir.back() = edgeDir.front();
11375 edgeSize.back() = edgeSize.front();
11379 double sumSize = 0;
11380 for ( size_t i = 1; i < edgeDir.size(); ++i )
11382 if ( edgeDir[i-1].X() > 1. ) continue;
11384 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
11385 if ( i == edgeDir.size() ) break;
11387 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
11388 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
11389 gp_XY bisec = norm1 + norm2;
11390 double bisecSize = bisec.Modulus();
11391 if ( bisecSize < numeric_limits<double>::min() )
11393 bisec = -edgeDir[i1] + edgeDir[i];
11394 bisecSize = bisec.Modulus();
11396 bisec /= bisecSize;
11398 gp_XY dirToN = uvToFix - p;
11399 double distToN = dirToN.Modulus();
11400 if ( bisec * dirToN < 0 )
11401 distToN = -distToN;
11403 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
11405 sumSize += edgeSize[i1] + edgeSize[i];
11407 newPos /= /*nbEdges * */sumSize;
11411 //================================================================================
11413 * \brief Delete _SolidData
11415 //================================================================================
11417 _SolidData::~_SolidData()
11419 TNode2Edge::iterator n2e = _n2eMap.begin();
11420 for ( ; n2e != _n2eMap.end(); ++n2e )
11422 _LayerEdge* & e = n2e->second;
11425 delete e->_curvature;
11426 if ( e->_2neibors )
11427 delete e->_2neibors->_plnNorm;
11428 delete e->_2neibors;
11439 //================================================================================
11441 * \brief Keep a _LayerEdge inflated along the EDGE
11443 //================================================================================
11445 void _Shrinker1D::AddEdge( const _LayerEdge* e,
11446 _EdgesOnShape& eos,
11447 SMESH_MesherHelper& helper )
11450 if ( _nodes.empty() )
11452 _edges[0] = _edges[1] = 0;
11455 // check _LayerEdge
11456 if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
11458 if ( eos.SWOLType() != TopAbs_EDGE )
11459 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
11460 if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
11461 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
11463 // store _LayerEdge
11464 _geomEdge = TopoDS::Edge( eos._sWOL );
11466 BRep_Tool::Range( _geomEdge, f,l );
11467 double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
11468 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
11472 const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
11473 const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
11475 if ( _nodes.empty() )
11477 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
11478 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
11480 TopLoc_Location loc;
11481 Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
11482 GeomAdaptor_Curve aCurve(C, f,l);
11483 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
11485 int nbExpectNodes = eSubMesh->NbNodes();
11486 _initU .reserve( nbExpectNodes );
11487 _normPar.reserve( nbExpectNodes );
11488 _nodes .reserve( nbExpectNodes );
11489 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
11490 while ( nIt->more() )
11492 const SMDS_MeshNode* node = nIt->next();
11494 // skip refinement nodes
11495 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
11496 node == tgtNode0 || node == tgtNode1 )
11498 bool hasMarkedFace = false;
11499 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
11500 while ( fIt->more() && !hasMarkedFace )
11501 hasMarkedFace = fIt->next()->isMarked();
11502 if ( !hasMarkedFace )
11505 _nodes.push_back( node );
11506 _initU.push_back( helper.GetNodeU( _geomEdge, node ));
11507 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
11508 _normPar.push_back( len / totLen );
11513 // remove target node of the _LayerEdge from _nodes
11514 size_t nbFound = 0;
11515 for ( size_t i = 0; i < _nodes.size(); ++i )
11516 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
11517 _nodes[i] = 0, nbFound++;
11518 if ( nbFound == _nodes.size() )
11523 //================================================================================
11525 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
11527 //================================================================================
11529 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
11531 if ( _done || _nodes.empty())
11533 const _LayerEdge* e = _edges[0];
11534 if ( !e ) e = _edges[1];
11537 _done = (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
11538 ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
11541 if ( set3D || _done )
11543 Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
11544 GeomAdaptor_Curve aCurve(C, f,l);
11547 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11549 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11550 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
11552 for ( size_t i = 0; i < _nodes.size(); ++i )
11554 if ( !_nodes[i] ) continue;
11555 double len = totLen * _normPar[i];
11556 GCPnts_AbscissaPoint discret( aCurve, len, f );
11557 if ( !discret.IsDone() )
11558 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
11559 double u = discret.Parameter();
11560 SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
11561 pos->SetUParameter( u );
11562 gp_Pnt p = C->Value( u );
11563 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
11568 BRep_Tool::Range( _geomEdge, f,l );
11570 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11572 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11574 for ( size_t i = 0; i < _nodes.size(); ++i )
11576 if ( !_nodes[i] ) continue;
11577 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
11578 SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
11579 pos->SetUParameter( u );
11584 //================================================================================
11586 * \brief Restore initial parameters of nodes on EDGE
11588 //================================================================================
11590 void _Shrinker1D::RestoreParams()
11593 for ( size_t i = 0; i < _nodes.size(); ++i )
11595 if ( !_nodes[i] ) continue;
11596 SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
11597 pos->SetUParameter( _initU[i] );
11602 //================================================================================
11604 * \brief Replace source nodes by target nodes in shrinked mesh edges
11606 //================================================================================
11608 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
11610 const SMDS_MeshNode* nodes[3];
11611 for ( int i = 0; i < 2; ++i )
11613 if ( !_edges[i] ) continue;
11615 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
11616 if ( !eSubMesh ) return;
11617 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
11618 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
11619 const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
11620 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11621 while ( eIt->more() )
11623 const SMDS_MeshElement* e = eIt->next();
11624 if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
11626 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
11627 for ( int iN = 0; iN < e->NbNodes(); ++iN )
11629 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
11630 nodes[iN] = ( n == srcNode ? tgtNode : n );
11632 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
11637 //================================================================================
11639 * \brief Creates 2D and 1D elements on boundaries of new prisms
11641 //================================================================================
11643 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
11645 SMESH_MesherHelper helper( *_mesh );
11647 vector< const SMDS_MeshNode* > faceNodes;
11649 //for ( size_t i = 0; i < _sdVec.size(); ++i )
11651 //_SolidData& data = _sdVec[i];
11652 TopTools_IndexedMapOfShape geomEdges;
11653 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
11654 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
11656 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
11657 const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
11658 if ( data._noShrinkShapes.count( edgeID ))
11661 // Get _LayerEdge's based on E
11663 map< double, const SMDS_MeshNode* > u2nodes;
11664 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
11667 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
11668 TNode2Edge & n2eMap = data._n2eMap;
11669 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
11671 //check if 2D elements are needed on E
11672 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
11673 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
11674 ledges.push_back( n2e->second );
11676 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
11677 continue; // no layers on E
11678 ledges.push_back( n2eMap[ u2n->second ]);
11680 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
11681 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
11682 int nbSharedPyram = 0;
11683 SMDS_ElemIteratorPtr vIt = tgtN1->GetInverseElementIterator(SMDSAbs_Volume);
11684 while ( vIt->more() )
11686 const SMDS_MeshElement* v = vIt->next();
11687 nbSharedPyram += int( v->GetNodeIndex( tgtN0 ) >= 0 );
11689 if ( nbSharedPyram > 1 )
11690 continue; // not free border of the pyramid
11693 faceNodes.push_back( ledges[0]->_nodes[0] );
11694 faceNodes.push_back( ledges[1]->_nodes[0] );
11695 if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
11696 if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
11698 if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
11699 continue; // faces already created
11701 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
11702 ledges.push_back( n2eMap[ u2n->second ]);
11704 // Find out orientation and type of face to create
11706 bool reverse = false, isOnFace;
11709 map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
11710 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
11712 F = e2f->second.Oriented( TopAbs_FORWARD );
11713 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
11714 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
11715 reverse = !reverse, F.Reverse();
11716 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11717 reverse = !reverse;
11719 else if ( !data._ignoreFaceIds.count( e2f->first ))
11721 // find FACE with layers sharing E
11722 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
11724 F = *( fIt->next() );
11726 // Find the sub-mesh to add new faces
11727 SMESHDS_SubMesh* sm = 0;
11729 sm = getMeshDS()->MeshElements( F );
11731 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11733 return error("error in addBoundaryElements()", data._index);
11735 // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
11736 // faces for 3D meshing (PAL23414)
11737 SMESHDS_SubMesh* adjSM = 0;
11740 const TGeomID faceID = sm->GetID();
11741 PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
11742 while ( const TopoDS_Shape* solid = soIt->next() )
11743 if ( !solid->IsSame( data._solid ))
11745 size_t iData = _solids.FindIndex( *solid ) - 1;
11746 if ( iData < _sdVec.size() &&
11747 _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
11748 _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
11750 SMESH_ProxyMesh::SubMesh* proxySub =
11751 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
11752 if ( proxySub && proxySub->NbElements() > 0 )
11759 const int dj1 = reverse ? 0 : 1;
11760 const int dj2 = reverse ? 1 : 0;
11761 vector< const SMDS_MeshElement*> ff; // new faces row
11762 SMESHDS_Mesh* m = getMeshDS();
11763 for ( size_t j = 1; j < ledges.size(); ++j )
11765 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
11766 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
11767 ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
11768 if ( nn1.size() == nn2.size() )
11771 for ( size_t z = 1; z < nn1.size(); ++z )
11772 sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11774 for ( size_t z = 1; z < nn1.size(); ++z )
11775 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11777 else if ( nn1.size() == 1 )
11780 for ( size_t z = 1; z < nn2.size(); ++z )
11781 sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11783 for ( size_t z = 1; z < nn2.size(); ++z )
11784 sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11789 for ( size_t z = 1; z < nn1.size(); ++z )
11790 sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11792 for ( size_t z = 1; z < nn1.size(); ++z )
11793 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11796 if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
11798 for ( size_t z = 0; z < ff.size(); ++z )
11800 adjSM->AddElement( ff[ z ]);
11806 for ( int isFirst = 0; isFirst < 2; ++isFirst )
11808 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11809 _EdgesOnShape* eos = data.GetShapeEdges( edge );
11810 if ( eos && eos->SWOLType() == TopAbs_EDGE )
11812 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
11813 if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
11815 helper.SetSubShape( eos->_sWOL );
11816 helper.SetElementsOnShape( true );
11817 for ( size_t z = 1; z < nn.size(); ++z )
11818 helper.AddEdge( nn[z-1], nn[z] );
11822 } // loop on EDGE's
11823 } // loop on _SolidData's