1 // Copyright (C) 2007-2016 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_subMeshEventListener.hxx"
47 #include "StdMeshers_FaceSide.hxx"
48 #include "StdMeshers_ViscousLayers2D.hxx"
50 #include <Adaptor3d_HSurface.hxx>
51 #include <BRepAdaptor_Curve.hxx>
52 #include <BRepAdaptor_Curve2d.hxx>
53 #include <BRepAdaptor_Surface.hxx>
54 //#include <BRepLProp_CLProps.hxx>
55 #include <BRepLProp_SLProps.hxx>
56 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
57 #include <BRep_Tool.hxx>
58 #include <Bnd_B2d.hxx>
59 #include <Bnd_B3d.hxx>
61 #include <GCPnts_AbscissaPoint.hxx>
62 #include <GCPnts_TangentialDeflection.hxx>
63 #include <Geom2d_Circle.hxx>
64 #include <Geom2d_Line.hxx>
65 #include <Geom2d_TrimmedCurve.hxx>
66 #include <GeomAdaptor_Curve.hxx>
67 #include <GeomLib.hxx>
68 #include <Geom_Circle.hxx>
69 #include <Geom_Curve.hxx>
70 #include <Geom_Line.hxx>
71 #include <Geom_TrimmedCurve.hxx>
72 #include <Precision.hxx>
73 #include <Standard_ErrorHandler.hxx>
74 #include <Standard_Failure.hxx>
75 #include <TColStd_Array1OfReal.hxx>
77 #include <TopExp_Explorer.hxx>
78 #include <TopTools_IndexedMapOfShape.hxx>
79 #include <TopTools_ListOfShape.hxx>
80 #include <TopTools_MapIteratorOfMapOfShape.hxx>
81 #include <TopTools_MapOfShape.hxx>
83 #include <TopoDS_Edge.hxx>
84 #include <TopoDS_Face.hxx>
85 #include <TopoDS_Vertex.hxx>
87 #include <gp_Cone.hxx>
88 #include <gp_Sphere.hxx>
97 #include <unordered_map>
101 //#define __NOT_INVALIDATE_BAD_SMOOTH
102 //#define __NODES_AT_POS
105 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
106 #define BLOCK_INFLATION // of individual _LayerEdge's
107 #define OLD_NEF_POLYGON
111 //================================================================================
116 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
118 const double theMinSmoothCosin = 0.1;
119 const double theSmoothThickToElemSizeRatio = 0.6;
120 const double theMinSmoothTriaAngle = 30;
121 const double theMinSmoothQuadAngle = 45;
123 // what part of thickness is allowed till intersection
124 // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
125 const double theThickToIntersection = 1.5;
127 bool needSmoothing( double cosin, double tgtThick, double elemSize )
129 return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
131 double getSmoothingThickness( double cosin, double elemSize )
133 return theSmoothThickToElemSizeRatio * elemSize / cosin;
137 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
138 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
140 struct _MeshOfSolid : public SMESH_ProxyMesh,
141 public SMESH_subMeshEventListenerData
143 bool _n2nMapComputed;
144 SMESH_ComputeErrorPtr _warning;
146 _MeshOfSolid( SMESH_Mesh* mesh)
147 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
149 SMESH_ProxyMesh::setMesh( *mesh );
152 // returns submesh for a geom face
153 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
155 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
156 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
158 void setNode2Node(const SMDS_MeshNode* srcNode,
159 const SMDS_MeshNode* proxyNode,
160 const SMESH_ProxyMesh::SubMesh* subMesh)
162 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
165 //--------------------------------------------------------------------------------
167 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
168 * It is used to clear an inferior dim sub-meshes modified by viscous layers
170 class _ShrinkShapeListener : SMESH_subMeshEventListener
172 _ShrinkShapeListener()
173 : SMESH_subMeshEventListener(/*isDeletable=*/false,
174 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
176 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
177 virtual void ProcessEvent(const int event,
179 SMESH_subMesh* solidSM,
180 SMESH_subMeshEventListenerData* data,
181 const SMESH_Hypothesis* hyp)
183 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
185 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
189 //--------------------------------------------------------------------------------
191 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
192 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
193 * delete the data as soon as it has been used
195 class _ViscousListener : SMESH_subMeshEventListener
198 SMESH_subMeshEventListener(/*isDeletable=*/false,
199 "StdMeshers_ViscousLayers::_ViscousListener") {}
200 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
202 virtual void ProcessEvent(const int event,
204 SMESH_subMesh* subMesh,
205 SMESH_subMeshEventListenerData* data,
206 const SMESH_Hypothesis* hyp)
208 if (( SMESH_subMesh::COMPUTE_EVENT == eventType ) &&
209 ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
210 SMESH_subMesh::SUBMESH_COMPUTED != event ))
212 // delete SMESH_ProxyMesh containing temporary faces
213 subMesh->DeleteEventListener( this );
216 // Finds or creates proxy mesh of the solid
217 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
218 const TopoDS_Shape& solid,
221 if ( !mesh ) return 0;
222 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
223 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
224 if ( !data && toCreate )
226 data = new _MeshOfSolid(mesh);
227 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
228 sm->SetEventListener( Get(), data, sm );
232 // Removes proxy mesh of the solid
233 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
235 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
239 //================================================================================
241 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
242 * the main shape when sub-mesh of the main shape is cleared,
243 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
246 //================================================================================
248 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
250 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
251 SMESH_subMeshEventListenerData* data =
252 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
255 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
256 data->mySubMeshes.end())
257 data->mySubMeshes.push_back( sub );
261 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
262 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
266 //--------------------------------------------------------------------------------
268 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
269 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
270 * The class is used to check validity of face or volumes around a smoothed node;
271 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
275 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
276 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
277 _Simplex(const SMDS_MeshNode* nPrev=0,
278 const SMDS_MeshNode* nNext=0,
279 const SMDS_MeshNode* nOpp=0)
280 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
281 bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
283 const double M[3][3] =
284 {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
285 { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
286 { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
287 vol = ( + M[0][0] * M[1][1] * M[2][2]
288 + M[0][1] * M[1][2] * M[2][0]
289 + M[0][2] * M[1][0] * M[2][1]
290 - M[0][0] * M[1][2] * M[2][1]
291 - M[0][1] * M[1][0] * M[2][2]
292 - M[0][2] * M[1][1] * M[2][0]);
295 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
297 SMESH_TNodeXYZ pSrc( nSrc );
298 return IsForward( &pSrc, &pTgt, vol );
300 bool IsForward(const gp_XY& tgtUV,
301 const SMDS_MeshNode* smoothedNode,
302 const TopoDS_Face& face,
303 SMESH_MesherHelper& helper,
304 const double refSign) const
306 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
307 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
308 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
310 return d*refSign > 1e-100;
312 bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
314 SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
315 if ( !_nOpp ) // triangle
317 gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
318 double tp2 = tp.SquareMagnitude();
319 double pn2 = pn.SquareMagnitude();
320 double nt2 = nt.SquareMagnitude();
322 if ( tp2 < pn2 && tp2 < nt2 )
323 minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
324 else if ( pn2 < nt2 )
325 minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
327 minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
329 static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
330 Cos( theMinSmoothTriaAngle * M_PI / 180. ));
331 return minAngle < theMaxCos2;
335 SMESH_TNodeXYZ pOpp( _nOpp );
336 gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
337 double tp2 = tp.SquareMagnitude();
338 double po2 = po.SquareMagnitude();
339 double on2 = on.SquareMagnitude();
340 double nt2 = nt.SquareMagnitude();
341 minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
342 (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
343 Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
344 (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
346 static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
347 Cos( theMinSmoothQuadAngle * M_PI / 180. ));
348 return minAngle < theMaxCos2;
351 bool IsNeighbour(const _Simplex& other) const
353 return _nPrev == other._nNext || _nNext == other._nPrev;
355 bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
356 static void GetSimplices( const SMDS_MeshNode* node,
357 vector<_Simplex>& simplices,
358 const set<TGeomID>& ingnoreShapes,
359 const _SolidData* dataToCheckOri = 0,
360 const bool toSort = false);
361 static void SortSimplices(vector<_Simplex>& simplices);
363 //--------------------------------------------------------------------------------
365 * Structure used to take into account surface curvature while smoothing
370 double _k; // factor to correct node smoothed position
371 double _h2lenRatio; // avgNormProj / (2*avgDist)
372 gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
374 static _Curvature* New( double avgNormProj, double avgDist )
377 if ( fabs( avgNormProj / avgDist ) > 1./200 )
380 c->_r = avgDist * avgDist / avgNormProj;
381 c->_k = avgDist * avgDist / c->_r / c->_r;
382 //c->_k = avgNormProj / c->_r;
383 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
384 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
386 c->_uv.SetCoord( 0., 0. );
390 double lenDelta(double len) const { return _k * ( _r + len ); }
391 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
393 //--------------------------------------------------------------------------------
397 struct _EdgesOnShape;
399 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
401 //--------------------------------------------------------------------------------
403 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
404 * and a node of the most internal layer (_nodes.back())
408 typedef gp_XYZ (_LayerEdge::*PSmooFun)();
410 vector< const SMDS_MeshNode*> _nodes;
412 gp_XYZ _normal; // to boundary of solid
413 vector<gp_XYZ> _pos; // points computed during inflation
414 double _len; // length achieved with the last inflation step
415 double _maxLen; // maximal possible length
416 double _cosin; // of angle (_normal ^ surface)
417 double _minAngle; // of _simplices
418 double _lenFactor; // to compute _len taking _cosin into account
421 // simplices connected to the source node (_nodes[0]);
422 // used for smoothing and quality check of _LayerEdge's based on the FACE
423 vector<_Simplex> _simplices;
424 vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
425 PSmooFun _smooFunction; // smoothing function
426 _Curvature* _curvature;
427 // data for smoothing of _LayerEdge's based on the EDGE
428 _2NearEdges* _2neibors;
430 enum EFlags { TO_SMOOTH = 0x0000001,
431 MOVED = 0x0000002, // set by _neibors[i]->SetNewLength()
432 SMOOTHED = 0x0000004, // set by _LayerEdge::Smooth()
433 DIFFICULT = 0x0000008, // near concave VERTEX
434 ON_CONCAVE_FACE = 0x0000010,
435 BLOCKED = 0x0000020, // not to inflate any more
436 INTERSECTED = 0x0000040, // close intersection with a face found
437 NORMAL_UPDATED = 0x0000080,
438 UPD_NORMAL_CONV = 0x0000100, // to update normal on boundary of concave FACE
439 MARKED = 0x0000200, // local usage
440 MULTI_NORMAL = 0x0000400, // a normal is invisible by some of surrounding faces
441 NEAR_BOUNDARY = 0x0000800, // is near FACE boundary forcing smooth
442 SMOOTHED_C1 = 0x0001000, // is on _eosC1
443 DISTORTED = 0x0002000, // was bad before smoothing
444 RISKY_SWOL = 0x0004000, // SWOL is parallel to a source FACE
445 SHRUNK = 0x0008000, // target node reached a tgt position while shrink()
446 UNUSED_FLAG = 0x0100000 // to add user flags after
448 bool Is ( int flag ) const { return _flags & flag; }
449 void Set ( int flag ) { _flags |= flag; }
450 void Unset( int flag ) { _flags &= ~flag; }
451 std::string DumpFlags() const; // debug
453 void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
454 bool SetNewLength2d( Handle(Geom_Surface)& surface,
455 const TopoDS_Face& F,
457 SMESH_MesherHelper& helper );
458 void SetDataByNeighbors( const SMDS_MeshNode* n1,
459 const SMDS_MeshNode* n2,
460 const _EdgesOnShape& eos,
461 SMESH_MesherHelper& helper);
462 void Block( _SolidData& data );
463 void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
464 void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
465 const TNode2Edge& n2eMap);
466 void SmoothPos( const vector< double >& segLen, const double tol );
467 int GetSmoothedPos( const double tol );
468 int Smooth(const int step, const bool isConcaveFace, bool findBest);
469 int Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
470 int CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
471 void SmoothWoCheck();
472 bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
473 const TopoDS_Face& F,
474 SMESH_MesherHelper& helper);
475 void MoveNearConcaVer( const _EdgesOnShape* eov,
476 const _EdgesOnShape* eos,
478 vector< _LayerEdge* > & badSmooEdges);
479 bool FindIntersection( SMESH_ElementSearcher& searcher,
481 const double& epsilon,
483 const SMDS_MeshElement** face = 0);
484 bool SegTriaInter( const gp_Ax1& lastSegment,
489 const double& epsilon) const;
490 bool SegTriaInter( const gp_Ax1& lastSegment,
491 const SMDS_MeshNode* n0,
492 const SMDS_MeshNode* n1,
493 const SMDS_MeshNode* n2,
495 const double& epsilon) const
496 { return SegTriaInter( lastSegment,
497 SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
500 const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
501 gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
502 gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
503 gp_XY LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which=-1 ) const;
504 bool IsOnEdge() const { return _2neibors; }
505 bool IsOnFace() const { return ( _nodes[0]->GetPosition()->GetDim() == 2 ); }
506 int BaseShapeDim() const { return _nodes[0]->GetPosition()->GetDim(); }
507 gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
508 void SetCosin( double cosin );
509 void SetNormal( const gp_XYZ& n ) { _normal = n; }
510 void SetMaxLen( double l ) { _maxLen = l; }
511 int NbSteps() const { return _pos.size() - 1; } // nb inlation steps
512 bool IsNeiborOnEdge( const _LayerEdge* edge ) const;
513 void SetSmooLen( double len ) { // set _len at which smoothing is needed
514 _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
516 double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
518 gp_XYZ smoothLaplacian();
519 gp_XYZ smoothAngular();
520 gp_XYZ smoothLengthWeighted();
521 gp_XYZ smoothCentroidal();
522 gp_XYZ smoothNefPolygon();
524 enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
525 static const int theNbSmooFuns = FUN_NB;
526 static PSmooFun _funs[theNbSmooFuns];
527 static const char* _funNames[theNbSmooFuns+1];
528 int smooFunID( PSmooFun fun=0) const;
530 _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
531 &_LayerEdge::smoothLengthWeighted,
532 &_LayerEdge::smoothCentroidal,
533 &_LayerEdge::smoothNefPolygon,
534 &_LayerEdge::smoothAngular };
535 const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
543 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
545 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
546 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
549 //--------------------------------------------------------------------------------
551 * A 2D half plane used by _LayerEdge::smoothNefPolygon()
555 gp_XY _pos, _dir, _inNorm;
556 bool IsOut( const gp_XY p, const double tol ) const
558 return _inNorm * ( p - _pos ) < -tol;
560 bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
562 //const double eps = 1e-10;
563 double D = _dir.Crossed( hp._dir );
564 if ( fabs(D) < std::numeric_limits<double>::min())
566 gp_XY vec21 = _pos - hp._pos;
567 double u = hp._dir.Crossed( vec21 ) / D;
568 intPnt = _pos + _dir * u;
572 //--------------------------------------------------------------------------------
574 * Structure used to smooth a _LayerEdge based on an EDGE.
578 double _wgt [2]; // weights of _nodes
579 _LayerEdge* _edges[2];
581 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
584 _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
585 const SMDS_MeshNode* tgtNode(bool is2nd) {
586 return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
588 const SMDS_MeshNode* srcNode(bool is2nd) {
589 return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
592 std::swap( _wgt [0], _wgt [1] );
593 std::swap( _edges[0], _edges[1] );
595 void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
596 _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
598 bool include( const _LayerEdge* e ) {
599 return ( _edges[0] == e || _edges[1] == e );
604 //--------------------------------------------------------------------------------
606 * \brief Layers parameters got by averaging several hypotheses
610 AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
611 :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
615 void Add( const StdMeshers_ViscousLayers* hyp )
620 _nbLayers = hyp->GetNumberLayers();
621 //_thickness += hyp->GetTotalThickness();
622 _thickness = Max( _thickness, hyp->GetTotalThickness() );
623 _stretchFactor += hyp->GetStretchFactor();
624 _method = hyp->GetMethod();
627 double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
628 double GetStretchFactor() const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
629 int GetNumberLayers() const { return _nbLayers; }
630 int GetMethod() const { return _method; }
632 bool UseSurfaceNormal() const
633 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
634 bool ToSmooth() const
635 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
636 bool IsOffsetMethod() const
637 { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
640 int _nbLayers, _nbHyps, _method;
641 double _thickness, _stretchFactor;
644 //--------------------------------------------------------------------------------
646 * \brief _LayerEdge's on a shape and other shape data
650 vector< _LayerEdge* > _edges;
654 SMESH_subMesh * _subMesh;
655 // face or edge w/o layer along or near which _edges are inflated
657 bool _isRegularSWOL; // w/o singularities
658 // averaged StdMeshers_ViscousLayers parameters
661 _Smoother1D* _edgeSmoother;
662 vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
663 vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
665 typedef std::unordered_map< const SMDS_MeshElement*, gp_XYZ > TFace2NormMap;
666 TFace2NormMap _faceNormals; // if _shape is FACE
667 vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
669 Handle(ShapeAnalysis_Surface) _offsetSurf;
670 _LayerEdge* _edgeForOffset;
672 _SolidData* _data; // parent SOLID
674 _LayerEdge* operator[](size_t i) const { return (_LayerEdge*) _edges[i]; }
675 size_t size() const { return _edges.size(); }
676 TopAbs_ShapeEnum ShapeType() const
677 { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
678 TopAbs_ShapeEnum SWOLType() const
679 { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
680 bool HasC1( const _EdgesOnShape* other ) const
681 { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
682 bool GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
683 _SolidData& GetData() const { return *_data; }
685 _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
688 //--------------------------------------------------------------------------------
690 * \brief Convex FACE whose radius of curvature is less than the thickness of
691 * layers. It is used to detect distortion of prisms based on a convex
692 * FACE and to update normals to enable further increasing the thickness
698 // edges whose _simplices are used to detect prism distortion
699 vector< _LayerEdge* > _simplexTestEdges;
701 // map a sub-shape to _SolidData::_edgesOnShape
702 map< TGeomID, _EdgesOnShape* > _subIdToEOS;
706 bool _normalsFixedOnBorders; // used in putOnOffsetSurface()
708 double GetMaxCurvature( _SolidData& data,
710 BRepLProp_SLProps& surfProp,
711 SMESH_MesherHelper& helper);
713 bool GetCenterOfCurvature( _LayerEdge* ledge,
714 BRepLProp_SLProps& surfProp,
715 SMESH_MesherHelper& helper,
716 gp_Pnt & center ) const;
717 bool CheckPrisms() const;
720 //--------------------------------------------------------------------------------
722 * \brief Structure holding _LayerEdge's based on EDGEs that will collide
723 * at inflation up to the full thickness. A detected collision
724 * is fixed in updateNormals()
726 struct _CollisionEdges
729 vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
730 const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
731 const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
734 //--------------------------------------------------------------------------------
736 * \brief Data of a SOLID
740 typedef const StdMeshers_ViscousLayers* THyp;
742 TopTools_MapOfShape _before; // SOLIDs to be computed before _solid
743 TGeomID _index; // SOLID id
744 _MeshOfSolid* _proxyMesh;
746 list< TopoDS_Shape > _hypShapes;
747 map< TGeomID, THyp > _face2hyp; // filled if _hyps.size() > 1
748 set< TGeomID > _reversedFaceIds;
749 set< TGeomID > _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
751 double _stepSize, _stepSizeCoeff, _geomSize;
752 const SMDS_MeshNode* _stepSizeNodes[2];
754 TNode2Edge _n2eMap; // nodes and _LayerEdge's based on them
756 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
757 map< TGeomID, TNode2Edge* > _s2neMap;
758 // _LayerEdge's with underlying shapes
759 vector< _EdgesOnShape > _edgesOnShape;
761 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
762 // layers and a FACE w/o layers
763 // value: the shape (FACE or EDGE) to shrink mesh on.
764 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
765 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
767 // Convex FACEs whose radius of curvature is less than the thickness of layers
768 map< TGeomID, _ConvexFace > _convexFaces;
770 // shapes (EDGEs and VERTEXes) shrink from which is forbidden due to collisions with
771 // the adjacent SOLID
772 set< TGeomID > _noShrinkShapes;
774 int _nbShapesToSmooth;
776 vector< _CollisionEdges > _collisionEdges;
777 set< TGeomID > _concaveFaces;
779 double _maxThickness; // of all _hyps
780 double _minThickness; // of all _hyps
782 double _epsilon; // precision for SegTriaInter()
784 SMESH_MesherHelper* _helper;
786 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
788 :_solid(s), _proxyMesh(m), _helper(0) {}
791 void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
792 void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
794 _ConvexFace* GetConvexFace( const TGeomID faceID ) {
795 map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
796 return id2face == _convexFaces.end() ? 0 : & id2face->second;
798 _EdgesOnShape* GetShapeEdges(const TGeomID shapeID );
799 _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
800 _EdgesOnShape* GetShapeEdges(const _LayerEdge* edge )
801 { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
803 SMESH_MesherHelper& GetHelper() const { return *_helper; }
805 void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
806 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
807 for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
808 _edgesOnShape[i]._edges[j]->Unset( flag );
810 void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
811 const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
813 void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
815 //--------------------------------------------------------------------------------
817 * \brief Offset plane used in getNormalByOffset()
823 int _faceIndexNext[2];
824 gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
827 _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
829 void ComputeIntersectionLine( _OffsetPlane& pln,
830 const TopoDS_Edge& E,
831 const TopoDS_Vertex& V );
832 gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
833 int NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
835 //--------------------------------------------------------------------------------
837 * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
839 struct _CentralCurveOnEdge
842 vector< gp_Pnt > _curvaCenters;
843 vector< _LayerEdge* > _ledges;
844 vector< gp_XYZ > _normals; // new normal for each of _ledges
845 vector< double > _segLength2;
848 TopoDS_Face _adjFace;
849 bool _adjFaceToSmooth;
851 void Append( const gp_Pnt& center, _LayerEdge* ledge )
853 if ( ledge->Is( _LayerEdge::MULTI_NORMAL ))
855 if ( _curvaCenters.size() > 0 )
856 _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
857 _curvaCenters.push_back( center );
858 _ledges.push_back( ledge );
859 _normals.push_back( ledge->_normal );
861 bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
862 void SetShapes( const TopoDS_Edge& edge,
863 const _ConvexFace& convFace,
865 SMESH_MesherHelper& helper);
867 //--------------------------------------------------------------------------------
869 * \brief Data of node on a shrinked FACE
873 const SMDS_MeshNode* _node;
874 vector<_Simplex> _simplices; // for quality check
876 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
878 bool Smooth(int& badNb,
879 Handle(Geom_Surface)& surface,
880 SMESH_MesherHelper& helper,
881 const double refSign,
885 gp_XY computeAngularPos(vector<gp_XY>& uv,
886 const gp_XY& uvToFix,
887 const double refSign );
890 //--------------------------------------------------------------------------------
892 * \brief Builder of viscous layers
894 class _ViscousBuilder
899 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
900 const TopoDS_Shape& shape);
901 // check validity of hypotheses
902 SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh& mesh,
903 const TopoDS_Shape& shape );
905 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
906 void RestoreListeners();
908 // computes SMESH_ProxyMesh::SubMesh::_n2n;
909 bool MakeN2NMap( _MeshOfSolid* pm );
913 bool findSolidsWithLayers();
914 bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
915 bool findFacesWithLayers(const bool onlyWith=false);
916 void getIgnoreFaces(const TopoDS_Shape& solid,
917 const StdMeshers_ViscousLayers* hyp,
918 const TopoDS_Shape& hypShape,
919 set<TGeomID>& ignoreFaces);
920 bool makeLayer(_SolidData& data);
921 void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
922 bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
923 SMESH_MesherHelper& helper, _SolidData& data);
924 gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
925 const TopoDS_Face& face,
926 SMESH_MesherHelper& helper,
928 bool shiftInside=false);
929 bool getFaceNormalAtSingularity(const gp_XY& uv,
930 const TopoDS_Face& face,
931 SMESH_MesherHelper& helper,
933 gp_XYZ getWeigthedNormal( const _LayerEdge* edge );
934 gp_XYZ getNormalByOffset( _LayerEdge* edge,
935 std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
937 bool lastNoOffset = false);
938 bool findNeiborsOnEdge(const _LayerEdge* edge,
939 const SMDS_MeshNode*& n1,
940 const SMDS_MeshNode*& n2,
943 void findSimplexTestEdges( _SolidData& data,
944 vector< vector<_LayerEdge*> >& edgesByGeom);
945 void computeGeomSize( _SolidData& data );
946 bool findShapesToSmooth( _SolidData& data);
947 void limitStepSizeByCurvature( _SolidData& data );
948 void limitStepSize( _SolidData& data,
949 const SMDS_MeshElement* face,
950 const _LayerEdge* maxCosinEdge );
951 void limitStepSize( _SolidData& data, const double minSize);
952 bool inflate(_SolidData& data);
953 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
954 int invalidateBadSmooth( _SolidData& data,
955 SMESH_MesherHelper& helper,
956 vector< _LayerEdge* >& badSmooEdges,
957 vector< _EdgesOnShape* >& eosC1,
959 void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
960 void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
961 vector< _EdgesOnShape* >& eosC1,
962 int smooStep=0, int moveAll=false );
963 void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
964 void findEdgesToUpdateNormalNearConvexFace( _ConvexFace & convFace,
966 SMESH_MesherHelper& helper );
967 void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
968 void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
969 _EdgesOnShape& eos1, _EdgesOnShape& eos2,
970 const bool isSmoothable );
971 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
972 bool updateNormalsOfConvexFaces( _SolidData& data,
973 SMESH_MesherHelper& helper,
975 void updateNormalsOfC1Vertices( _SolidData& data );
976 bool updateNormalsOfSmoothed( _SolidData& data,
977 SMESH_MesherHelper& helper,
979 const double stepSize );
980 bool isNewNormalOk( _SolidData& data,
982 const gp_XYZ& newNormal);
983 bool refine(_SolidData& data);
984 bool shrink(_SolidData& data);
985 bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
986 SMESH_MesherHelper& helper,
987 const SMESHDS_SubMesh* faceSubMesh );
988 void restoreNoShrink( _LayerEdge& edge ) const;
989 void fixBadFaces(const TopoDS_Face& F,
990 SMESH_MesherHelper& helper,
993 set<const SMDS_MeshNode*> * involvedNodes=NULL);
994 bool addBoundaryElements(_SolidData& data);
996 bool error( const string& text, int solidID=-1 );
997 SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
1000 void makeGroupOfLE();
1003 SMESH_ComputeErrorPtr _error;
1005 vector< _SolidData > _sdVec;
1006 TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
1007 TopTools_MapOfShape _shrinkedFaces;
1012 //--------------------------------------------------------------------------------
1014 * \brief Shrinker of nodes on the EDGE
1018 TopoDS_Edge _geomEdge;
1019 vector<double> _initU;
1020 vector<double> _normPar;
1021 vector<const SMDS_MeshNode*> _nodes;
1022 const _LayerEdge* _edges[2];
1025 void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1026 void Compute(bool set3D, SMESH_MesherHelper& helper);
1027 void RestoreParams();
1028 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1029 const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1030 const SMDS_MeshNode* TgtNode( bool is2nd ) const
1031 { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1032 const SMDS_MeshNode* SrcNode( bool is2nd ) const
1033 { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1035 //--------------------------------------------------------------------------------
1037 * \brief Smoother of _LayerEdge's on EDGE.
1041 struct OffPnt // point of the offsetted EDGE
1043 gp_XYZ _xyz; // coord of a point inflated from EDGE w/o smooth
1044 double _len; // length reached at previous inflation step
1045 double _param; // on EDGE
1046 _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1047 gp_XYZ _edgeDir;// EDGE tangent at _param
1048 double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1050 vector< OffPnt > _offPoints;
1051 vector< double > _leParams; // normalized param of _eos._edges on EDGE
1052 Handle(Geom_Curve) _anaCurve; // for analytic smooth
1053 _LayerEdge _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1054 gp_XYZ _edgeDir[2]; // tangent at VERTEXes
1055 size_t _iSeg[2]; // index of segment where extreme tgt node is projected
1056 _EdgesOnShape& _eos;
1057 double _curveLen; // length of the EDGE
1058 std::pair<int,int> _eToSmooth[2]; // <from,to> indices of _LayerEdge's in _eos
1060 static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
1062 SMESH_MesherHelper& helper);
1064 _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1065 _EdgesOnShape& eos )
1066 : _anaCurve( curveForSmooth ), _eos( eos )
1069 bool Perform(_SolidData& data,
1070 Handle(ShapeAnalysis_Surface)& surface,
1071 const TopoDS_Face& F,
1072 SMESH_MesherHelper& helper );
1074 void prepare(_SolidData& data );
1076 void findEdgesToSmooth();
1078 bool isToSmooth( int iE );
1080 bool smoothAnalyticEdge( _SolidData& data,
1081 Handle(ShapeAnalysis_Surface)& surface,
1082 const TopoDS_Face& F,
1083 SMESH_MesherHelper& helper);
1084 bool smoothComplexEdge( _SolidData& data,
1085 Handle(ShapeAnalysis_Surface)& surface,
1086 const TopoDS_Face& F,
1087 SMESH_MesherHelper& helper);
1088 gp_XYZ getNormalNormal( const gp_XYZ & normal,
1089 const gp_XYZ& edgeDir);
1090 _LayerEdge* getLEdgeOnV( bool is2nd )
1092 return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1094 bool isAnalytic() const { return !_anaCurve.IsNull(); }
1096 void offPointsToPython() const; // debug
1098 //--------------------------------------------------------------------------------
1100 * \brief Class of temporary mesh face.
1101 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1102 * needed because SMESH_ElementSearcher internally uses set of elements sorted by ID
1104 struct _TmpMeshFace : public SMDS_PolygonalFaceOfNodes
1106 const SMDS_MeshElement* _srcFace;
1108 _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1111 const SMDS_MeshElement* srcFace=0 ):
1112 SMDS_PolygonalFaceOfNodes(nodes), _srcFace( srcFace ) { setID( ID ); setShapeID( faceID ); }
1113 virtual SMDSAbs_EntityType GetEntityType() const
1114 { return _srcFace ? _srcFace->GetEntityType() : SMDSEntity_Quadrangle; }
1115 virtual SMDSAbs_GeometryType GetGeomType() const
1116 { return _srcFace ? _srcFace->GetGeomType() : SMDSGeom_QUADRANGLE; }
1118 //--------------------------------------------------------------------------------
1120 * \brief Class of temporary mesh quadrangle face storing _LayerEdge it's based on
1122 struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1124 _LayerEdge *_le1, *_le2;
1125 _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1126 _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1128 myNodes[0]=_le1->_nodes[0];
1129 myNodes[1]=_le1->_nodes.back();
1130 myNodes[2]=_le2->_nodes.back();
1131 myNodes[3]=_le2->_nodes[0];
1133 const SMDS_MeshNode* n( size_t i ) const
1135 return myNodes[ i ];
1137 gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1139 SMESH_TNodeXYZ p0s( myNodes[0] );
1140 SMESH_TNodeXYZ p0t( myNodes[1] );
1141 SMESH_TNodeXYZ p1t( myNodes[2] );
1142 SMESH_TNodeXYZ p1s( myNodes[3] );
1143 gp_XYZ v0 = p0t - p0s;
1144 gp_XYZ v1 = p1t - p1s;
1145 gp_XYZ v01 = p1s - p0s;
1146 gp_XYZ n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1151 gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1153 myNodes[0]=le1->_nodes[0];
1154 myNodes[1]=le1->_nodes.back();
1155 myNodes[2]=le2->_nodes.back();
1156 myNodes[3]=le2->_nodes[0];
1160 //--------------------------------------------------------------------------------
1162 * \brief Retriever of node coordinates either directly or from a surface by node UV.
1163 * \warning Location of a surface is ignored
1165 struct _NodeCoordHelper
1167 SMESH_MesherHelper& _helper;
1168 const TopoDS_Face& _face;
1169 Handle(Geom_Surface) _surface;
1170 gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1172 _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1173 : _helper( helper ), _face( F )
1177 TopLoc_Location loc;
1178 _surface = BRep_Tool::Surface( _face, loc );
1180 if ( _surface.IsNull() )
1181 _fun = & _NodeCoordHelper::direct;
1183 _fun = & _NodeCoordHelper::byUV;
1185 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1188 gp_XYZ direct(const SMDS_MeshNode* n) const
1190 return SMESH_TNodeXYZ( n );
1192 gp_XYZ byUV (const SMDS_MeshNode* n) const
1194 gp_XY uv = _helper.GetNodeUV( _face, n );
1195 return _surface->Value( uv.X(), uv.Y() ).XYZ();
1199 //================================================================================
1201 * \brief Check angle between vectors
1203 //================================================================================
1205 inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1207 double dot = v1 * v2; // cos * |v1| * |v2|
1208 double l1 = v1.SquareMagnitude();
1209 double l2 = v2.SquareMagnitude();
1210 return (( dot * cos >= 0 ) &&
1211 ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1214 } // namespace VISCOUS_3D
1218 //================================================================================
1219 // StdMeshers_ViscousLayers hypothesis
1221 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, SMESH_Gen* gen)
1222 :SMESH_Hypothesis(hypId, gen),
1223 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1224 _method( SURF_OFFSET_SMOOTH )
1226 _name = StdMeshers_ViscousLayers::GetHypType();
1227 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1228 } // --------------------------------------------------------------------------------
1229 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1231 if ( faceIds != _shapeIds )
1232 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1233 if ( _isToIgnoreShapes != toIgnore )
1234 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1235 } // --------------------------------------------------------------------------------
1236 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1238 if ( thickness != _thickness )
1239 _thickness = thickness, NotifySubMeshesHypothesisModification();
1240 } // --------------------------------------------------------------------------------
1241 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1243 if ( _nbLayers != nb )
1244 _nbLayers = nb, NotifySubMeshesHypothesisModification();
1245 } // --------------------------------------------------------------------------------
1246 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1248 if ( _stretchFactor != factor )
1249 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1250 } // --------------------------------------------------------------------------------
1251 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1253 if ( _method != method )
1254 _method = method, NotifySubMeshesHypothesisModification();
1255 } // --------------------------------------------------------------------------------
1256 SMESH_ProxyMesh::Ptr
1257 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
1258 const TopoDS_Shape& theShape,
1259 const bool toMakeN2NMap) const
1261 using namespace VISCOUS_3D;
1262 _ViscousBuilder builder;
1263 SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1264 if ( err && !err->IsOK() )
1265 return SMESH_ProxyMesh::Ptr();
1267 vector<SMESH_ProxyMesh::Ptr> components;
1268 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1269 for ( ; exp.More(); exp.Next() )
1271 if ( _MeshOfSolid* pm =
1272 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1274 if ( toMakeN2NMap && !pm->_n2nMapComputed )
1275 if ( !builder.MakeN2NMap( pm ))
1276 return SMESH_ProxyMesh::Ptr();
1277 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1278 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1280 if ( pm->_warning && !pm->_warning->IsOK() )
1282 SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1283 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1284 if ( !smError || smError->IsOK() )
1285 smError = pm->_warning;
1288 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1290 switch ( components.size() )
1294 case 1: return components[0];
1296 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1298 return SMESH_ProxyMesh::Ptr();
1299 } // --------------------------------------------------------------------------------
1300 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1302 save << " " << _nbLayers
1303 << " " << _thickness
1304 << " " << _stretchFactor
1305 << " " << _shapeIds.size();
1306 for ( size_t i = 0; i < _shapeIds.size(); ++i )
1307 save << " " << _shapeIds[i];
1308 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1309 save << " " << _method;
1311 } // --------------------------------------------------------------------------------
1312 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1314 int nbFaces, faceID, shapeToTreat, method;
1315 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1316 while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1317 _shapeIds.push_back( faceID );
1318 if ( load >> shapeToTreat ) {
1319 _isToIgnoreShapes = !shapeToTreat;
1320 if ( load >> method )
1321 _method = (ExtrusionMethod) method;
1324 _isToIgnoreShapes = true; // old behavior
1327 } // --------------------------------------------------------------------------------
1328 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
1329 const TopoDS_Shape& theShape)
1333 } // --------------------------------------------------------------------------------
1334 SMESH_ComputeErrorPtr
1335 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh& theMesh,
1336 const TopoDS_Shape& theShape,
1337 SMESH_Hypothesis::Hypothesis_Status& theStatus)
1339 VISCOUS_3D::_ViscousBuilder builder;
1340 SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1341 if ( err && !err->IsOK() )
1342 theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1344 theStatus = SMESH_Hypothesis::HYP_OK;
1348 // --------------------------------------------------------------------------------
1349 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1352 ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1353 return IsToIgnoreShapes() ? !isIn : isIn;
1355 // END StdMeshers_ViscousLayers hypothesis
1356 //================================================================================
1358 namespace VISCOUS_3D
1360 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1364 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1365 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1366 gp_Pnt p = BRep_Tool::Pnt( fromV );
1367 double distF = p.SquareDistance( c->Value( f ));
1368 double distL = p.SquareDistance( c->Value( l ));
1369 c->D1(( distF < distL ? f : l), p, dir );
1370 if ( distL < distF ) dir.Reverse();
1373 //--------------------------------------------------------------------------------
1374 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1375 SMESH_MesherHelper& helper)
1378 double f,l; gp_Pnt p;
1379 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1380 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1381 double u = helper.GetNodeU( E, atNode );
1385 //--------------------------------------------------------------------------------
1386 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1387 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1389 //--------------------------------------------------------------------------------
1390 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1391 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1394 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1397 TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1398 return getFaceDir( F, v, node, helper, ok );
1400 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1401 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1402 gp_Pnt p; gp_Vec du, dv, norm;
1403 surface->D1( uv.X(),uv.Y(), p, du,dv );
1406 double u = helper.GetNodeU( fromE, node, 0, &ok );
1408 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1409 if ( o == TopAbs_REVERSED )
1412 gp_Vec dir = norm ^ du;
1414 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1415 helper.IsClosedEdge( fromE ))
1417 if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1418 else c->D1( f, p, dv );
1419 if ( o == TopAbs_REVERSED )
1421 gp_Vec dir2 = norm ^ dv;
1422 dir = dir.Normalized() + dir2.Normalized();
1426 //--------------------------------------------------------------------------------
1427 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1428 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1429 bool& ok, double* cosin)
1431 TopoDS_Face faceFrw = F;
1432 faceFrw.Orientation( TopAbs_FORWARD );
1433 //double f,l; TopLoc_Location loc;
1434 TopoDS_Edge edges[2]; // sharing a vertex
1437 TopoDS_Vertex VV[2];
1438 TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1439 for ( ; exp.More() && nbEdges < 2; exp.Next() )
1441 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1442 if ( SMESH_Algo::isDegenerated( e )) continue;
1443 TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1444 if ( VV[1].IsSame( fromV )) {
1445 nbEdges += edges[ 0 ].IsNull();
1448 else if ( VV[0].IsSame( fromV )) {
1449 nbEdges += edges[ 1 ].IsNull();
1454 gp_XYZ dir(0,0,0), edgeDir[2];
1457 // get dirs of edges going fromV
1459 for ( size_t i = 0; i < nbEdges && ok; ++i )
1461 edgeDir[i] = getEdgeDir( edges[i], fromV );
1462 double size2 = edgeDir[i].SquareModulus();
1463 if (( ok = size2 > numeric_limits<double>::min() ))
1464 edgeDir[i] /= sqrt( size2 );
1466 if ( !ok ) return dir;
1468 // get angle between the 2 edges
1470 double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1471 if ( Abs( angle ) < 5 * M_PI/180 )
1473 dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1477 dir = edgeDir[0] + edgeDir[1];
1482 double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1483 *cosin = Cos( angle );
1486 else if ( nbEdges == 1 )
1488 dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1489 if ( cosin ) *cosin = 1.;
1499 //================================================================================
1501 * \brief Finds concave VERTEXes of a FACE
1503 //================================================================================
1505 bool getConcaveVertices( const TopoDS_Face& F,
1506 SMESH_MesherHelper& helper,
1507 set< TGeomID >* vertices = 0)
1509 // check angles at VERTEXes
1511 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1512 for ( size_t iW = 0; iW < wires.size(); ++iW )
1514 const int nbEdges = wires[iW]->NbEdges();
1515 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1517 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1519 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1520 int iE2 = ( iE1 + 1 ) % nbEdges;
1521 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1522 iE2 = ( iE2 + 1 ) % nbEdges;
1523 TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1524 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1525 wires[iW]->Edge( iE2 ), F, V );
1526 if ( angle < -5. * M_PI / 180. )
1530 vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1534 return vertices ? !vertices->empty() : false;
1537 //================================================================================
1539 * \brief Returns true if a FACE is bound by a concave EDGE
1541 //================================================================================
1543 bool isConcave( const TopoDS_Face& F,
1544 SMESH_MesherHelper& helper,
1545 set< TGeomID >* vertices = 0 )
1547 bool isConcv = false;
1548 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1550 gp_Vec2d drv1, drv2;
1552 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1553 for ( ; eExp.More(); eExp.Next() )
1555 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1556 if ( SMESH_Algo::isDegenerated( E )) continue;
1557 // check if 2D curve is concave
1558 BRepAdaptor_Curve2d curve( E, F );
1559 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1560 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1561 curve.Intervals( intervals, GeomAbs_C2 );
1562 bool isConvex = true;
1563 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1565 double u1 = intervals( i );
1566 double u2 = intervals( i+1 );
1567 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1568 double cross = drv1 ^ drv2;
1569 if ( E.Orientation() == TopAbs_REVERSED )
1571 isConvex = ( cross > -1e-9 ); // 0.1 );
1575 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1584 // check angles at VERTEXes
1585 if ( getConcaveVertices( F, helper, vertices ))
1591 //================================================================================
1593 * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1594 * \param [in] face - the mesh face to treat
1595 * \param [in] nodeOnEdge - a node on the EDGE
1596 * \param [out] faceSize - the computed distance
1597 * \return bool - true if faceSize computed
1599 //================================================================================
1601 bool getDistFromEdge( const SMDS_MeshElement* face,
1602 const SMDS_MeshNode* nodeOnEdge,
1605 faceSize = Precision::Infinite();
1608 int nbN = face->NbCornerNodes();
1609 int iOnE = face->GetNodeIndex( nodeOnEdge );
1610 int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1611 SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1612 const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1613 face->GetNode( iNext[1] ) };
1614 gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1615 double segLen = -1.;
1616 // look for two neighbor not in-FACE nodes of face
1617 for ( int i = 0; i < 2; ++i )
1619 if (( nNext[i]->GetPosition()->GetDim() != 2 ) &&
1620 ( nodeOnEdge->GetPosition()->GetDim() == 0 || nNext[i]->GetID() < nodeOnEdge->GetID() ))
1622 // look for an in-FACE node
1623 for ( int iN = 0; iN < nbN; ++iN )
1625 if ( iN == iOnE || iN == iNext[i] )
1627 SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1628 gp_XYZ v = pInFace - segEnd;
1631 segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1632 segLen = segVec.Modulus();
1634 double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1635 faceSize = Min( faceSize, distToSeg );
1643 //================================================================================
1645 * \brief Return direction of axis or revolution of a surface
1647 //================================================================================
1649 bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1652 switch ( surface.GetType() ) {
1655 gp_Cone cone = surface.Cone();
1656 axis = cone.Axis().Direction();
1659 case GeomAbs_Sphere:
1661 gp_Sphere sphere = surface.Sphere();
1662 axis = sphere.Position().Direction();
1665 case GeomAbs_SurfaceOfRevolution:
1667 axis = surface.AxeOfRevolution().Direction();
1670 //case GeomAbs_SurfaceOfExtrusion:
1671 case GeomAbs_OffsetSurface:
1673 Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1674 return getRovolutionAxis( base->Surface(), axis );
1676 default: return false;
1681 //--------------------------------------------------------------------------------
1682 // DEBUG. Dump intermediate node positions into a python script
1683 // HOWTO use: run python commands written in a console to see
1684 // construction steps of viscous layers
1690 PyDump(SMESH_Mesh& m) {
1691 int tag = 3 + m.GetId();
1692 const char* fname = "/tmp/viscous.py";
1693 cout << "execfile('"<<fname<<"')"<<endl;
1694 py = _pyStream = new ofstream(fname);
1695 *py << "import SMESH" << endl
1696 << "from salome.smesh import smeshBuilder" << endl
1697 << "smesh = smeshBuilder.New()" << endl
1698 << "meshSO = salome.myStudy.FindObjectID('0:1:2:" << tag <<"')" << endl
1699 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
1704 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1705 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1706 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1707 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1711 ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1712 struct MyStream : public ostream
1714 template <class T> ostream & operator<<( const T &anything ) { return *this ; }
1716 void Pause() { py = &_mystream; }
1717 void Resume() { py = _pyStream; }
1721 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1722 #define dumpMove(n) { _dumpMove(n, __LINE__);}
1723 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1724 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
1725 void _dumpFunction(const string& fun, int ln)
1726 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1727 void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1728 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1729 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1730 void _dumpCmd(const string& txt, int ln)
1731 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
1732 void dumpFunctionEnd()
1733 { if (py) *py<< " return"<< endl; }
1734 void dumpChangeNodes( const SMDS_MeshElement* f )
1735 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
1736 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1737 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1738 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1742 struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} void Pause() {} void Resume() {} };
1743 #define dumpFunction(f) f
1745 #define dumpMoveComm(n,txt)
1746 #define dumpCmd(txt)
1747 #define dumpFunctionEnd()
1748 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1749 #define debugMsg( txt ) {}
1754 using namespace VISCOUS_3D;
1756 //================================================================================
1758 * \brief Constructor of _ViscousBuilder
1760 //================================================================================
1762 _ViscousBuilder::_ViscousBuilder()
1764 _error = SMESH_ComputeError::New(COMPERR_OK);
1768 //================================================================================
1770 * \brief Stores error description and returns false
1772 //================================================================================
1774 bool _ViscousBuilder::error(const string& text, int solidId )
1776 const string prefix = string("Viscous layers builder: ");
1777 _error->myName = COMPERR_ALGO_FAILED;
1778 _error->myComment = prefix + text;
1781 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1782 if ( !sm && !_sdVec.empty() )
1783 sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1784 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1786 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1787 if ( smError && smError->myAlgo )
1788 _error->myAlgo = smError->myAlgo;
1790 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1792 // set KO to all solids
1793 for ( size_t i = 0; i < _sdVec.size(); ++i )
1795 if ( _sdVec[i]._index == solidId )
1797 sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1798 if ( !sm->IsEmpty() )
1800 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1801 if ( !smError || smError->IsOK() )
1803 smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1804 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1808 makeGroupOfLE(); // debug
1813 //================================================================================
1815 * \brief At study restoration, restore event listeners used to clear an inferior
1816 * dim sub-mesh modified by viscous layers
1818 //================================================================================
1820 void _ViscousBuilder::RestoreListeners()
1825 //================================================================================
1827 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1829 //================================================================================
1831 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1833 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1834 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1835 for ( ; fExp.More(); fExp.Next() )
1837 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1838 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1840 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1842 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1845 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1846 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1848 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1849 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1850 while( prxIt->more() )
1852 const SMDS_MeshElement* fSrc = srcIt->next();
1853 const SMDS_MeshElement* fPrx = prxIt->next();
1854 if ( fSrc->NbNodes() != fPrx->NbNodes())
1855 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1856 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1857 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1860 pm->_n2nMapComputed = true;
1864 //================================================================================
1866 * \brief Does its job
1868 //================================================================================
1870 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1871 const TopoDS_Shape& theShape)
1875 // check if proxy mesh already computed
1876 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1878 return error("No SOLID's in theShape"), _error;
1880 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1881 return SMESH_ComputeErrorPtr(); // everything already computed
1883 PyDump debugDump( theMesh );
1884 _pyDump = &debugDump;
1886 // TODO: ignore already computed SOLIDs
1887 if ( !findSolidsWithLayers())
1890 if ( !findFacesWithLayers() )
1893 for ( size_t i = 0; i < _sdVec.size(); ++i )
1896 for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1897 if ( _sdVec[iSD]._before.IsEmpty() &&
1898 !_sdVec[iSD]._solid.IsNull() &&
1899 _sdVec[iSD]._n2eMap.empty() )
1902 if ( ! makeLayer(_sdVec[iSD]) ) // create _LayerEdge's
1905 if ( _sdVec[iSD]._n2eMap.size() == 0 ) // no layers in a SOLID
1907 _sdVec[iSD]._solid.Nullify();
1911 if ( ! inflate(_sdVec[iSD]) ) // increase length of _LayerEdge's
1914 if ( ! refine(_sdVec[iSD]) ) // create nodes and prisms
1917 if ( ! shrink(_sdVec[iSD]) ) // shrink 2D mesh on FACEs w/o layer
1920 addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
1922 const TopoDS_Shape& solid = _sdVec[iSD]._solid;
1923 for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1924 _sdVec[iSD]._before.Remove( solid );
1927 makeGroupOfLE(); // debug
1933 //================================================================================
1935 * \brief Check validity of hypotheses
1937 //================================================================================
1939 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh& mesh,
1940 const TopoDS_Shape& shape )
1944 if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1945 return SMESH_ComputeErrorPtr(); // everything already computed
1948 findSolidsWithLayers();
1949 bool ok = findFacesWithLayers( true );
1951 // remove _MeshOfSolid's of _SolidData's
1952 for ( size_t i = 0; i < _sdVec.size(); ++i )
1953 _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1958 return SMESH_ComputeErrorPtr();
1961 //================================================================================
1963 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1965 //================================================================================
1967 bool _ViscousBuilder::findSolidsWithLayers()
1970 TopTools_IndexedMapOfShape allSolids;
1971 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1972 _sdVec.reserve( allSolids.Extent());
1974 SMESH_HypoFilter filter;
1975 for ( int i = 1; i <= allSolids.Extent(); ++i )
1977 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1978 SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
1979 if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
1980 continue; // solid is already meshed
1981 SMESH_Algo* algo = sm->GetAlgo();
1982 if ( !algo ) continue;
1983 // TODO: check if algo is hidden
1984 const list <const SMESHDS_Hypothesis *> & allHyps =
1985 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1986 _SolidData* soData = 0;
1987 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1988 const StdMeshers_ViscousLayers* viscHyp = 0;
1989 for ( ; hyp != allHyps.end(); ++hyp )
1990 if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1992 TopoDS_Shape hypShape;
1993 filter.Init( filter.Is( viscHyp ));
1994 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1998 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
2001 _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
2002 soData = & _sdVec.back();
2003 soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
2004 soData->_helper = new SMESH_MesherHelper( *_mesh );
2005 soData->_helper->SetSubShape( allSolids(i) );
2006 _solids.Add( allSolids(i) );
2008 soData->_hyps.push_back( viscHyp );
2009 soData->_hypShapes.push_back( hypShape );
2012 if ( _sdVec.empty() )
2014 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
2019 //================================================================================
2021 * \brief Set a _SolidData to be computed before another
2023 //================================================================================
2025 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
2027 // check possibility to set this order; get all solids before solidBefore
2028 TopTools_IndexedMapOfShape allSolidsBefore;
2029 allSolidsBefore.Add( solidBefore._solid );
2030 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2032 int iSD = _solids.FindIndex( allSolidsBefore(i) );
2035 TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2036 for ( ; soIt.More(); soIt.Next() )
2037 allSolidsBefore.Add( soIt.Value() );
2040 if ( allSolidsBefore.Contains( solidAfter._solid ))
2043 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2044 solidAfter._before.Add( allSolidsBefore(i) );
2049 //================================================================================
2053 //================================================================================
2055 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2057 SMESH_MesherHelper helper( *_mesh );
2058 TopExp_Explorer exp;
2060 // collect all faces-to-ignore defined by hyp
2061 for ( size_t i = 0; i < _sdVec.size(); ++i )
2063 // get faces-to-ignore defined by each hyp
2064 typedef const StdMeshers_ViscousLayers* THyp;
2065 typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2066 list< TFacesOfHyp > ignoreFacesOfHyps;
2067 list< THyp >::iterator hyp = _sdVec[i]._hyps.begin();
2068 list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2069 for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2071 ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2072 getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2075 // fill _SolidData::_face2hyp and check compatibility of hypotheses
2076 const int nbHyps = _sdVec[i]._hyps.size();
2079 // check if two hypotheses define different parameters for the same FACE
2080 list< TFacesOfHyp >::iterator igFacesOfHyp;
2081 for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2083 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2085 igFacesOfHyp = ignoreFacesOfHyps.begin();
2086 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2087 if ( ! igFacesOfHyp->first.count( faceID ))
2090 return error(SMESH_Comment("Several hypotheses define "
2091 "Viscous Layers on the face #") << faceID );
2092 hyp = igFacesOfHyp->second;
2095 _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2097 _sdVec[i]._ignoreFaceIds.insert( faceID );
2100 // check if two hypotheses define different number of viscous layers for
2101 // adjacent faces of a solid
2102 set< int > nbLayersSet;
2103 igFacesOfHyp = ignoreFacesOfHyps.begin();
2104 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2106 nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2108 if ( nbLayersSet.size() > 1 )
2110 for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2112 PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2113 THyp hyp1 = 0, hyp2 = 0;
2114 while( const TopoDS_Shape* face = fIt->next() )
2116 const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2117 map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2118 if ( f2h != _sdVec[i]._face2hyp.end() )
2120 ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2123 if ( hyp1 && hyp2 &&
2124 hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2126 return error("Two hypotheses define different number of "
2127 "viscous layers on adjacent faces");
2131 } // if ( nbHyps > 1 )
2134 _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2138 if ( onlyWith ) // is called to check hypotheses compatibility only
2141 // fill _SolidData::_reversedFaceIds
2142 for ( size_t i = 0; i < _sdVec.size(); ++i )
2144 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2145 for ( ; exp.More(); exp.Next() )
2147 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2148 const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2149 if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2150 helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2151 helper.IsReversedSubMesh( face ))
2153 _sdVec[i]._reversedFaceIds.insert( faceID );
2158 // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2159 TopTools_IndexedMapOfShape shapes;
2160 std::string structAlgoName = "Hexa_3D";
2161 for ( size_t i = 0; i < _sdVec.size(); ++i )
2164 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2165 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2167 const TopoDS_Shape& edge = shapes(iE);
2168 // find 2 FACEs sharing an EDGE
2170 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2171 while ( fIt->more())
2173 const TopoDS_Shape* f = fIt->next();
2174 FF[ int( !FF[0].IsNull()) ] = *f;
2176 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2178 // check presence of layers on them
2180 for ( int j = 0; j < 2; ++j )
2181 ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2182 if ( ignore[0] == ignore[1] )
2183 continue; // nothing interesting
2184 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2187 if ( !fWOL.IsNull())
2189 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2190 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2195 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2197 for ( size_t i = 0; i < _sdVec.size(); ++i )
2200 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2201 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2203 const TopoDS_Shape& vertex = shapes(iV);
2204 // find faces WOL sharing the vertex
2205 vector< TopoDS_Shape > facesWOL;
2206 size_t totalNbFaces = 0;
2207 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2208 while ( fIt->more())
2210 const TopoDS_Shape* f = fIt->next();
2212 const int fID = getMeshDS()->ShapeToIndex( *f );
2213 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2214 facesWOL.push_back( *f );
2216 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2217 continue; // no layers at this vertex or no WOL
2218 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2219 switch ( facesWOL.size() )
2223 helper.SetSubShape( facesWOL[0] );
2224 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2226 TopoDS_Shape seamEdge;
2227 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2228 while ( eIt->more() && seamEdge.IsNull() )
2230 const TopoDS_Shape* e = eIt->next();
2231 if ( helper.IsRealSeam( *e ) )
2234 if ( !seamEdge.IsNull() )
2236 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2240 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2245 // find an edge shared by 2 faces
2246 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2247 while ( eIt->more())
2249 const TopoDS_Shape* e = eIt->next();
2250 if ( helper.IsSubShape( *e, facesWOL[0]) &&
2251 helper.IsSubShape( *e, facesWOL[1]))
2253 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2259 return error("Not yet supported case", _sdVec[i]._index);
2264 // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrinked since
2265 // the algo of the SOLID sharing the FACE does not support it or for other reasons
2266 set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2267 for ( size_t i = 0; i < _sdVec.size(); ++i )
2269 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2270 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2272 const TopoDS_Shape& fWOL = e2f->second;
2273 const TGeomID edgeID = e2f->first;
2274 TGeomID faceID = getMeshDS()->ShapeToIndex( fWOL );
2275 TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2276 if ( edge.ShapeType() != TopAbs_EDGE )
2277 continue; // shrink shape is VERTEX
2280 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2281 while ( soIt->more() && solid.IsNull() )
2283 const TopoDS_Shape* so = soIt->next();
2284 if ( !so->IsSame( _sdVec[i]._solid ))
2287 if ( solid.IsNull() )
2290 bool noShrinkE = false;
2291 SMESH_Algo* algo = _mesh->GetSubMesh( solid )->GetAlgo();
2292 bool isStructured = ( algo && algo->GetName() == structAlgoName );
2293 size_t iSolid = _solids.FindIndex( solid ) - 1;
2294 if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2296 // the adjacent SOLID has NO layers on fWOL;
2297 // shrink allowed if
2298 // - there are layers on the EDGE in the adjacent SOLID
2299 // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2300 bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2301 bool shrinkAllowed = (( hasWLAdj ) ||
2302 ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2303 noShrinkE = !shrinkAllowed;
2305 else if ( iSolid < _sdVec.size() )
2307 // the adjacent SOLID has layers on fWOL;
2308 // check if SOLID's mesh is unstructured and then try to set it
2309 // to be computed after the i-th solid
2310 if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2311 noShrinkE = true; // don't shrink fWOL
2315 // the adjacent SOLID has NO layers at all
2316 noShrinkE = isStructured;
2321 _sdVec[i]._noShrinkShapes.insert( edgeID );
2323 // check if there is a collision with to-shrink-from EDGEs in iSolid
2324 // if ( iSolid < _sdVec.size() )
2327 // TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2328 // for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2330 // const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2331 // const TGeomID eID = getMeshDS()->ShapeToIndex( E );
2332 // if ( eID == edgeID ||
2333 // !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2334 // _sdVec[i]._noShrinkShapes.count( eID ))
2336 // for ( int is1st = 0; is1st < 2; ++is1st )
2338 // TopoDS_Vertex V = helper.IthVertex( is1st, E );
2339 // if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2341 // return error("No way to make a conformal mesh with "
2342 // "the given set of faces with layers", _sdVec[i]._index);
2349 // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2350 // _shrinkShape2Shape is different in the adjacent SOLID
2351 for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2353 TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2354 bool noShrinkV = false, noShrinkIfAdjMeshed = false;
2356 if ( iSolid < _sdVec.size() )
2358 if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2360 map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2361 i2S = _sdVec[i ]._shrinkShape2Shape.find( vID );
2362 i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2363 if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2364 noShrinkV = (( isStructured ) ||
2365 ( noShrinkIfAdjMeshed = i2S->second.ShapeType() == TopAbs_EDGE ));
2367 noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2371 noShrinkV = noShrinkE;
2376 // the adjacent SOLID has NO layers at all
2383 noShrinkV = noShrinkIfAdjMeshed =
2384 ( _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2388 if ( noShrinkV && noShrinkIfAdjMeshed )
2390 // noShrinkV if FACEs in the adjacent SOLID are meshed
2391 PShapeIteratorPtr fIt = helper.GetAncestors( _sdVec[i]._shrinkShape2Shape[ vID ],
2392 *_mesh, TopAbs_FACE, &solid );
2393 while ( fIt->more() )
2395 const TopoDS_Shape* f = fIt->next();
2396 if ( !f->IsSame( fWOL ))
2398 noShrinkV = ! _mesh->GetSubMesh( *f )->IsEmpty();
2404 _sdVec[i]._noShrinkShapes.insert( vID );
2407 } // loop on _sdVec[i]._shrinkShape2Shape
2408 } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2411 // add FACEs of other SOLIDs to _ignoreFaceIds
2412 for ( size_t i = 0; i < _sdVec.size(); ++i )
2415 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2417 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2419 if ( !shapes.Contains( exp.Current() ))
2420 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2427 //================================================================================
2429 * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2431 //================================================================================
2433 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape& solid,
2434 const StdMeshers_ViscousLayers* hyp,
2435 const TopoDS_Shape& hypShape,
2436 set<TGeomID>& ignoreFaceIds)
2438 TopExp_Explorer exp;
2440 vector<TGeomID> ids = hyp->GetBndShapes();
2441 if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2443 for ( size_t ii = 0; ii < ids.size(); ++ii )
2445 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2446 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2447 ignoreFaceIds.insert( ids[ii] );
2450 else // FACEs with layers are given
2452 exp.Init( solid, TopAbs_FACE );
2453 for ( ; exp.More(); exp.Next() )
2455 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2456 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2457 ignoreFaceIds.insert( faceInd );
2461 // ignore internal FACEs if inlets and outlets are specified
2462 if ( hyp->IsToIgnoreShapes() )
2464 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2465 TopExp::MapShapesAndAncestors( hypShape,
2466 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2468 for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2470 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2471 if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2474 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2476 ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2481 //================================================================================
2483 * \brief Create the inner surface of the viscous layer and prepare data for infation
2485 //================================================================================
2487 bool _ViscousBuilder::makeLayer(_SolidData& data)
2489 // get all sub-shapes to make layers on
2490 set<TGeomID> subIds, faceIds;
2491 subIds = data._noShrinkShapes;
2492 TopExp_Explorer exp( data._solid, TopAbs_FACE );
2493 for ( ; exp.More(); exp.Next() )
2495 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2496 if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2497 faceIds.insert( fSubM->GetId() );
2500 // make a map to find new nodes on sub-shapes shared with other SOLID
2501 map< TGeomID, TNode2Edge* >::iterator s2ne;
2502 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2503 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2505 TGeomID shapeInd = s2s->first;
2506 for ( size_t i = 0; i < _sdVec.size(); ++i )
2508 if ( _sdVec[i]._index == data._index ) continue;
2509 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2510 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2511 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2513 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2519 // Create temporary faces and _LayerEdge's
2521 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2523 data._stepSize = Precision::Infinite();
2524 data._stepSizeNodes[0] = 0;
2526 SMESH_MesherHelper helper( *_mesh );
2527 helper.SetSubShape( data._solid );
2528 helper.SetElementsOnShape( true );
2530 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2531 TNode2Edge::iterator n2e2;
2533 // collect _LayerEdge's of shapes they are based on
2534 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2535 const int nbShapes = getMeshDS()->MaxShapeIndex();
2536 edgesByGeom.resize( nbShapes+1 );
2538 // set data of _EdgesOnShape's
2539 if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2541 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2542 while ( smIt->more() )
2545 if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2546 !faceIds.count( sm->GetId() ))
2548 setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2551 // make _LayerEdge's
2552 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2554 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2555 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2556 SMESH_ProxyMesh::SubMesh* proxySub =
2557 data._proxyMesh->getFaceSubM( F, /*create=*/true);
2559 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2560 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2562 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2563 while ( eIt->more() )
2565 const SMDS_MeshElement* face = eIt->next();
2566 double faceMaxCosin = -1;
2567 _LayerEdge* maxCosinEdge = 0;
2568 int nbDegenNodes = 0;
2570 newNodes.resize( face->NbCornerNodes() );
2571 for ( size_t i = 0 ; i < newNodes.size(); ++i )
2573 const SMDS_MeshNode* n = face->GetNode( i );
2574 const int shapeID = n->getshapeId();
2575 const bool onDegenShap = helper.IsDegenShape( shapeID );
2576 const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2581 // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2582 const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2583 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2584 if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2594 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2595 if ( !(*n2e).second )
2598 _LayerEdge* edge = new _LayerEdge();
2599 edge->_nodes.push_back( n );
2601 edgesByGeom[ shapeID ]._edges.push_back( edge );
2602 const bool noShrink = data._noShrinkShapes.count( shapeID );
2604 SMESH_TNodeXYZ xyz( n );
2606 // set edge data or find already refined _LayerEdge and get data from it
2607 if (( !noShrink ) &&
2608 ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE ) &&
2609 (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2610 (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end() ))
2612 _LayerEdge* foundEdge = (*n2e2).second;
2613 gp_XYZ lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2614 foundEdge->_pos.push_back( lastPos );
2615 // location of the last node is modified and we restore it by foundEdge->_pos.back()
2616 const_cast< SMDS_MeshNode* >
2617 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2623 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2625 if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2628 if ( edge->_nodes.size() < 2 )
2629 edge->Block( data );
2630 //data._noShrinkShapes.insert( shapeID );
2632 dumpMove(edge->_nodes.back());
2634 if ( edge->_cosin > faceMaxCosin )
2636 faceMaxCosin = edge->_cosin;
2637 maxCosinEdge = edge;
2640 newNodes[ i ] = n2e->second->_nodes.back();
2643 data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2645 if ( newNodes.size() - nbDegenNodes < 2 )
2648 // create a temporary face
2649 const SMDS_MeshElement* newFace =
2650 new _TmpMeshFace( newNodes, --_tmpFaceID, face->GetShapeID(), face );
2651 proxySub->AddElement( newFace );
2653 // compute inflation step size by min size of element on a convex surface
2654 if ( faceMaxCosin > theMinSmoothCosin )
2655 limitStepSize( data, face, maxCosinEdge );
2657 } // loop on 2D elements on a FACE
2658 } // loop on FACEs of a SOLID to create _LayerEdge's
2661 // Set _LayerEdge::_neibors
2662 TNode2Edge::iterator n2e;
2663 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2665 _EdgesOnShape& eos = data._edgesOnShape[iS];
2666 for ( size_t i = 0; i < eos._edges.size(); ++i )
2668 _LayerEdge* edge = eos._edges[i];
2669 TIDSortedNodeSet nearNodes;
2670 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2671 while ( fIt->more() )
2673 const SMDS_MeshElement* f = fIt->next();
2674 if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2675 nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2677 nearNodes.erase( edge->_nodes[0] );
2678 edge->_neibors.reserve( nearNodes.size() );
2679 TIDSortedNodeSet::iterator node = nearNodes.begin();
2680 for ( ; node != nearNodes.end(); ++node )
2681 if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2682 edge->_neibors.push_back( n2e->second );
2686 data._epsilon = 1e-7;
2687 if ( data._stepSize < 1. )
2688 data._epsilon *= data._stepSize;
2690 if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2693 // limit data._stepSize depending on surface curvature and fill data._convexFaces
2694 limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2696 // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2697 const SMDS_MeshNode* nn[2];
2698 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2700 _EdgesOnShape& eos = data._edgesOnShape[iS];
2701 for ( size_t i = 0; i < eos._edges.size(); ++i )
2703 _LayerEdge* edge = eos._edges[i];
2704 if ( edge->IsOnEdge() )
2706 // get neighbor nodes
2707 bool hasData = ( edge->_2neibors->_edges[0] );
2708 if ( hasData ) // _LayerEdge is a copy of another one
2710 nn[0] = edge->_2neibors->srcNode(0);
2711 nn[1] = edge->_2neibors->srcNode(1);
2713 else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2717 // set neighbor _LayerEdge's
2718 for ( int j = 0; j < 2; ++j )
2720 if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2721 return error("_LayerEdge not found by src node", data._index);
2722 edge->_2neibors->_edges[j] = n2e->second;
2725 edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2728 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2730 _Simplex& s = edge->_simplices[j];
2731 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2732 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2735 // For an _LayerEdge on a degenerated EDGE, copy some data from
2736 // a corresponding _LayerEdge on a VERTEX
2737 // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2738 if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2740 // Generally we should not get here
2741 if ( eos.ShapeType() != TopAbs_EDGE )
2743 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2744 const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2745 if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2747 const _LayerEdge* vEdge = n2e->second;
2748 edge->_normal = vEdge->_normal;
2749 edge->_lenFactor = vEdge->_lenFactor;
2750 edge->_cosin = vEdge->_cosin;
2753 } // loop on data._edgesOnShape._edges
2754 } // loop on data._edgesOnShape
2756 // fix _LayerEdge::_2neibors on EDGEs to smooth
2757 // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2758 // for ( ; e2c != data._edge2curve.end(); ++e2c )
2759 // if ( !e2c->second.IsNull() )
2761 // if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2762 // data.Sort2NeiborsOnEdge( eos->_edges );
2769 //================================================================================
2771 * \brief Compute inflation step size by min size of element on a convex surface
2773 //================================================================================
2775 void _ViscousBuilder::limitStepSize( _SolidData& data,
2776 const SMDS_MeshElement* face,
2777 const _LayerEdge* maxCosinEdge )
2780 double minSize = 10 * data._stepSize;
2781 const int nbNodes = face->NbCornerNodes();
2782 for ( int i = 0; i < nbNodes; ++i )
2784 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2785 const SMDS_MeshNode* curN = face->GetNode( i );
2786 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2787 curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2789 double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2790 if ( dist < minSize )
2791 minSize = dist, iN = i;
2794 double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2795 if ( newStep < data._stepSize )
2797 data._stepSize = newStep;
2798 data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2799 data._stepSizeNodes[0] = face->GetNode( iN );
2800 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2804 //================================================================================
2806 * \brief Compute inflation step size by min size of element on a convex surface
2808 //================================================================================
2810 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2812 if ( minSize < data._stepSize )
2814 data._stepSize = minSize;
2815 if ( data._stepSizeNodes[0] )
2818 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2819 data._stepSizeCoeff = data._stepSize / dist;
2824 //================================================================================
2826 * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2828 //================================================================================
2830 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2832 SMESH_MesherHelper helper( *_mesh );
2834 BRepLProp_SLProps surfProp( 2, 1e-6 );
2835 data._convexFaces.clear();
2837 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2839 _EdgesOnShape& eof = data._edgesOnShape[iS];
2840 if ( eof.ShapeType() != TopAbs_FACE ||
2841 data._ignoreFaceIds.count( eof._shapeID ))
2844 TopoDS_Face F = TopoDS::Face( eof._shape );
2845 const TGeomID faceID = eof._shapeID;
2847 BRepAdaptor_Surface surface( F, false );
2848 surfProp.SetSurface( surface );
2850 _ConvexFace cnvFace;
2852 cnvFace._normalsFixed = false;
2853 cnvFace._isTooCurved = false;
2855 double maxCurvature = cnvFace.GetMaxCurvature( data, eof, surfProp, helper );
2856 if ( maxCurvature > 0 )
2858 limitStepSize( data, 0.9 / maxCurvature );
2859 findEdgesToUpdateNormalNearConvexFace( cnvFace, data, helper );
2861 if ( !cnvFace._isTooCurved ) continue;
2863 _ConvexFace & convFace =
2864 data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2866 // skip a closed surface (data._convexFaces is useful anyway)
2867 bool isClosedF = false;
2868 helper.SetSubShape( F );
2869 if ( helper.HasRealSeam() )
2871 // in the closed surface there must be a closed EDGE
2872 for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2873 isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2877 // limit _LayerEdge::_maxLen on the FACE
2878 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2879 const double minCurvature =
2880 1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2881 map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2882 if ( id2eos != cnvFace._subIdToEOS.end() )
2884 _EdgesOnShape& eos = * id2eos->second;
2885 for ( size_t i = 0; i < eos._edges.size(); ++i )
2887 _LayerEdge* ledge = eos._edges[ i ];
2888 gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2889 surfProp.SetParameters( uv.X(), uv.Y() );
2890 if ( surfProp.IsCurvatureDefined() )
2892 double curvature = Max( surfProp.MaxCurvature() * oriFactor,
2893 surfProp.MinCurvature() * oriFactor );
2894 if ( curvature > minCurvature )
2895 ledge->SetMaxLen( Min( ledge->_maxLen, 1. / curvature ));
2902 // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2903 // prism distortion.
2904 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2905 if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2907 // there are _LayerEdge's on the FACE it-self;
2908 // select _LayerEdge's near EDGEs
2909 _EdgesOnShape& eos = * id2eos->second;
2910 for ( size_t i = 0; i < eos._edges.size(); ++i )
2912 _LayerEdge* ledge = eos._edges[ i ];
2913 for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2914 if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2916 // do not select _LayerEdge's neighboring sharp EDGEs
2917 bool sharpNbr = false;
2918 for ( size_t iN = 0; iN < ledge->_neibors.size() && !sharpNbr; ++iN )
2919 sharpNbr = ( ledge->_neibors[iN]->_cosin > theMinSmoothCosin );
2921 convFace._simplexTestEdges.push_back( ledge );
2928 // where there are no _LayerEdge's on a _ConvexFace,
2929 // as e.g. on a fillet surface with no internal nodes - issue 22580,
2930 // so that collision of viscous internal faces is not detected by check of
2931 // intersection of _LayerEdge's with the viscous internal faces.
2933 set< const SMDS_MeshNode* > usedNodes;
2935 // look for _LayerEdge's with null _sWOL
2936 id2eos = convFace._subIdToEOS.begin();
2937 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2939 _EdgesOnShape& eos = * id2eos->second;
2940 if ( !eos._sWOL.IsNull() )
2942 for ( size_t i = 0; i < eos._edges.size(); ++i )
2944 _LayerEdge* ledge = eos._edges[ i ];
2945 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2946 if ( !usedNodes.insert( srcNode ).second ) continue;
2948 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2950 usedNodes.insert( ledge->_simplices[i]._nPrev );
2951 usedNodes.insert( ledge->_simplices[i]._nNext );
2953 convFace._simplexTestEdges.push_back( ledge );
2957 } // loop on FACEs of data._solid
2960 //================================================================================
2962 * \brief Detect shapes (and _LayerEdge's on them) to smooth
2964 //================================================================================
2966 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2968 // define allowed thickness
2969 computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2972 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2973 // boundary inclined to the shape at a sharp angle
2975 TopTools_MapOfShape edgesOfSmooFaces;
2976 SMESH_MesherHelper helper( *_mesh );
2979 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2980 data._nbShapesToSmooth = 0;
2982 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2984 _EdgesOnShape& eos = edgesByGeom[iS];
2985 eos._toSmooth = false;
2986 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2989 double tgtThick = eos._hyp.GetTotalThickness();
2990 SMESH_subMeshIteratorPtr subIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false );
2991 while ( subIt->more() && !eos._toSmooth )
2993 TGeomID iSub = subIt->next()->GetId();
2994 const vector<_LayerEdge*>& eSub = edgesByGeom[ iSub ]._edges;
2995 if ( eSub.empty() ) continue;
2998 for ( size_t i = 0; i < eSub.size() && !eos._toSmooth; ++i )
2999 if ( eSub[i]->_cosin > theMinSmoothCosin )
3001 SMDS_ElemIteratorPtr fIt = eSub[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3002 while ( fIt->more() && !eos._toSmooth )
3004 const SMDS_MeshElement* face = fIt->next();
3005 if ( face->getshapeId() == eos._shapeID &&
3006 getDistFromEdge( face, eSub[i]->_nodes[0], faceSize ))
3008 eos._toSmooth = needSmoothing( eSub[i]->_cosin,
3009 tgtThick * eSub[i]->_lenFactor,
3015 if ( eos._toSmooth )
3017 for ( TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
3018 edgesOfSmooFaces.Add( eExp.Current() );
3020 data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3022 data._nbShapesToSmooth += eos._toSmooth;
3026 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3028 _EdgesOnShape& eos = edgesByGeom[iS];
3029 eos._edgeSmoother = NULL;
3030 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3031 if ( !eos._hyp.ToSmooth() ) continue;
3033 const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3034 if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3037 double tgtThick = eos._hyp.GetTotalThickness();
3038 for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3040 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3041 vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3042 if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3043 gp_Vec eDir = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
3044 double angle = eDir.Angle( eV[0]->_normal );
3045 double cosin = Cos( angle );
3046 double cosinAbs = Abs( cosin );
3047 if ( cosinAbs > theMinSmoothCosin )
3049 // always smooth analytic EDGEs
3050 Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3051 eos._toSmooth = ! curve.IsNull();
3053 // compare tgtThick with the length of an end segment
3054 SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3055 while ( eIt->more() && !eos._toSmooth )
3057 const SMDS_MeshElement* endSeg = eIt->next();
3058 if ( endSeg->getshapeId() == (int) iS )
3061 SMESH_TNodeXYZ( endSeg->GetNode( 0 )).Distance( endSeg->GetNode( 1 ));
3062 eos._toSmooth = needSmoothing( cosinAbs, tgtThick * eV[0]->_lenFactor, segLen );
3065 if ( eos._toSmooth )
3067 eos._edgeSmoother = new _Smoother1D( curve, eos );
3069 // for ( size_t i = 0; i < eos._edges.size(); ++i )
3070 // eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3074 data._nbShapesToSmooth += eos._toSmooth;
3078 // Reset _cosin if no smooth is allowed by the user
3079 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3081 _EdgesOnShape& eos = edgesByGeom[iS];
3082 if ( eos._edges.empty() ) continue;
3084 if ( !eos._hyp.ToSmooth() )
3085 for ( size_t i = 0; i < eos._edges.size(); ++i )
3086 //eos._edges[i]->SetCosin( 0 ); // keep _cosin to use in limitMaxLenByCurvature()
3087 eos._edges[i]->_lenFactor = 1;
3091 // Fill _eosC1 to make that C1 FACEs and EDGEs between them to be smoothed as a whole
3093 TopTools_MapOfShape c1VV;
3095 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3097 _EdgesOnShape& eos = edgesByGeom[iS];
3098 if ( eos._edges.empty() ||
3099 eos.ShapeType() != TopAbs_FACE ||
3103 // check EDGEs of a FACE
3104 TopTools_MapOfShape checkedEE, allVV;
3105 list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3106 while ( !smQueue.empty() )
3108 SMESH_subMesh* sm = smQueue.front();
3109 smQueue.pop_front();
3110 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3111 while ( smIt->more() )
3114 if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3115 allVV.Add( sm->GetSubShape() );
3116 if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3117 !checkedEE.Add( sm->GetSubShape() ))
3120 _EdgesOnShape* eoe = data.GetShapeEdges( sm->GetId() );
3121 vector<_LayerEdge*>& eE = eoe->_edges;
3122 if ( eE.empty() || !eoe->_sWOL.IsNull() )
3125 bool isC1 = true; // check continuity along an EDGE
3126 for ( size_t i = 0; i < eE.size() && isC1; ++i )
3127 isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3131 // check that mesh faces are C1 as well
3133 gp_XYZ norm1, norm2;
3134 const SMDS_MeshNode* n = eE[ eE.size() / 2 ]->_nodes[0];
3135 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3136 if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3138 while ( fIt->more() && isC1 )
3139 isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3140 Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3145 // add the EDGE and an adjacent FACE to _eosC1
3146 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3147 while ( const TopoDS_Shape* face = fIt->next() )
3149 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3150 if ( !eof ) continue; // other solid
3151 if ( eos._shapeID == eof->_shapeID ) continue;
3152 if ( !eos.HasC1( eof ))
3155 eos._eosC1.push_back( eof );
3156 eof->_toSmooth = false;
3157 data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3158 smQueue.push_back( eof->_subMesh );
3160 if ( !eos.HasC1( eoe ))
3162 eos._eosC1.push_back( eoe );
3163 eoe->_toSmooth = false;
3164 data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3169 if ( eos._eosC1.empty() )
3172 // check VERTEXes of C1 FACEs
3173 TopTools_MapIteratorOfMapOfShape vIt( allVV );
3174 for ( ; vIt.More(); vIt.Next() )
3176 _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3177 if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3180 bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3181 PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3182 while ( const TopoDS_Shape* face = fIt->next() )
3184 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3185 if ( !eof ) continue; // other solid
3186 isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3192 eos._eosC1.push_back( eov );
3193 data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3194 c1VV.Add( eov->_shape );
3198 } // fill _eosC1 of FACEs
3203 vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3205 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3207 _EdgesOnShape& eov = edgesByGeom[iS];
3208 if ( eov._edges.empty() ||
3209 eov.ShapeType() != TopAbs_VERTEX ||
3210 c1VV.Contains( eov._shape ))
3212 const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3214 // get directions of surrounding EDGEs
3216 PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3217 while ( const TopoDS_Shape* e = fIt->next() )
3219 _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3220 if ( !eoe ) continue; // other solid
3221 gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3222 if ( !Precision::IsInfinite( eDir.X() ))
3223 dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3226 // find EDGEs with C1 directions
3227 for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3228 for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3229 if ( dirOfEdges[i].first && dirOfEdges[j].first )
3231 double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3232 bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3235 double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3236 double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3237 double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3238 if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3239 if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3240 dirOfEdges[i].first = 0;
3241 dirOfEdges[j].first = 0;
3244 } // fill _eosC1 of VERTEXes
3251 //================================================================================
3253 * \brief initialize data of _EdgesOnShape
3255 //================================================================================
3257 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3261 if ( !eos._shape.IsNull() ||
3262 sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3265 SMESH_MesherHelper helper( *_mesh );
3268 eos._shapeID = sm->GetId();
3269 eos._shape = sm->GetSubShape();
3270 if ( eos.ShapeType() == TopAbs_FACE )
3271 eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3272 eos._toSmooth = false;
3276 map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3277 data._shrinkShape2Shape.find( eos._shapeID );
3278 if ( s2s != data._shrinkShape2Shape.end() )
3279 eos._sWOL = s2s->second;
3281 eos._isRegularSWOL = true;
3282 if ( eos.SWOLType() == TopAbs_FACE )
3284 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3285 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3286 eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3290 if ( data._hyps.size() == 1 )
3292 eos._hyp = data._hyps.back();
3296 // compute average StdMeshers_ViscousLayers parameters
3297 map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3298 if ( eos.ShapeType() == TopAbs_FACE )
3300 if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3301 eos._hyp = f2hyp->second;
3305 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3306 while ( const TopoDS_Shape* face = fIt->next() )
3308 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3309 if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3310 eos._hyp.Add( f2hyp->second );
3316 if ( ! eos._hyp.UseSurfaceNormal() )
3318 if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3320 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3321 if ( !smDS ) return;
3322 eos._faceNormals.reserve( smDS->NbElements() );
3324 double oriFactor = helper.IsReversedSubMesh( TopoDS::Face( eos._shape )) ? 1.: -1.;
3325 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3326 for ( ; eIt->more(); )
3328 const SMDS_MeshElement* face = eIt->next();
3329 gp_XYZ& norm = eos._faceNormals[face];
3330 if ( !SMESH_MeshAlgos::FaceNormal( face, norm, /*normalized=*/true ))
3331 norm.SetCoord( 0,0,0 );
3335 else // find EOS of adjacent FACEs
3337 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3338 while ( const TopoDS_Shape* face = fIt->next() )
3340 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3341 eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3342 if ( eos._faceEOS.back()->_shape.IsNull() )
3343 // avoid using uninitialised _shapeID in GetNormal()
3344 eos._faceEOS.back()->_shapeID = faceID;
3350 //================================================================================
3352 * \brief Returns normal of a face
3354 //================================================================================
3356 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3359 _EdgesOnShape* eos = 0;
3361 if ( face->getshapeId() == _shapeID )
3367 for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3368 if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3369 eos = _faceEOS[ iF ];
3373 ( ok = ( eos->_faceNormals.count( face ) )))
3375 norm = eos->_faceNormals[ face ];
3379 debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3380 << " on _shape #" << _shapeID );
3386 //================================================================================
3388 * \brief Set data of _LayerEdge needed for smoothing
3390 //================================================================================
3392 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
3394 SMESH_MesherHelper& helper,
3397 const SMDS_MeshNode* node = edge._nodes[0]; // source node
3400 edge._maxLen = Precision::Infinite();
3403 edge._curvature = 0;
3406 // --------------------------
3407 // Compute _normal and _cosin
3408 // --------------------------
3411 edge._lenFactor = 1.;
3412 edge._normal.SetCoord(0,0,0);
3413 _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3415 int totalNbFaces = 0;
3417 std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3421 const bool onShrinkShape = !eos._sWOL.IsNull();
3422 const bool useGeometry = (( eos._hyp.UseSurfaceNormal() ) ||
3423 ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3425 // get geom FACEs the node lies on
3426 //if ( useGeometry )
3428 set<TGeomID> faceIds;
3429 if ( eos.ShapeType() == TopAbs_FACE )
3431 faceIds.insert( eos._shapeID );
3435 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3436 while ( fIt->more() )
3437 faceIds.insert( fIt->next()->getshapeId() );
3439 set<TGeomID>::iterator id = faceIds.begin();
3440 for ( ; id != faceIds.end(); ++id )
3442 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3443 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3445 F = TopoDS::Face( s );
3446 face2Norm[ totalNbFaces ].first = F;
3452 bool fromVonF = false;
3455 fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3456 eos.SWOLType() == TopAbs_FACE &&
3459 if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3461 if ( eos.SWOLType() == TopAbs_EDGE )
3463 // inflate from VERTEX along EDGE
3464 edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3466 else if ( eos.ShapeType() == TopAbs_VERTEX )
3468 // inflate from VERTEX along FACE
3469 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3470 node, helper, normOK, &edge._cosin);
3474 // inflate from EDGE along FACE
3475 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3476 node, helper, normOK);
3479 else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3482 face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3485 for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3487 F = face2Norm[ iF ].first;
3488 geomNorm = getFaceNormal( node, F, helper, normOK );
3489 if ( !normOK ) continue;
3492 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3494 face2Norm[ iF ].second = geomNorm.XYZ();
3495 edge._normal += geomNorm.XYZ();
3497 if ( nbOkNorms == 0 )
3498 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3500 if ( totalNbFaces >= 3 )
3502 edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3505 if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3507 // opposite normals, re-get normals at shifted positions (IPAL 52426)
3508 edge._normal.SetCoord( 0,0,0 );
3509 for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3511 const TopoDS_Face& F = face2Norm[iF].first;
3512 geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3513 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3516 face2Norm[ iF ].second = geomNorm.XYZ();
3517 edge._normal += face2Norm[ iF ].second;
3522 else // !useGeometry - get _normal using surrounding mesh faces
3524 edge._normal = getWeigthedNormal( &edge );
3526 // set<TGeomID> faceIds;
3528 // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3529 // while ( fIt->more() )
3531 // const SMDS_MeshElement* face = fIt->next();
3532 // if ( eos.GetNormal( face, geomNorm ))
3534 // if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3535 // continue; // use only one mesh face on FACE
3536 // edge._normal += geomNorm.XYZ();
3543 //if ( eos._hyp.UseSurfaceNormal() )
3545 switch ( eos.ShapeType() )
3552 TopoDS_Edge E = TopoDS::Edge( eos._shape );
3553 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3554 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3555 edge._cosin = Cos( angle );
3558 case TopAbs_VERTEX: {
3561 getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3562 node, helper, normOK, &edge._cosin );
3564 else if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3566 TopoDS_Vertex V = TopoDS::Vertex( eos._shape );
3567 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3568 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3569 edge._cosin = Cos( angle );
3570 if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3571 for ( int iF = 1; iF < totalNbFaces; ++iF )
3573 F = face2Norm[ iF ].first;
3574 inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3576 double angle = inFaceDir.Angle( edge._normal );
3577 double cosin = Cos( angle );
3578 if ( Abs( cosin ) > Abs( edge._cosin ))
3579 edge._cosin = cosin;
3586 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3590 double normSize = edge._normal.SquareModulus();
3591 if ( normSize < numeric_limits<double>::min() )
3592 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3594 edge._normal /= sqrt( normSize );
3596 if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3598 getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3599 edge._nodes.resize( 1 );
3600 edge._normal.SetCoord( 0,0,0 );
3601 edge.SetMaxLen( 0 );
3604 // Set the rest data
3605 // --------------------
3607 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3609 if ( onShrinkShape )
3611 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3612 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3613 sm->RemoveNode( tgtNode );
3615 // set initial position which is parameters on _sWOL in this case
3616 if ( eos.SWOLType() == TopAbs_EDGE )
3618 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3619 edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3620 if ( edge._nodes.size() > 1 )
3621 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3623 else // eos.SWOLType() == TopAbs_FACE
3625 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3626 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3627 if ( edge._nodes.size() > 1 )
3628 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3631 if ( edge._nodes.size() > 1 )
3633 // check if an angle between a FACE with layers and SWOL is sharp,
3634 // else the edge should not inflate
3636 for ( int iF = 0; iF < totalNbFaces && F.IsNull(); ++iF ) // find a FACE with VL
3637 if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3638 F = face2Norm[iF].first;
3641 geomNorm = getFaceNormal( node, F, helper, normOK );
3642 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3643 geomNorm.Reverse(); // inside the SOLID
3644 if ( geomNorm * edge._normal < -0.001 )
3646 getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3647 edge._nodes.resize( 1 );
3649 else if ( edge._lenFactor > 3 )
3651 edge._lenFactor = 2;
3652 edge.Set( _LayerEdge::RISKY_SWOL );
3659 edge._pos.push_back( SMESH_TNodeXYZ( node ));
3661 if ( eos.ShapeType() == TopAbs_FACE )
3664 for ( size_t i = 0; i < edge._simplices.size(); ++i )
3666 edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3667 edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3672 // Set neighbor nodes for a _LayerEdge based on EDGE
3674 if ( eos.ShapeType() == TopAbs_EDGE /*||
3675 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3677 edge._2neibors = new _2NearEdges;
3678 // target nodes instead of source ones will be set later
3684 //================================================================================
3686 * \brief Return normal to a FACE at a node
3687 * \param [in] n - node
3688 * \param [in] face - FACE
3689 * \param [in] helper - helper
3690 * \param [out] isOK - true or false
3691 * \param [in] shiftInside - to find normal at a position shifted inside the face
3692 * \return gp_XYZ - normal
3694 //================================================================================
3696 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3697 const TopoDS_Face& face,
3698 SMESH_MesherHelper& helper,
3705 // get a shifted position
3706 gp_Pnt p = SMESH_TNodeXYZ( node );
3707 gp_XYZ shift( 0,0,0 );
3708 TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3709 switch ( S.ShapeType() ) {
3712 shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3717 shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3725 p.Translate( shift * 1e-5 );
3727 TopLoc_Location loc;
3728 GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3730 if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3732 projector.Perform( p );
3733 if ( !projector.IsDone() || projector.NbPoints() < 1 )
3739 projector.LowerDistanceParameters(U,V);
3744 uv = helper.GetNodeUV( face, node, 0, &isOK );
3750 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3752 if ( !shiftInside &&
3753 helper.IsDegenShape( node->getshapeId() ) &&
3754 getFaceNormalAtSingularity( uv, face, helper, normal ))
3757 return normal.XYZ();
3760 int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3761 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3763 if ( pointKind == IMPOSSIBLE &&
3764 node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3766 // probably NormEstim() failed due to a too high tolerance
3767 pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3768 isOK = ( pointKind < IMPOSSIBLE );
3770 if ( pointKind < IMPOSSIBLE )
3772 if ( pointKind != REGULAR &&
3774 node->GetPosition()->GetDim() < 2 ) // FACE boundary
3776 gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3777 if ( normShift * normal.XYZ() < 0. )
3783 if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3785 const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3787 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3788 while ( fIt->more() )
3790 const SMDS_MeshElement* f = fIt->next();
3791 if ( f->getshapeId() == faceID )
3793 isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3796 TopoDS_Face ff = face;
3797 ff.Orientation( TopAbs_FORWARD );
3798 if ( helper.IsReversedSubMesh( ff ))
3805 return normal.XYZ();
3808 //================================================================================
3810 * \brief Try to get normal at a singularity of a surface basing on it's nature
3812 //================================================================================
3814 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY& uv,
3815 const TopoDS_Face& face,
3816 SMESH_MesherHelper& helper,
3819 BRepAdaptor_Surface surface( face );
3821 if ( !getRovolutionAxis( surface, axis ))
3824 double f,l, d, du, dv;
3825 f = surface.FirstUParameter();
3826 l = surface.LastUParameter();
3827 d = ( uv.X() - f ) / ( l - f );
3828 du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3829 f = surface.FirstVParameter();
3830 l = surface.LastVParameter();
3831 d = ( uv.Y() - f ) / ( l - f );
3832 dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3835 gp_Pnt2d testUV = uv;
3836 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3838 Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3839 for ( int iLoop = 0; true ; ++iLoop )
3841 testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3842 if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3849 if ( axis * refDir < 0. )
3857 //================================================================================
3859 * \brief Return a normal at a node weighted with angles taken by faces
3861 //================================================================================
3863 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3865 const SMDS_MeshNode* n = edge->_nodes[0];
3867 gp_XYZ resNorm(0,0,0);
3868 SMESH_TNodeXYZ p0( n ), pP, pN;
3869 for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3871 pP.Set( edge->_simplices[i]._nPrev );
3872 pN.Set( edge->_simplices[i]._nNext );
3873 gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3874 double l0P = v0P.SquareMagnitude();
3875 double l0N = v0N.SquareMagnitude();
3876 double lPN = vPN.SquareMagnitude();
3877 if ( l0P < std::numeric_limits<double>::min() ||
3878 l0N < std::numeric_limits<double>::min() ||
3879 lPN < std::numeric_limits<double>::min() )
3881 double lNorm = norm.SquareMagnitude();
3882 double sin2 = lNorm / l0P / l0N;
3883 double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3885 double weight = sin2 * angle / lPN;
3886 resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3892 //================================================================================
3894 * \brief Return a normal at a node by getting a common point of offset planes
3895 * defined by the FACE normals
3897 //================================================================================
3899 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge* edge,
3900 std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3904 SMESH_TNodeXYZ p0 = edge->_nodes[0];
3906 gp_XYZ resNorm(0,0,0);
3907 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3908 if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3910 for ( int i = 0; i < nbFaces; ++i )
3911 resNorm += f2Normal[i].second;
3915 // prepare _OffsetPlane's
3916 vector< _OffsetPlane > pln( nbFaces );
3917 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3919 pln[i]._faceIndex = i;
3920 pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3924 pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3925 pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3928 // intersect neighboring OffsetPlane's
3929 PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3930 while ( const TopoDS_Shape* edge = edgeIt->next() )
3932 int f1 = -1, f2 = -1;
3933 for ( int i = 0; i < nbFaces && f2 < 0; ++i )
3934 if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3935 (( f1 < 0 ) ? f1 : f2 ) = i;
3938 pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3941 // get a common point
3942 gp_XYZ commonPnt( 0, 0, 0 );
3945 for ( int i = 0; i < nbFaces; ++i )
3947 commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3948 nbPoints += isPointFound;
3950 gp_XYZ wgtNorm = getWeigthedNormal( edge );
3951 if ( nbPoints == 0 )
3954 commonPnt /= nbPoints;
3955 resNorm = commonPnt - p0;
3959 // choose the best among resNorm and wgtNorm
3960 resNorm.Normalize();
3961 wgtNorm.Normalize();
3962 double resMinDot = std::numeric_limits<double>::max();
3963 double wgtMinDot = std::numeric_limits<double>::max();
3964 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3966 resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3967 wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3970 if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3972 edge->Set( _LayerEdge::MULTI_NORMAL );
3975 return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3978 //================================================================================
3980 * \brief Compute line of intersection of 2 planes
3982 //================================================================================
3984 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane& pln,
3985 const TopoDS_Edge& E,
3986 const TopoDS_Vertex& V )
3988 int iNext = bool( _faceIndexNext[0] >= 0 );
3989 _faceIndexNext[ iNext ] = pln._faceIndex;
3991 gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3992 gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3994 gp_XYZ lineDir = n1 ^ n2;
3996 double x = Abs( lineDir.X() );
3997 double y = Abs( lineDir.Y() );
3998 double z = Abs( lineDir.Z() );
4000 int cooMax; // max coordinate
4002 if (x > z) cooMax = 1;
4006 if (y > z) cooMax = 2;
4011 if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
4013 // parallel planes - intersection is an offset of the common EDGE
4014 gp_Pnt p = BRep_Tool::Pnt( V );
4015 linePos = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
4016 lineDir = getEdgeDir( E, V );
4020 // the constants in the 2 plane equations
4021 double d1 = - ( _plane.Axis().Direction().XYZ() * _plane.Location().XYZ() );
4022 double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
4027 linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
4028 linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
4031 linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4033 linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4036 linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4037 linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4041 gp_Lin& line = _lines[ iNext ];
4042 line.SetDirection( lineDir );
4043 line.SetLocation ( linePos );
4045 _isLineOK[ iNext ] = true;
4048 iNext = bool( pln._faceIndexNext[0] >= 0 );
4049 pln._lines [ iNext ] = line;
4050 pln._faceIndexNext[ iNext ] = this->_faceIndex;
4051 pln._isLineOK [ iNext ] = true;
4054 //================================================================================
4056 * \brief Computes intersection point of two _lines
4058 //================================================================================
4060 gp_XYZ _OffsetPlane::GetCommonPoint(bool& isFound,
4061 const TopoDS_Vertex & V) const
4066 if ( NbLines() == 2 )
4068 gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4069 double dot01 = lPerp0 * _lines[1].Direction().XYZ();
4070 if ( Abs( dot01 ) > 0.05 )
4072 gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4073 double u1 = - ( lPerp0 * l0l1 ) / dot01;
4074 p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4079 gp_Pnt pV ( BRep_Tool::Pnt( V ));
4080 gp_Vec lv0( _lines[0].Location(), pV ), lv1(_lines[1].Location(), pV );
4081 double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4082 p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4083 p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4091 //================================================================================
4093 * \brief Find 2 neigbor nodes of a node on EDGE
4095 //================================================================================
4097 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
4098 const SMDS_MeshNode*& n1,
4099 const SMDS_MeshNode*& n2,
4103 const SMDS_MeshNode* node = edge->_nodes[0];
4104 const int shapeInd = eos._shapeID;
4105 SMESHDS_SubMesh* edgeSM = 0;
4106 if ( eos.ShapeType() == TopAbs_EDGE )
4108 edgeSM = eos._subMesh->GetSubMeshDS();
4109 if ( !edgeSM || edgeSM->NbElements() == 0 )
4110 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4114 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4115 while ( eIt->more() && !n2 )
4117 const SMDS_MeshElement* e = eIt->next();
4118 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
4119 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4122 if (!edgeSM->Contains(e)) continue;
4126 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4127 if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4129 ( iN++ ? n2 : n1 ) = nNeibor;
4132 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4136 //================================================================================
4138 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4140 //================================================================================
4142 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4143 const SMDS_MeshNode* n2,
4144 const _EdgesOnShape& eos,
4145 SMESH_MesherHelper& helper)
4147 if ( eos.ShapeType() != TopAbs_EDGE )
4149 if ( _curvature && Is( SMOOTHED_C1 ))
4152 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
4153 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4154 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4158 double sumLen = vec1.Modulus() + vec2.Modulus();
4159 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4160 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4161 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4162 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4163 if ( _curvature ) delete _curvature;
4164 _curvature = _Curvature::New( avgNormProj, avgLen );
4165 // if ( _curvature )
4166 // debugMsg( _nodes[0]->GetID()
4167 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4168 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4169 // << _curvature->lenDelta(0) );
4173 if ( eos._sWOL.IsNull() )
4175 TopoDS_Edge E = TopoDS::Edge( eos._shape );
4176 // if ( SMESH_Algo::isDegenerated( E ))
4178 gp_XYZ dirE = getEdgeDir( E, _nodes[0], helper );
4179 gp_XYZ plnNorm = dirE ^ _normal;
4180 double proj0 = plnNorm * vec1;
4181 double proj1 = plnNorm * vec2;
4182 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4184 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4185 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4190 //================================================================================
4192 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4193 * this and the other _LayerEdge are inflated along a FACE or an EDGE
4195 //================================================================================
4197 gp_XYZ _LayerEdge::Copy( _LayerEdge& other,
4199 SMESH_MesherHelper& helper )
4201 _nodes = other._nodes;
4202 _normal = other._normal;
4204 _lenFactor = other._lenFactor;
4205 _cosin = other._cosin;
4206 _2neibors = other._2neibors;
4207 _curvature = 0; std::swap( _curvature, other._curvature );
4208 _2neibors = 0; std::swap( _2neibors, other._2neibors );
4210 gp_XYZ lastPos( 0,0,0 );
4211 if ( eos.SWOLType() == TopAbs_EDGE )
4213 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4214 _pos.push_back( gp_XYZ( u, 0, 0));
4216 u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4221 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4222 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4224 uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4225 lastPos.SetX( uv.X() );
4226 lastPos.SetY( uv.Y() );
4231 //================================================================================
4233 * \brief Set _cosin and _lenFactor
4235 //================================================================================
4237 void _LayerEdge::SetCosin( double cosin )
4240 cosin = Abs( _cosin );
4241 //_lenFactor = ( cosin < 1.-1e-12 ) ? Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4242 _lenFactor = ( cosin < 1.-1e-12 ) ? 1./sqrt(1-cosin*cosin ) : 1.0;
4245 //================================================================================
4247 * \brief Check if another _LayerEdge is a neighbor on EDGE
4249 //================================================================================
4251 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4253 return (( this->_2neibors && this->_2neibors->include( edge )) ||
4254 ( edge->_2neibors && edge->_2neibors->include( this )));
4257 //================================================================================
4259 * \brief Fills a vector<_Simplex >
4261 //================================================================================
4263 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4264 vector<_Simplex>& simplices,
4265 const set<TGeomID>& ingnoreShapes,
4266 const _SolidData* dataToCheckOri,
4270 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4271 while ( fIt->more() )
4273 const SMDS_MeshElement* f = fIt->next();
4274 const TGeomID shapeInd = f->getshapeId();
4275 if ( ingnoreShapes.count( shapeInd )) continue;
4276 const int nbNodes = f->NbCornerNodes();
4277 const int srcInd = f->GetNodeIndex( node );
4278 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4279 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4280 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4281 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4282 std::swap( nPrev, nNext );
4283 simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4287 SortSimplices( simplices );
4290 //================================================================================
4292 * \brief Set neighbor simplices side by side
4294 //================================================================================
4296 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4298 vector<_Simplex> sortedSimplices( simplices.size() );
4299 sortedSimplices[0] = simplices[0];
4301 for ( size_t i = 1; i < simplices.size(); ++i )
4303 for ( size_t j = 1; j < simplices.size(); ++j )
4304 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4306 sortedSimplices[i] = simplices[j];
4311 if ( nbFound == simplices.size() - 1 )
4312 simplices.swap( sortedSimplices );
4315 //================================================================================
4317 * \brief DEBUG. Create groups containing temporary data of _LayerEdge's
4319 //================================================================================
4321 void _ViscousBuilder::makeGroupOfLE()
4324 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4326 if ( _sdVec[i]._n2eMap.empty() ) continue;
4328 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4329 TNode2Edge::iterator n2e;
4330 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4332 _LayerEdge* le = n2e->second;
4333 // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4334 // dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4335 // << ", " << le->_nodes[iN]->GetID() <<"])");
4337 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4338 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4343 dumpFunction( SMESH_Comment("makeNormals") << i );
4344 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4346 _LayerEdge* edge = n2e->second;
4347 SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4348 nXYZ += edge->_normal * _sdVec[i]._stepSize;
4349 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4350 << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4354 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4355 dumpCmd( "faceId1 = mesh.NbElements()" );
4356 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4357 for ( ; fExp.More(); fExp.Next() )
4359 if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4361 if ( sm->NbElements() == 0 ) continue;
4362 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4363 while ( fIt->more())
4365 const SMDS_MeshElement* e = fIt->next();
4366 SMESH_Comment cmd("mesh.AddFace([");
4367 for ( int j = 0; j < e->NbCornerNodes(); ++j )
4368 cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4373 dumpCmd( "faceId2 = mesh.NbElements()" );
4374 dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4375 << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4376 << "'%s-%s' % (faceId1+1, faceId2))");
4382 //================================================================================
4384 * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4386 //================================================================================
4388 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4390 data._geomSize = Precision::Infinite();
4391 double intersecDist;
4392 const SMDS_MeshElement* face;
4393 SMESH_MesherHelper helper( *_mesh );
4395 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4396 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4397 data._proxyMesh->GetFaces( data._solid )));
4399 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4401 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4402 if ( eos._edges.empty() )
4404 // get neighbor faces, intersection with which should not be considered since
4405 // collisions are avoided by means of smoothing
4406 set< TGeomID > neighborFaces;
4407 if ( eos._hyp.ToSmooth() )
4409 SMESH_subMeshIteratorPtr subIt =
4410 eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4411 while ( subIt->more() )
4413 SMESH_subMesh* sm = subIt->next();
4414 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4415 while ( const TopoDS_Shape* face = fIt->next() )
4416 neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4419 // find intersections
4420 double thinkness = eos._hyp.GetTotalThickness();
4421 for ( size_t i = 0; i < eos._edges.size(); ++i )
4423 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4424 eos._edges[i]->SetMaxLen( thinkness );
4425 eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4426 if ( intersecDist > 0 && face )
4428 data._geomSize = Min( data._geomSize, intersecDist );
4429 if ( !neighborFaces.count( face->getshapeId() ))
4430 eos[i]->SetMaxLen( Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. )));
4435 data._maxThickness = 0;
4436 data._minThickness = 1e100;
4437 list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
4438 for ( ; hyp != data._hyps.end(); ++hyp )
4440 data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
4441 data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
4444 // Limit inflation step size by geometry size found by intersecting
4445 // normals of _LayerEdge's with mesh faces
4446 if ( data._stepSize > 0.3 * data._geomSize )
4447 limitStepSize( data, 0.3 * data._geomSize );
4449 if ( data._stepSize > data._minThickness )
4450 limitStepSize( data, data._minThickness );
4453 // -------------------------------------------------------------------------
4454 // Detect _LayerEdge which can't intersect with opposite or neighbor layer,
4455 // so no need in detecting intersection at each inflation step
4456 // -------------------------------------------------------------------------
4458 int nbSteps = data._maxThickness / data._stepSize;
4459 if ( nbSteps < 3 || nbSteps * data._n2eMap.size() < 100000 )
4462 vector< const SMDS_MeshElement* > closeFaces;
4465 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4467 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4468 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
4471 for ( size_t i = 0; i < eos.size(); ++i )
4473 SMESH_NodeXYZ p( eos[i]->_nodes[0] );
4474 double radius = data._maxThickness + 2 * eos[i]->_maxLen;
4476 searcher->GetElementsInSphere( p, radius, SMDSAbs_Face, closeFaces );
4478 bool toIgnore = true;
4479 for ( size_t iF = 0; iF < closeFaces.size() && toIgnore; ++iF )
4480 if ( !( toIgnore = ( closeFaces[ iF ]->getshapeId() == eos._shapeID ||
4481 data._ignoreFaceIds.count( closeFaces[ iF ]->getshapeId() ))))
4483 // check if a _LayerEdge will inflate in a direction opposite to a direction
4484 // toward a close face
4485 bool allBehind = true;
4486 for ( int iN = 0; iN < closeFaces[ iF ]->NbCornerNodes() && allBehind; ++iN )
4488 SMESH_NodeXYZ pi( closeFaces[ iF ]->GetNode( iN ));
4489 allBehind = (( pi - p ) * eos[i]->_normal < 0.1 * data._stepSize );
4491 toIgnore = allBehind;
4495 if ( toIgnore ) // no need to detect intersection
4497 eos[i]->Set( _LayerEdge::INTERSECTED );
4503 debugMsg( "Nb LE to intersect " << data._n2eMap.size()-nbDetected << ", ignore " << nbDetected );
4508 //================================================================================
4510 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4512 //================================================================================
4514 bool _ViscousBuilder::inflate(_SolidData& data)
4516 SMESH_MesherHelper helper( *_mesh );
4518 const double tgtThick = data._maxThickness;
4520 if ( data._stepSize < 1. )
4521 data._epsilon = data._stepSize * 1e-7;
4523 debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4526 findCollisionEdges( data, helper );
4528 limitMaxLenByCurvature( data, helper );
4532 // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4533 for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4534 if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4535 data._edgesOnShape[i]._edges.size() > 0 &&
4536 data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4538 data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4539 data._edgesOnShape[i]._edges[0]->Block( data );
4542 const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4544 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4545 int nbSteps = 0, nbRepeats = 0;
4546 while ( avgThick < 0.99 )
4548 // new target length
4549 double prevThick = curThick;
4550 curThick += data._stepSize;
4551 if ( curThick > tgtThick )
4553 curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4557 double stepSize = curThick - prevThick;
4558 updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4560 // Elongate _LayerEdge's
4561 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4562 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4564 _EdgesOnShape& eos = data._edgesOnShape[iS];
4565 if ( eos._edges.empty() ) continue;
4567 const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4568 for ( size_t i = 0; i < eos._edges.size(); ++i )
4570 eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4575 if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4578 // Improve and check quality
4579 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4583 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4584 debugMsg("NOT INVALIDATED STEP!");
4585 return error("Smoothing failed", data._index);
4587 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4588 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4590 _EdgesOnShape& eos = data._edgesOnShape[iS];
4591 for ( size_t i = 0; i < eos._edges.size(); ++i )
4592 eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4596 break; // no more inflating possible
4600 // Evaluate achieved thickness
4602 int nbActiveEdges = 0;
4603 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4605 _EdgesOnShape& eos = data._edgesOnShape[iS];
4606 if ( eos._edges.empty() ) continue;
4608 const double shapeTgtThick = eos._hyp.GetTotalThickness();
4609 for ( size_t i = 0; i < eos._edges.size(); ++i )
4611 if ( eos._edges[i]->_nodes.size() > 1 )
4612 avgThick += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4614 avgThick += shapeTgtThick;
4615 nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4618 avgThick /= data._n2eMap.size();
4619 debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4621 #ifdef BLOCK_INFLATION
4622 if ( nbActiveEdges == 0 )
4624 debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4628 if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4630 debugMsg( "-- Stop inflation since "
4631 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4632 << tgtThick * avgThick << " ) * " << safeFactor );
4638 limitStepSize( data, 0.25 * distToIntersection );
4639 if ( data._stepSizeNodes[0] )
4640 data._stepSize = data._stepSizeCoeff *
4641 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4643 } // while ( avgThick < 0.99 )
4646 return error("failed at the very first inflation step", data._index);
4648 if ( avgThick < 0.99 )
4650 if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4652 data._proxyMesh->_warning.reset
4653 ( new SMESH_ComputeError (COMPERR_WARNING,
4654 SMESH_Comment("Thickness ") << tgtThick <<
4655 " of viscous layers not reached,"
4656 " average reached thickness is " << avgThick*tgtThick));
4660 // Restore position of src nodes moved by inflation on _noShrinkShapes
4661 dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4662 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4664 _EdgesOnShape& eos = data._edgesOnShape[iS];
4665 if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4666 for ( size_t i = 0; i < eos._edges.size(); ++i )
4668 restoreNoShrink( *eos._edges[ i ] );
4673 return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4676 //================================================================================
4678 * \brief Improve quality of layer inner surface and check intersection
4680 //================================================================================
4682 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4684 double & distToIntersection)
4686 if ( data._nbShapesToSmooth == 0 )
4687 return true; // no shapes needing smoothing
4689 bool moved, improved;
4691 vector< _LayerEdge* > movedEdges, badEdges;
4692 vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4693 vector< bool > isConcaveFace;
4695 SMESH_MesherHelper helper(*_mesh);
4696 Handle(ShapeAnalysis_Surface) surface;
4699 for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4701 const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4703 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4705 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4706 if ( !eos._toSmooth ||
4707 eos.ShapeType() != shapeType ||
4708 eos._edges.empty() )
4711 // already smoothed?
4712 // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4713 // if ( !toSmooth ) continue;
4715 if ( !eos._hyp.ToSmooth() )
4717 // smooth disabled by the user; check validy only
4718 if ( !isFace ) continue;
4720 for ( size_t i = 0; i < eos._edges.size(); ++i )
4722 _LayerEdge* edge = eos._edges[i];
4723 for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4724 if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4726 // debugMsg( "-- Stop inflation. Bad simplex ("
4727 // << " "<< edge->_nodes[0]->GetID()
4728 // << " "<< edge->_nodes.back()->GetID()
4729 // << " "<< edge->_simplices[iF]._nPrev->GetID()
4730 // << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4732 badEdges.push_back( edge );
4735 if ( !badEdges.empty() )
4739 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4743 continue; // goto the next EDGE or FACE
4747 if ( eos.SWOLType() == TopAbs_FACE )
4749 if ( !F.IsSame( eos._sWOL )) {
4750 F = TopoDS::Face( eos._sWOL );
4751 helper.SetSubShape( F );
4752 surface = helper.GetSurface( F );
4757 F.Nullify(); surface.Nullify();
4759 const TGeomID sInd = eos._shapeID;
4761 // perform smoothing
4763 if ( eos.ShapeType() == TopAbs_EDGE )
4765 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4767 if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4769 // smooth on EDGE's (normally we should not get here)
4773 for ( size_t i = 0; i < eos._edges.size(); ++i )
4775 moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4777 dumpCmd( SMESH_Comment("# end step ")<<step);
4779 while ( moved && step++ < 5 );
4784 else // smooth on FACE
4787 eosC1.push_back( & eos );
4788 eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4791 isConcaveFace.resize( eosC1.size() );
4792 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4794 isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID );
4795 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4796 for ( size_t i = 0; i < edges.size(); ++i )
4797 if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4798 edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4799 movedEdges.push_back( edges[i] );
4801 makeOffsetSurface( *eosC1[ iEOS ], helper );
4804 int step = 0, stepLimit = 5, nbBad = 0;
4805 while (( ++step <= stepLimit ) || improved )
4807 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4808 <<"_InfStep"<<infStep<<"_"<<step); // debug
4809 int oldBadNb = nbBad;
4812 #ifdef INCREMENTAL_SMOOTH
4813 bool findBest = false; // ( step == stepLimit );
4814 for ( size_t i = 0; i < movedEdges.size(); ++i )
4816 movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4817 if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4818 badEdges.push_back( movedEdges[i] );
4821 bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4822 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4824 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4825 for ( size_t i = 0; i < edges.size(); ++i )
4827 edges[i]->Unset( _LayerEdge::SMOOTHED );
4828 if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4829 badEdges.push_back( eos._edges[i] );
4833 nbBad = badEdges.size();
4836 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4838 if ( !badEdges.empty() && step >= stepLimit / 2 )
4840 if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4843 // resolve hard smoothing situation around concave VERTEXes
4844 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4846 vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4847 for ( size_t i = 0; i < eosCoVe.size(); ++i )
4848 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4851 // look for the best smooth of _LayerEdge's neighboring badEdges
4853 for ( size_t i = 0; i < badEdges.size(); ++i )
4855 _LayerEdge* ledge = badEdges[i];
4856 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4858 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4859 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4861 ledge->Unset( _LayerEdge::SMOOTHED );
4862 nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4864 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4867 if ( nbBad == oldBadNb &&
4869 step < stepLimit ) // smooth w/o check of validity
4872 dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4873 <<"_InfStep"<<infStep<<"_"<<step); // debug
4874 for ( size_t i = 0; i < movedEdges.size(); ++i )
4876 movedEdges[i]->SmoothWoCheck();
4878 if ( stepLimit < 9 )
4882 improved = ( nbBad < oldBadNb );
4886 if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4887 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4889 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4892 } // smoothing steps
4894 // project -- to prevent intersections or fix bad simplices
4895 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4897 if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4898 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4901 //if ( !badEdges.empty() )
4904 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4906 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4908 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4910 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4911 edge->CheckNeiborsOnBoundary( & badEdges );
4912 if (( nbBad > 0 ) ||
4913 ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4915 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4916 gp_XYZ prevXYZ = edge->PrevCheckPos();
4917 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4918 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4920 debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4921 << " "<< tgtXYZ._node->GetID()
4922 << " "<< edge->_simplices[j]._nPrev->GetID()
4923 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4924 badEdges.push_back( edge );
4931 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4932 nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4938 } // // smooth on FACE's
4940 } // smooth on [ EDGEs, FACEs ]
4942 // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4944 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4946 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4947 if ( eos.ShapeType() == TopAbs_FACE ||
4948 eos._edges.empty() ||
4949 !eos._sWOL.IsNull() )
4953 for ( size_t i = 0; i < eos._edges.size(); ++i )
4955 _LayerEdge* edge = eos._edges[i];
4956 if ( edge->_nodes.size() < 2 ) continue;
4957 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4958 //SMESH_TNodeXYZ prevXYZ = edge->_nodes[0];
4959 gp_XYZ prevXYZ = edge->PrevCheckPos( &eos );
4960 //const gp_XYZ& prevXYZ = edge->PrevPos();
4961 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4962 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4964 debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4965 << " "<< tgtXYZ._node->GetID()
4966 << " "<< edge->_simplices[j]._nPrev->GetID()
4967 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4968 badEdges.push_back( edge );
4973 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4975 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4981 // Check if the last segments of _LayerEdge intersects 2D elements;
4982 // checked elements are either temporary faces or faces on surfaces w/o the layers
4984 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4985 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4986 data._proxyMesh->GetFaces( data._solid )) );
4988 #ifdef BLOCK_INFLATION
4989 const bool toBlockInfaltion = true;
4991 const bool toBlockInfaltion = false;
4993 distToIntersection = Precision::Infinite();
4995 const SMDS_MeshElement* intFace = 0;
4996 const SMDS_MeshElement* closestFace = 0;
4998 bool is1stBlocked = true; // dbg
4999 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5001 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5002 if ( eos._edges.empty() || !eos._sWOL.IsNull() )
5004 for ( size_t i = 0; i < eos._edges.size(); ++i )
5006 if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
5007 eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
5009 if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5012 // commented due to "Illegal hash-positionPosition" error in NETGEN
5013 // on Debian60 on viscous_layers_01/B2 case
5014 // Collision; try to deflate _LayerEdge's causing it
5015 // badEdges.clear();
5016 // badEdges.push_back( eos._edges[i] );
5017 // eosC1[0] = & eos;
5018 // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5022 // badEdges.clear();
5023 // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5025 // if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5027 // const SMDS_MeshElement* srcFace =
5028 // eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5029 // SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5030 // while ( nIt->more() )
5032 // const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5033 // TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5034 // if ( n2e != data._n2eMap.end() )
5035 // badEdges.push_back( n2e->second );
5038 // nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5043 // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5050 SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
5055 const bool isShorterDist = ( distToIntersection > dist );
5056 if ( toBlockInfaltion || isShorterDist )
5058 // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
5059 // lying on this _ConvexFace
5060 if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
5061 if ( convFace->_isTooCurved && convFace->_subIdToEOS.count ( eos._shapeID ))
5064 // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
5065 // ( avoid limiting the thickness on the case of issue 22576)
5066 if ( intFace->getshapeId() == eos._shapeID )
5069 // ignore intersection with intFace of an adjacent FACE
5070 if ( dist > 0.1 * eos._edges[i]->_len )
5072 bool toIgnore = false;
5073 if ( eos._toSmooth )
5075 const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
5076 if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
5078 TopExp_Explorer sub( eos._shape,
5079 eos.ShapeType() == TopAbs_FACE ? TopAbs_EDGE : TopAbs_VERTEX );
5080 for ( ; !toIgnore && sub.More(); sub.Next() )
5081 // is adjacent - has a common EDGE or VERTEX
5082 toIgnore = ( helper.IsSubShape( sub.Current(), S ));
5084 if ( toIgnore ) // check angle between normals
5087 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
5088 toIgnore = ( normal * eos._edges[i]->_normal > -0.5 );
5092 if ( !toIgnore ) // check if the edge is a neighbor of intFace
5094 for ( size_t iN = 0; !toIgnore && iN < eos._edges[i]->_neibors.size(); ++iN )
5096 int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
5097 toIgnore = ( nInd >= 0 );
5104 // intersection not ignored
5106 if ( toBlockInfaltion &&
5107 dist < ( eos._edges[i]->_len * theThickToIntersection ))
5109 if ( is1stBlocked ) { is1stBlocked = false; // debug
5110 dumpFunction(SMESH_Comment("blockIntersected") <<data._index<<"_InfStep"<<infStep);
5112 eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5113 eos._edges[i]->Block( data ); // not to inflate
5115 //if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5117 // block _LayerEdge's, on top of which intFace is
5118 if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5120 const SMDS_MeshElement* srcFace = f->_srcFace;
5121 SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5122 while ( nIt->more() )
5124 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5125 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5126 if ( n2e != data._n2eMap.end() )
5127 n2e->second->Block( data );
5133 if ( isShorterDist )
5135 distToIntersection = dist;
5137 closestFace = intFace;
5140 } // if ( toBlockInfaltion || isShorterDist )
5141 } // loop on eos._edges
5142 } // loop on data._edgesOnShape
5144 if ( !is1stBlocked )
5147 if ( closestFace && le )
5150 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5151 cout << "#Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5152 << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5153 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5154 << ") distance = " << distToIntersection<< endl;
5161 //================================================================================
5163 * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5164 * \param [in,out] badSmooEdges - _LayerEdge's to fix
5165 * \return int - resulting nb of bad _LayerEdge's
5167 //================================================================================
5169 int _ViscousBuilder::invalidateBadSmooth( _SolidData& data,
5170 SMESH_MesherHelper& helper,
5171 vector< _LayerEdge* >& badSmooEdges,
5172 vector< _EdgesOnShape* >& eosC1,
5175 if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5177 dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5180 INVALIDATED = _LayerEdge::UNUSED_FLAG,
5181 TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5182 ADDED = _LayerEdge::UNUSED_FLAG * 4
5184 data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5187 bool haveInvalidated = true;
5188 while ( haveInvalidated )
5190 haveInvalidated = false;
5191 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5193 _LayerEdge* edge = badSmooEdges[i];
5194 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5196 bool invalidated = false;
5197 if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5199 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5200 edge->Block( data );
5201 edge->Set( INVALIDATED );
5202 edge->Unset( TO_INVALIDATE );
5204 haveInvalidated = true;
5207 // look for _LayerEdge's of bad _simplices
5209 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5210 gp_XYZ prevXYZ1 = edge->PrevCheckPos( eos );
5211 //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5212 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5214 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5215 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5219 _LayerEdge* ee[2] = { 0,0 };
5220 for ( size_t iN = 0; iN < edge->_neibors.size() && !ee[1] ; ++iN )
5221 if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5222 ee[ ee[0] != 0 ] = edge->_neibors[iN];
5224 int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5225 while ( maxNbSteps > edge->NbSteps() && isBad )
5228 for ( int iE = 0; iE < 2; ++iE )
5230 if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5231 ee[ iE ]->NbSteps() > 1 )
5233 _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5234 ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5235 ee[ iE ]->Block( data );
5236 ee[ iE ]->Set( INVALIDATED );
5237 haveInvalidated = true;
5240 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5241 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5245 if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5246 if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5247 ee[0]->Set( ADDED );
5248 ee[1]->Set( ADDED );
5251 ee[0]->Set( TO_INVALIDATE );
5252 ee[1]->Set( TO_INVALIDATE );
5256 if ( !invalidated && nbBad > 0 && edge->NbSteps() > 1 )
5258 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5259 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5260 edge->Block( data );
5261 edge->Set( INVALIDATED );
5262 edge->Unset( TO_INVALIDATE );
5263 haveInvalidated = true;
5265 } // loop on badSmooEdges
5266 } // while ( haveInvalidated )
5268 // re-smooth on analytical EDGEs
5269 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5271 _LayerEdge* edge = badSmooEdges[i];
5272 if ( !edge->Is( INVALIDATED )) continue;
5274 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5275 if ( eos->ShapeType() == TopAbs_VERTEX )
5277 PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5278 while ( const TopoDS_Shape* e = eIt->next() )
5279 if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5280 if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5282 // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5283 // if ( eoe->SWOLType() == TopAbs_FACE ) {
5284 // F = TopoDS::Face( eoe->_sWOL );
5285 // surface = helper.GetSurface( F );
5287 // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5288 eoe->_edgeSmoother->_anaCurve.Nullify();
5294 // check result of invalidation
5297 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5299 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5301 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5302 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5303 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5304 gp_XYZ prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5305 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5306 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5309 debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5310 << " "<< tgtXYZ._node->GetID()
5311 << " "<< edge->_simplices[j]._nPrev->GetID()
5312 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5321 //================================================================================
5323 * \brief Create an offset surface
5325 //================================================================================
5327 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5329 if ( eos._offsetSurf.IsNull() ||
5330 eos._edgeForOffset == 0 ||
5331 eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5334 Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5337 gp_Pnt tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5338 /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5339 double offset = baseSurface->Gap();
5341 eos._offsetSurf.Nullify();
5345 BRepOffsetAPI_MakeOffsetShape offsetMaker;
5346 offsetMaker.PerformByJoin( eos._shape, -offset, Precision::Confusion() );
5347 if ( !offsetMaker.IsDone() ) return;
5349 TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5350 if ( !fExp.More() ) return;
5352 TopoDS_Face F = TopoDS::Face( fExp.Current() );
5353 Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5354 if ( surf.IsNull() ) return;
5356 eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5358 catch ( Standard_Failure )
5363 //================================================================================
5365 * \brief Put nodes of a curved FACE to its offset surface
5367 //================================================================================
5369 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape& eos,
5371 vector< _EdgesOnShape* >& eosC1,
5375 _EdgesOnShape * eof = & eos;
5376 if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5379 for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5381 if ( eosC1[i]->_offsetSurf.IsNull() ||
5382 eosC1[i]->ShapeType() != TopAbs_FACE ||
5383 eosC1[i]->_edgeForOffset == 0 ||
5384 eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5386 if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5391 eof->_offsetSurf.IsNull() ||
5392 eof->ShapeType() != TopAbs_FACE ||
5393 eof->_edgeForOffset == 0 ||
5394 eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5397 double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5398 for ( size_t i = 0; i < eos._edges.size(); ++i )
5400 _LayerEdge* edge = eos._edges[i];
5401 edge->Unset( _LayerEdge::MARKED );
5402 if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5404 if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5406 if ( !edge->Is( _LayerEdge::UPD_NORMAL_CONV ))
5409 else if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5412 int nbBlockedAround = 0;
5413 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5414 nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5415 if ( nbBlockedAround > 1 )
5418 gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5419 gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5420 if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5421 edge->_curvature->_uv = uv;
5422 if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5424 gp_XYZ newP = eof->_offsetSurf->Value( uv ).XYZ();
5425 gp_XYZ prevP = edge->PrevCheckPos();
5428 for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5430 ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5434 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5435 n->setXYZ( newP.X(), newP.Y(), newP.Z());
5436 edge->_pos.back() = newP;
5438 edge->Set( _LayerEdge::MARKED );
5439 if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5441 edge->_normal = ( newP - prevP ).Normalized();
5449 // dumpMove() for debug
5451 for ( ; i < eos._edges.size(); ++i )
5452 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5454 if ( i < eos._edges.size() )
5456 dumpFunction(SMESH_Comment("putOnOffsetSurface_S") << eos._shapeID
5457 << "_InfStep" << infStep << "_" << smooStep );
5458 for ( ; i < eos._edges.size(); ++i )
5460 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5461 dumpMove( eos._edges[i]->_nodes.back() );
5467 _ConvexFace* cnvFace;
5468 if ( moveAll != _LayerEdge::UPD_NORMAL_CONV &&
5469 eos.ShapeType() == TopAbs_FACE &&
5470 (cnvFace = eos.GetData().GetConvexFace( eos._shapeID )) &&
5471 !cnvFace->_normalsFixedOnBorders )
5473 // put on the surface nodes built on FACE boundaries
5474 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5475 while ( smIt->more() )
5477 SMESH_subMesh* sm = smIt->next();
5478 _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5479 if ( !subEOS->_sWOL.IsNull() ) continue;
5480 if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5482 putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::UPD_NORMAL_CONV );
5484 cnvFace->_normalsFixedOnBorders = true;
5488 //================================================================================
5490 * \brief Return a curve of the EDGE to be used for smoothing and arrange
5491 * _LayerEdge's to be in a consequent order
5493 //================================================================================
5495 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge& E,
5497 SMESH_MesherHelper& helper)
5499 SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5501 TopLoc_Location loc; double f,l;
5503 Handle(Geom_Line) line;
5504 Handle(Geom_Circle) circle;
5505 bool isLine, isCirc;
5506 if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5508 // check if the EDGE is a line
5509 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5510 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5511 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5513 line = Handle(Geom_Line)::DownCast( curve );
5514 circle = Handle(Geom_Circle)::DownCast( curve );
5515 isLine = (!line.IsNull());
5516 isCirc = (!circle.IsNull());
5518 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5520 isLine = SMESH_Algo::IsStraight( E );
5523 line = new Geom_Line( gp::OX() ); // only type does matter
5525 if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5530 else //////////////////////////////////////////////////////////////////////// 2D case
5532 if ( !eos._isRegularSWOL ) // 23190
5535 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5537 // check if the EDGE is a line
5538 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5539 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5540 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5542 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
5543 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5544 isLine = (!line2d.IsNull());
5545 isCirc = (!circle2d.IsNull());
5547 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5550 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5551 while ( nIt->more() )
5552 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5553 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5555 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5556 for ( int i = 0; i < 2 && !isLine; ++i )
5557 isLine = ( size.Coord( i+1 ) <= lineTol );
5559 if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5565 line = new Geom_Line( gp::OX() ); // only type does matter
5569 gp_Pnt2d p = circle2d->Location();
5570 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5571 circle = new Geom_Circle( ax, 1.); // only center position does matter
5580 return Handle(Geom_Curve)();
5583 //================================================================================
5585 * \brief Smooth edges on EDGE
5587 //================================================================================
5589 bool _Smoother1D::Perform(_SolidData& data,
5590 Handle(ShapeAnalysis_Surface)& surface,
5591 const TopoDS_Face& F,
5592 SMESH_MesherHelper& helper )
5594 if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
5597 findEdgesToSmooth();
5599 return smoothAnalyticEdge( data, surface, F, helper );
5601 return smoothComplexEdge ( data, surface, F, helper );
5604 //================================================================================
5606 * \brief Find edges to smooth
5608 //================================================================================
5610 void _Smoother1D::findEdgesToSmooth()
5612 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5613 for ( int iEnd = 0; iEnd < 2; ++iEnd )
5614 if ( leOnV[iEnd]->Is( _LayerEdge::NORMAL_UPDATED ))
5615 _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
5617 _eToSmooth[0].first = _eToSmooth[0].second = 0;
5619 for ( size_t i = 0; i < _eos.size(); ++i )
5621 if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5623 if ( needSmoothing( _leOnV[0]._cosin,
5624 _eos[i]->_len * leOnV[0]->_lenFactor, _curveLen * _leParams[i] ) ||
5627 _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5631 _eToSmooth[0].second = i+1;
5634 _eToSmooth[1].first = _eToSmooth[1].second = _eos.size();
5636 for ( int i = _eos.size() - 1; i >= _eToSmooth[0].second; --i )
5638 if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5640 if ( needSmoothing( _leOnV[1]._cosin,
5641 _eos[i]->_len * leOnV[1]->_lenFactor, _curveLen * ( 1.-_leParams[i] )) ||
5643 _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5647 _eToSmooth[1].first = i;
5651 //================================================================================
5653 * \brief Check if iE-th _LayerEdge needs smoothing
5655 //================================================================================
5657 bool _Smoother1D::isToSmooth( int iE )
5659 SMESH_NodeXYZ pi( _eos[iE]->_nodes[0] );
5660 SMESH_NodeXYZ p0( _eos[iE]->_2neibors->srcNode(0) );
5661 SMESH_NodeXYZ p1( _eos[iE]->_2neibors->srcNode(1) );
5662 gp_XYZ seg0 = pi - p0;
5663 gp_XYZ seg1 = p1 - pi;
5664 gp_XYZ tangent = seg0 + seg1;
5665 double tangentLen = tangent.Modulus();
5666 double segMinLen = Min( seg0.Modulus(), seg1.Modulus() );
5667 if ( tangentLen < std::numeric_limits<double>::min() )
5669 tangent /= tangentLen;
5671 for ( size_t i = 0; i < _eos[iE]->_neibors.size(); ++i )
5673 _LayerEdge* ne = _eos[iE]->_neibors[i];
5674 if ( !ne->Is( _LayerEdge::TO_SMOOTH ) ||
5675 ne->_nodes.size() < 2 ||
5676 ne->_nodes[0]->GetPosition()->GetDim() != 2 )
5678 gp_XYZ edgeVec = SMESH_NodeXYZ( ne->_nodes.back() ) - SMESH_NodeXYZ( ne->_nodes[0] );
5679 double proj = edgeVec * tangent;
5680 if ( needSmoothing( 1., proj, segMinLen ))
5686 //================================================================================
5688 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5690 //================================================================================
5692 bool _Smoother1D::smoothAnalyticEdge( _SolidData& data,
5693 Handle(ShapeAnalysis_Surface)& surface,
5694 const TopoDS_Face& F,
5695 SMESH_MesherHelper& helper)
5697 if ( !isAnalytic() ) return false;
5699 size_t iFrom = 0, iTo = _eos._edges.size();
5701 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5703 if ( F.IsNull() ) // 3D
5705 SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5706 SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5707 //const gp_XYZ lineDir = pSrc1 - pSrc0;
5708 //_LayerEdge* vLE0 = getLEdgeOnV( 0 );
5709 //_LayerEdge* vLE1 = getLEdgeOnV( 1 );
5710 // bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5711 // vLE0->Is( _LayerEdge::BLOCKED ) ||
5712 // vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5713 // vLE1->Is( _LayerEdge::BLOCKED ));
5714 for ( int iEnd = 0; iEnd < 2; ++iEnd )
5716 iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5717 if ( iFrom >= iTo ) continue;
5718 SMESH_TNodeXYZ p0( _eos[iFrom]->_2neibors->tgtNode(0) );
5719 SMESH_TNodeXYZ p1( _eos[iTo-1]->_2neibors->tgtNode(1) );
5720 double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5721 double param1 = _leParams[ iTo ];
5722 for ( size_t i = iFrom; i < iTo; ++i )
5724 _LayerEdge* edge = _eos[i];
5725 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5726 double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5727 gp_XYZ newPos = p0 * ( 1. - param ) + p1 * param;
5729 // if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5731 // gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5732 // double shift = ( lineDir * ( newPos - pSrc0 ) -
5733 // lineDir * ( curPos - pSrc0 ));
5734 // newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5736 if ( edge->Is( _LayerEdge::BLOCKED ))
5738 SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5739 double curThick = pSrc.SquareDistance( tgtNode );
5740 double newThink = ( pSrc - newPos ).SquareModulus();
5741 if ( newThink > curThick )
5744 edge->_pos.back() = newPos;
5745 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5746 dumpMove( tgtNode );
5752 _LayerEdge* eV0 = getLEdgeOnV( 0 );
5753 _LayerEdge* eV1 = getLEdgeOnV( 1 );
5754 gp_XY uvV0 = eV0->LastUV( F, *data.GetShapeEdges( eV0 ));
5755 gp_XY uvV1 = eV1->LastUV( F, *data.GetShapeEdges( eV1 ));
5756 if ( eV0->_nodes.back() == eV1->_nodes.back() ) // closed edge
5758 int iPeriodic = helper.GetPeriodicIndex();
5759 if ( iPeriodic == 1 || iPeriodic == 2 )
5761 uvV1.SetCoord( iPeriodic, helper.GetOtherParam( uvV1.Coord( iPeriodic )));
5762 if ( uvV0.Coord( iPeriodic ) > uvV1.Coord( iPeriodic ))
5763 std::swap( uvV0, uvV1 );
5766 for ( int iEnd = 0; iEnd < 2; ++iEnd )
5768 iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5769 if ( iFrom >= iTo ) continue;
5770 _LayerEdge* e0 = _eos[iFrom]->_2neibors->_edges[0];
5771 _LayerEdge* e1 = _eos[iTo-1]->_2neibors->_edges[1];
5772 gp_XY uv0 = ( e0 == eV0 ) ? uvV0 : e0->LastUV( F, _eos );
5773 gp_XY uv1 = ( e1 == eV1 ) ? uvV1 : e1->LastUV( F, _eos );
5774 double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5775 double param1 = _leParams[ iTo ];
5776 gp_XY rangeUV = uv1 - uv0;
5777 for ( size_t i = iFrom; i < iTo; ++i )
5779 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5780 double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5781 gp_XY newUV = uv0 + param * rangeUV;
5783 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5784 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
5785 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5786 dumpMove( tgtNode );
5788 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
5789 pos->SetUParameter( newUV.X() );
5790 pos->SetVParameter( newUV.Y() );
5792 gp_XYZ newUV0( newUV.X(), newUV.Y(), 0 );
5794 if ( !_eos[i]->Is( _LayerEdge::SMOOTHED ))
5796 _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5797 if ( _eos[i]->_pos.size() > 2 )
5799 // modify previous positions to make _LayerEdge less sharply bent
5800 vector<gp_XYZ>& uvVec = _eos[i]->_pos;
5801 const gp_XYZ uvShift = newUV0 - uvVec.back();
5802 const double len2 = ( uvVec.back() - uvVec[ 0 ] ).SquareModulus();
5803 int iPrev = uvVec.size() - 2;
5806 double r = ( uvVec[ iPrev ] - uvVec[0] ).SquareModulus() / len2;
5807 uvVec[ iPrev ] += uvShift * r;
5812 _eos[i]->_pos.back() = newUV0;
5819 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5821 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5822 gp_Pnt center3D = circle->Location();
5824 if ( F.IsNull() ) // 3D
5826 if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5827 return true; // closed EDGE - nothing to do
5829 // circle is a real curve of EDGE
5830 gp_Circ circ = circle->Circ();
5832 // new center is shifted along its axis
5833 const gp_Dir& axis = circ.Axis().Direction();
5834 _LayerEdge* e0 = getLEdgeOnV(0);
5835 _LayerEdge* e1 = getLEdgeOnV(1);
5836 SMESH_TNodeXYZ p0 = e0->_nodes.back();
5837 SMESH_TNodeXYZ p1 = e1->_nodes.back();
5838 double shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5839 double shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5840 gp_Pnt newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5842 double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5844 gp_Ax2 newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5845 gp_Circ newCirc( newAxis, newRadius );
5846 gp_Vec vecC1 ( newCenter, p1 );
5848 double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5852 for ( size_t i = 0; i < _eos.size(); ++i )
5854 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5855 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5856 double u = uLast * _leParams[i];
5857 gp_Pnt p = ElCLib::Value( u, newCirc );
5858 _eos._edges[i]->_pos.back() = p.XYZ();
5860 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5861 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5862 dumpMove( tgtNode );
5868 const gp_XY center( center3D.X(), center3D.Y() );
5870 _LayerEdge* e0 = getLEdgeOnV(0);
5871 _LayerEdge* eM = _eos._edges[ 0 ];
5872 _LayerEdge* e1 = getLEdgeOnV(1);
5873 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5874 gp_XY uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5875 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5876 gp_Vec2d vec0( center, uv0 );
5877 gp_Vec2d vecM( center, uvM );
5878 gp_Vec2d vec1( center, uv1 );
5879 double uLast = vec0.Angle( vec1 ); // -PI - +PI
5880 double uMidl = vec0.Angle( vecM );
5881 if ( uLast * uMidl <= 0. )
5882 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5883 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5885 gp_Ax2d axis( center, vec0 );
5886 gp_Circ2d circ( axis, radius );
5887 for ( size_t i = 0; i < _eos.size(); ++i )
5889 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5890 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5891 double newU = uLast * _leParams[i];
5892 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5893 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5895 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5896 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5897 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5898 dumpMove( tgtNode );
5900 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
5901 pos->SetUParameter( newUV.X() );
5902 pos->SetVParameter( newUV.Y() );
5904 _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5913 //================================================================================
5915 * \brief smooth _LayerEdge's on a an EDGE
5917 //================================================================================
5919 bool _Smoother1D::smoothComplexEdge( _SolidData& data,
5920 Handle(ShapeAnalysis_Surface)& surface,
5921 const TopoDS_Face& F,
5922 SMESH_MesherHelper& helper)
5924 if ( _offPoints.empty() )
5927 // ----------------------------------------------
5928 // move _offPoints along normals of _LayerEdge's
5929 // ----------------------------------------------
5931 _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5932 if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5933 _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5934 if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED ))
5935 _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5936 _leOnV[0]._len = e[0]->_len;
5937 _leOnV[1]._len = e[1]->_len;
5938 for ( size_t i = 0; i < _offPoints.size(); i++ )
5940 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
5941 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
5942 const double w0 = _offPoints[i]._2edges._wgt[0];
5943 const double w1 = _offPoints[i]._2edges._wgt[1];
5944 gp_XYZ avgNorm = ( e0->_normal * w0 + e1->_normal * w1 ).Normalized();
5945 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
5946 double avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5947 if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5948 e1->Is( _LayerEdge::NORMAL_UPDATED ))
5949 avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5951 _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5952 _offPoints[i]._len = avgLen;
5956 if ( !surface.IsNull() ) // project _offPoints to the FACE
5958 fTol = 100 * BRep_Tool::Tolerance( F );
5959 //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5961 gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5962 //if ( surface->Gap() < 0.5 * segLen )
5963 _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5965 for ( size_t i = 1; i < _offPoints.size(); ++i )
5967 uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5968 //if ( surface->Gap() < 0.5 * segLen )
5969 _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5973 // -----------------------------------------------------------------
5974 // project tgt nodes of extreme _LayerEdge's to the offset segments
5975 // -----------------------------------------------------------------
5977 const int updatedOrBlocked = _LayerEdge::NORMAL_UPDATED | _LayerEdge::BLOCKED;
5978 if ( e[0]->Is( updatedOrBlocked )) _iSeg[0] = 0;
5979 if ( e[1]->Is( updatedOrBlocked )) _iSeg[1] = _offPoints.size()-2;
5981 gp_Pnt pExtreme[2], pProj[2];
5982 bool isProjected[2];
5983 for ( int is2nd = 0; is2nd < 2; ++is2nd )
5985 pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5986 int i = _iSeg[ is2nd ];
5987 int di = is2nd ? -1 : +1;
5988 bool & projected = isProjected[ is2nd ];
5990 double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5993 gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ] );
5994 gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5995 uOnSeg = ( v0p * v01 ) / v01.SquareMagnitude(); // param [0,1] along v01
5996 projected = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5997 dist = pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5998 if ( dist < distMin || projected )
6001 pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
6004 else if ( dist > distPrev )
6006 if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
6012 while ( !projected &&
6013 i >= 0 && i+1 < (int)_offPoints.size() );
6017 if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
6020 _iSeg[1] = _offPoints.size()-2;
6021 debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
6026 if ( _iSeg[0] > _iSeg[1] )
6028 debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
6032 // adjust length of extreme LE (test viscous_layers_01/B7)
6033 gp_Vec vDiv0( pExtreme[0], pProj[0] );
6034 gp_Vec vDiv1( pExtreme[1], pProj[1] );
6035 double d0 = vDiv0.Magnitude();
6036 double d1 = isProjected[1] ? vDiv1.Magnitude() : 0;
6037 if ( e[0]->Is( _LayerEdge::BLOCKED )) {
6038 if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
6039 else e[0]->_len -= d0;
6041 if ( e[1]->Is( _LayerEdge::BLOCKED )) {
6042 if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
6043 else e[1]->_len -= d1;
6046 // ---------------------------------------------------------------------------------
6047 // compute normalized length of the offset segments located between the projections
6048 // ---------------------------------------------------------------------------------
6050 // temporary replace extreme _offPoints by pExtreme
6051 gp_XYZ opXYZ[2] = { _offPoints[ _iSeg[0] ]._xyz,
6052 _offPoints[ _iSeg[1]+1 ]._xyz };
6053 _offPoints[ _iSeg[0] ]._xyz = pExtreme[0].XYZ();
6054 _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
6056 size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
6057 vector< double > len( nbSeg + 1 );
6059 len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
6060 for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
6062 len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
6064 // if ( isProjected[ 1 ])
6065 // len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6067 // len[ nbSeg ] += pExtreme[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6069 double fullLen = len.back() - d0 - d1;
6070 for ( iSeg = 0; iSeg < len.size(); ++iSeg )
6071 len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
6073 // -------------------------------------------------------------
6074 // distribute tgt nodes of _LayerEdge's between the projections
6075 // -------------------------------------------------------------
6078 for ( size_t i = 0; i < _eos.size(); ++i )
6080 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6081 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6082 while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
6084 double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
6085 gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0] ]._xyz * ( 1 - r ) +
6086 _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
6088 if ( surface.IsNull() )
6090 _eos[i]->_pos.back() = p;
6092 else // project a new node position to a FACE
6094 gp_Pnt2d uv ( _eos[i]->_pos.back().X(), _eos[i]->_pos.back().Y() );
6095 gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
6097 p = surface->Value( uv2 ).XYZ();
6098 _eos[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
6100 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6101 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6102 dumpMove( tgtNode );
6105 _offPoints[ _iSeg[0] ]._xyz = opXYZ[0];
6106 _offPoints[ _iSeg[1]+1 ]._xyz = opXYZ[1];
6111 //================================================================================
6113 * \brief Prepare for smoothing
6115 //================================================================================
6117 void _Smoother1D::prepare(_SolidData& data)
6119 const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
6120 _curveLen = SMESH_Algo::EdgeLength( E );
6122 // sort _LayerEdge's by position on the EDGE
6123 data.SortOnEdge( E, _eos._edges );
6125 // compute normalized param of _eos._edges on EDGE
6126 _leParams.resize( _eos._edges.size() + 1 );
6129 gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
6131 for ( size_t i = 0; i < _eos._edges.size(); ++i )
6133 gp_Pnt p = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
6134 curLen = p.Distance( pPrev );
6135 _leParams[i+1] = _leParams[i] + curLen;
6138 double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
6139 for ( size_t i = 0; i < _leParams.size()-1; ++i )
6140 _leParams[i] = _leParams[i+1] / fullLen;
6141 _leParams.back() = 1.;
6144 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6146 // get cosin to use in findEdgesToSmooth()
6147 _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
6148 _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
6149 _leOnV[0]._cosin = Abs( leOnV[0]->_cosin );
6150 _leOnV[1]._cosin = Abs( leOnV[1]->_cosin );
6151 if ( _eos._sWOL.IsNull() ) // 3D
6152 for ( int iEnd = 0; iEnd < 2; ++iEnd )
6153 _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6158 // divide E to have offset segments with low deflection
6159 BRepAdaptor_Curve c3dAdaptor( E );
6160 const double curDeflect = 0.1; //0.01; // Curvature deflection == |p1p2]*sin(p1p2,p1pM)
6161 const double angDeflect = 0.1; //0.09; // Angular deflection == sin(p1pM,pMp2)
6162 GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
6163 if ( discret.NbPoints() <= 2 )
6165 _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
6169 const double u0 = c3dAdaptor.FirstParameter();
6170 gp_Pnt p; gp_Vec tangent;
6171 if ( discret.NbPoints() >= (int) _eos.size() + 2 )
6173 _offPoints.resize( discret.NbPoints() );
6174 for ( size_t i = 0; i < _offPoints.size(); i++ )
6176 double u = discret.Parameter( i+1 );
6177 c3dAdaptor.D1( u, p, tangent );
6178 _offPoints[i]._xyz = p.XYZ();
6179 _offPoints[i]._edgeDir = tangent.XYZ();
6180 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6185 std::vector< double > params( _eos.size() + 2 );
6187 params[0] = data.GetHelper().GetNodeU( E, leOnV[0]->_nodes[0] );
6188 params.back() = data.GetHelper().GetNodeU( E, leOnV[1]->_nodes[0] );
6189 for ( size_t i = 0; i < _eos.size(); i++ )
6190 params[i+1] = data.GetHelper().GetNodeU( E, _eos[i]->_nodes[0] );
6192 if ( params[1] > params[ _eos.size() ] )
6193 std::reverse( params.begin() + 1, params.end() - 1 );
6195 _offPoints.resize( _eos.size() + 2 );
6196 for ( size_t i = 0; i < _offPoints.size(); i++ )
6198 const double u = params[i];
6199 c3dAdaptor.D1( u, p, tangent );
6200 _offPoints[i]._xyz = p.XYZ();
6201 _offPoints[i]._edgeDir = tangent.XYZ();
6202 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6207 _offPoints [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
6208 _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
6209 _2NearEdges tmp2edges;
6210 tmp2edges._edges[1] = _eos._edges[0];
6211 _leOnV[0]._2neibors = & tmp2edges;
6212 _leOnV[0]._nodes = leOnV[0]->_nodes;
6213 _leOnV[1]._nodes = leOnV[1]->_nodes;
6214 _LayerEdge* eNext, *ePrev = & _leOnV[0];
6215 for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
6217 // find _LayerEdge's located before and after an offset point
6218 // (_eos._edges[ iLE ] is next after ePrev)
6219 while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
6220 ePrev = _eos._edges[ iLE++ ];
6221 eNext = ePrev->_2neibors->_edges[1];
6223 gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
6224 gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
6225 double r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
6226 _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
6229 // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
6230 for ( size_t i = 0; i < _offPoints.size(); i++ )
6231 if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
6232 _offPoints[i]._2edges._edges[0] = & _leOnV[0];
6234 for ( size_t i = _offPoints.size()-1; i > 0; i-- )
6235 if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
6236 _offPoints[i]._2edges._edges[1] = & _leOnV[1];
6239 // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
6241 int iLBO = _offPoints.size() - 2; // last but one
6243 if ( leOnV[ 0 ]->Is( _LayerEdge::MULTI_NORMAL ))
6244 _leOnV[ 0 ]._normal = getNormalNormal( _eos._edges[1]->_normal, _edgeDir[0] );
6246 _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
6247 if ( leOnV[ 1 ]->Is( _LayerEdge::MULTI_NORMAL ))
6248 _leOnV[ 1 ]._normal = getNormalNormal( _eos._edges.back()->_normal, _edgeDir[1] );
6250 _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
6251 _leOnV[ 0 ]._len = 0;
6252 _leOnV[ 1 ]._len = 0;
6253 _leOnV[ 0 ]._lenFactor = _offPoints[1 ]._2edges._edges[1]->_lenFactor;
6254 _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
6257 _iSeg[1] = _offPoints.size()-2;
6259 // initialize OffPnt::_len
6260 for ( size_t i = 0; i < _offPoints.size(); ++i )
6261 _offPoints[i]._len = 0;
6263 if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
6265 _leOnV[0]._len = leOnV[0]->_len;
6266 _leOnV[1]._len = leOnV[1]->_len;
6267 for ( size_t i = 0; i < _offPoints.size(); i++ )
6269 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
6270 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
6271 const double w0 = _offPoints[i]._2edges._wgt[0];
6272 const double w1 = _offPoints[i]._2edges._wgt[1];
6273 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
6274 gp_XYZ avgXYZ = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
6275 SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
6276 _offPoints[i]._xyz = avgXYZ;
6277 _offPoints[i]._len = avgLen;
6282 //================================================================================
6284 * \brief return _normal of _leOnV[is2nd] normal to the EDGE
6286 //================================================================================
6288 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
6289 const gp_XYZ& edgeDir)
6291 gp_XYZ cross = normal ^ edgeDir;
6292 gp_XYZ norm = edgeDir ^ cross;
6293 double size = norm.Modulus();
6295 // if ( size == 0 ) // MULTI_NORMAL _LayerEdge
6296 // return gp_XYZ( 1e-100, 1e-100, 1e-100 );
6301 //================================================================================
6303 * \brief Writes a script creating a mesh composed of _offPoints
6305 //================================================================================
6307 void _Smoother1D::offPointsToPython() const
6309 const char* fname = "/tmp/offPoints.py";
6310 cout << "execfile('"<<fname<<"')"<<endl;
6312 py << "import SMESH" << endl
6313 << "from salome.smesh import smeshBuilder" << endl
6314 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
6315 << "mesh = smesh.Mesh( 'offPoints' )"<<endl;
6316 for ( size_t i = 0; i < _offPoints.size(); i++ )
6318 py << "mesh.AddNode( "
6319 << _offPoints[i]._xyz.X() << ", "
6320 << _offPoints[i]._xyz.Y() << ", "
6321 << _offPoints[i]._xyz.Z() << " )" << endl;
6325 //================================================================================
6327 * \brief Sort _LayerEdge's by a parameter on a given EDGE
6329 //================================================================================
6331 void _SolidData::SortOnEdge( const TopoDS_Edge& E,
6332 vector< _LayerEdge* >& edges)
6334 map< double, _LayerEdge* > u2edge;
6335 for ( size_t i = 0; i < edges.size(); ++i )
6336 u2edge.insert( u2edge.end(),
6337 make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
6339 ASSERT( u2edge.size() == edges.size() );
6340 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
6341 for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
6342 edges[i] = u2e->second;
6344 Sort2NeiborsOnEdge( edges );
6347 //================================================================================
6349 * \brief Set _2neibors according to the order of _LayerEdge on EDGE
6351 //================================================================================
6353 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
6355 if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
6357 for ( size_t i = 0; i < edges.size()-1; ++i )
6358 if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
6359 edges[i]->_2neibors->reverse();
6361 const size_t iLast = edges.size() - 1;
6362 if ( edges.size() > 1 &&
6363 edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
6364 edges[iLast]->_2neibors->reverse();
6367 //================================================================================
6369 * \brief Return _EdgesOnShape* corresponding to the shape
6371 //================================================================================
6373 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6375 if ( shapeID < (int)_edgesOnShape.size() &&
6376 _edgesOnShape[ shapeID ]._shapeID == shapeID )
6377 return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6379 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6380 if ( _edgesOnShape[i]._shapeID == shapeID )
6381 return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6386 //================================================================================
6388 * \brief Return _EdgesOnShape* corresponding to the shape
6390 //================================================================================
6392 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6394 SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6395 return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6398 //================================================================================
6400 * \brief Prepare data of the _LayerEdge for smoothing on FACE
6402 //================================================================================
6404 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6406 SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6408 set< TGeomID > vertices;
6410 if ( eos->ShapeType() == TopAbs_FACE )
6412 // check FACE concavity and get concave VERTEXes
6413 F = TopoDS::Face( eos->_shape );
6414 if ( isConcave( F, helper, &vertices ))
6415 _concaveFaces.insert( eos->_shapeID );
6417 // set eos._eosConcaVer
6418 eos->_eosConcaVer.clear();
6419 eos->_eosConcaVer.reserve( vertices.size() );
6420 for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6422 _EdgesOnShape* eov = GetShapeEdges( *v );
6423 if ( eov && eov->_edges.size() == 1 )
6425 eos->_eosConcaVer.push_back( eov );
6426 for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6427 eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6431 // SetSmooLen() to _LayerEdge's on FACE
6432 // for ( size_t i = 0; i < eos->_edges.size(); ++i )
6434 // eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6436 // SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6437 // while ( smIt->more() ) // loop on sub-shapes of the FACE
6439 // _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6440 // if ( !eoe ) continue;
6442 // vector<_LayerEdge*>& eE = eoe->_edges;
6443 // for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6445 // if ( eE[iE]->_cosin <= theMinSmoothCosin )
6448 // SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6449 // while ( segIt->more() )
6451 // const SMDS_MeshElement* seg = segIt->next();
6452 // if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6454 // if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6455 // continue; // not to check a seg twice
6456 // for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6458 // _LayerEdge* eN = eE[iE]->_neibors[iN];
6459 // if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6461 // double dist = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6462 // double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6463 // eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6464 // eN->Set( _LayerEdge::NEAR_BOUNDARY );
6469 } // if ( eos->ShapeType() == TopAbs_FACE )
6471 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6473 eos->_edges[i]->_smooFunction = 0;
6474 eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6476 bool isCurved = false;
6477 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6479 _LayerEdge* edge = eos->_edges[i];
6481 // get simplices sorted
6482 _Simplex::SortSimplices( edge->_simplices );
6484 // smoothing function
6485 edge->ChooseSmooFunction( vertices, _n2eMap );
6488 double avgNormProj = 0, avgLen = 0;
6489 for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6491 _Simplex& s = edge->_simplices[iS];
6493 gp_XYZ vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6494 avgNormProj += edge->_normal * vec;
6495 avgLen += vec.Modulus();
6496 if ( substituteSrcNodes )
6498 s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6499 s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6502 avgNormProj /= edge->_simplices.size();
6503 avgLen /= edge->_simplices.size();
6504 if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6506 edge->Set( _LayerEdge::SMOOTHED_C1 );
6508 SMDS_FacePositionPtr fPos = edge->_nodes[0]->GetPosition();
6510 for ( size_t iS = 0; iS < edge->_simplices.size() && !fPos; ++iS )
6511 fPos = edge->_simplices[iS]._nPrev->GetPosition();
6513 edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6517 // prepare for putOnOffsetSurface()
6518 if (( eos->ShapeType() == TopAbs_FACE ) &&
6519 ( isCurved || !eos->_eosConcaVer.empty() ))
6521 eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6522 eos->_edgeForOffset = 0;
6524 double maxCosin = -1;
6525 for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6527 _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6528 if ( !eoe || eoe->_edges.empty() ) continue;
6530 vector<_LayerEdge*>& eE = eoe->_edges;
6531 _LayerEdge* e = eE[ eE.size() / 2 ];
6532 if ( e->_cosin > maxCosin )
6534 eos->_edgeForOffset = e;
6535 maxCosin = e->_cosin;
6541 //================================================================================
6543 * \brief Add faces for smoothing
6545 //================================================================================
6547 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6548 const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6550 set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6551 for ( ; eos != eosToSmooth.end(); ++eos )
6553 if ( !*eos || (*eos)->_toSmooth ) continue;
6555 (*eos)->_toSmooth = true;
6557 if ( (*eos)->ShapeType() == TopAbs_FACE )
6559 PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6560 (*eos)->_toSmooth = true;
6564 // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6565 if ( edgesNoAnaSmooth )
6566 for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6568 if ( (*eos)->_edgeSmoother )
6569 (*eos)->_edgeSmoother->_anaCurve.Nullify();
6573 //================================================================================
6575 * \brief Limit _LayerEdge::_maxLen according to local curvature
6577 //================================================================================
6579 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6581 // find intersection of neighbor _LayerEdge's to limit _maxLen
6582 // according to local curvature (IPAL52648)
6584 // This method must be called after findCollisionEdges() where _LayerEdge's
6585 // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6587 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6589 _EdgesOnShape& eosI = data._edgesOnShape[iS];
6590 if ( eosI._edges.empty() ) continue;
6591 if ( !eosI._hyp.ToSmooth() )
6593 for ( size_t i = 0; i < eosI._edges.size(); ++i )
6595 _LayerEdge* eI = eosI._edges[i];
6596 for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6598 _LayerEdge* eN = eI->_neibors[iN];
6599 if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6601 _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6602 limitMaxLenByCurvature( eI, eN, eosI, *eosN, eosI._hyp.ToSmooth() );
6607 else if ( eosI.ShapeType() == TopAbs_EDGE )
6609 const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6610 if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6612 _LayerEdge* e0 = eosI._edges[0];
6613 for ( size_t i = 1; i < eosI._edges.size(); ++i )
6615 _LayerEdge* eI = eosI._edges[i];
6616 limitMaxLenByCurvature( eI, e0, eosI, eosI, eosI._hyp.ToSmooth() );
6623 //================================================================================
6625 * \brief Limit _LayerEdge::_maxLen according to local curvature
6627 //================================================================================
6629 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge* e1,
6631 _EdgesOnShape& eos1,
6632 _EdgesOnShape& eos2,
6633 const bool isSmoothable )
6635 if (( e1->_nodes[0]->GetPosition()->GetDim() !=
6636 e2->_nodes[0]->GetPosition()->GetDim() ) &&
6637 ( e1->_cosin < 0.75 ))
6638 return; // angle > 90 deg at e1
6640 gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6641 double norSize = plnNorm.SquareModulus();
6642 if ( norSize < std::numeric_limits<double>::min() )
6643 return; // parallel normals
6645 // find closest points of skew _LayerEdge's
6646 SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6647 gp_XYZ dir12 = src2 - src1;
6648 gp_XYZ perp1 = e1->_normal ^ plnNorm;
6649 gp_XYZ perp2 = e2->_normal ^ plnNorm;
6650 double dot1 = perp2 * e1->_normal;
6651 double dot2 = perp1 * e2->_normal;
6652 double u1 = ( perp2 * dir12 ) / dot1;
6653 double u2 = - ( perp1 * dir12 ) / dot2;
6654 if ( u1 > 0 && u2 > 0 )
6656 double ovl = ( u1 * e1->_normal * dir12 -
6657 u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6658 if ( ovl > theSmoothThickToElemSizeRatio )
6660 const double coef = 0.75;
6661 e1->SetMaxLen( Min( e1->_maxLen, coef * u1 / e1->_lenFactor ));
6662 e2->SetMaxLen( Min( e2->_maxLen, coef * u2 / e2->_lenFactor ));
6667 //================================================================================
6669 * \brief Fill data._collisionEdges
6671 //================================================================================
6673 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6675 data._collisionEdges.clear();
6677 // set the full thickness of the layers to LEs
6678 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6680 _EdgesOnShape& eos = data._edgesOnShape[iS];
6681 if ( eos._edges.empty() ) continue;
6682 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6683 if ( !eos._sWOL.IsNull() ) continue; // PAL23566
6685 for ( size_t i = 0; i < eos._edges.size(); ++i )
6687 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6688 double maxLen = eos._edges[i]->_maxLen;
6689 eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6690 eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6691 eos._edges[i]->_maxLen = maxLen;
6695 // make temporary quadrangles got by extrusion of
6696 // mesh edges along _LayerEdge._normal's
6698 vector< const SMDS_MeshElement* > tmpFaces;
6700 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6702 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6703 if ( eos.ShapeType() != TopAbs_EDGE )
6705 if ( eos._edges.empty() )
6707 _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6708 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6709 while ( smIt->more() )
6710 if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6711 if ( eov->_edges.size() == 1 )
6712 edge[ bool( edge[0]) ] = eov->_edges[0];
6716 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6717 tmpFaces.push_back( f );
6720 for ( size_t i = 0; i < eos._edges.size(); ++i )
6722 _LayerEdge* edge = eos._edges[i];
6723 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6725 const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6726 if ( src2->GetPosition()->GetDim() > 0 &&
6727 src2->GetID() < edge->_nodes[0]->GetID() )
6728 continue; // avoid using same segment twice
6730 // a _LayerEdge containing tgt2
6731 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6733 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6734 tmpFaces.push_back( f );
6739 // Find _LayerEdge's intersecting tmpFaces.
6741 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6743 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6744 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6746 double dist1, dist2, segLen, eps = 0.5;
6747 _CollisionEdges collEdges;
6748 vector< const SMDS_MeshElement* > suspectFaces;
6749 const double angle45 = Cos( 45. * M_PI / 180. );
6751 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6753 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6754 if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6756 // find sub-shapes whose VL can influence VL on eos
6757 set< TGeomID > neighborShapes;
6758 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6759 while ( const TopoDS_Shape* face = fIt->next() )
6761 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6762 if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6764 SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6765 while ( subIt->more() )
6766 neighborShapes.insert( subIt->next()->GetId() );
6769 if ( eos.ShapeType() == TopAbs_VERTEX )
6771 PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6772 while ( const TopoDS_Shape* edge = eIt->next() )
6773 neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6775 // find intersecting _LayerEdge's
6776 for ( size_t i = 0; i < eos._edges.size(); ++i )
6778 if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6779 _LayerEdge* edge = eos._edges[i];
6780 gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6783 gp_Vec eSegDir0, eSegDir1;
6784 if ( edge->IsOnEdge() )
6786 SMESH_TNodeXYZ eP( edge->_nodes[0] );
6787 eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6788 eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6790 suspectFaces.clear();
6791 searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6792 SMDSAbs_Face, suspectFaces );
6793 collEdges._intEdges.clear();
6794 for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6796 const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6797 if ( f->_le1 == edge || f->_le2 == edge ) continue;
6798 if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6799 if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6800 if ( edge->IsOnEdge() ) {
6801 if ( edge->_2neibors->include( f->_le1 ) ||
6802 edge->_2neibors->include( f->_le2 )) continue;
6805 if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6806 ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge ))) continue;
6808 dist1 = dist2 = Precision::Infinite();
6809 if ( !edge->SegTriaInter( lastSegment, f->n(0), f->n(1), f->n(2), dist1, eps ))
6810 dist1 = Precision::Infinite();
6811 if ( !edge->SegTriaInter( lastSegment, f->n(3), f->n(2), f->n(0), dist2, eps ))
6812 dist2 = Precision::Infinite();
6813 if (( dist1 > segLen ) && ( dist2 > segLen ))
6816 if ( edge->IsOnEdge() )
6818 // skip perpendicular EDGEs
6819 gp_Vec fSegDir = SMESH_TNodeXYZ( f->n(0) ) - SMESH_TNodeXYZ( f->n(3) );
6820 bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6821 isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6822 isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6823 isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6828 // either limit inflation of edges or remember them for updating _normal
6829 // double dot = edge->_normal * f->GetDir();
6832 collEdges._intEdges.push_back( f->_le1 );
6833 collEdges._intEdges.push_back( f->_le2 );
6837 // double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6838 // edge->SetMaxLen( Min( shortLen, edge->_maxLen ));
6842 if ( !collEdges._intEdges.empty() )
6844 collEdges._edge = edge;
6845 data._collisionEdges.push_back( collEdges );
6850 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6853 // restore the zero thickness
6854 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6856 _EdgesOnShape& eos = data._edgesOnShape[iS];
6857 if ( eos._edges.empty() ) continue;
6858 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6860 for ( size_t i = 0; i < eos._edges.size(); ++i )
6862 eos._edges[i]->InvalidateStep( 1, eos );
6863 eos._edges[i]->_len = 0;
6868 //================================================================================
6870 * \brief Find _LayerEdge's located on boundary of a convex FACE whose normal
6871 * will be updated at each inflation step
6873 //================================================================================
6875 void _ViscousBuilder::findEdgesToUpdateNormalNearConvexFace( _ConvexFace & convFace,
6877 SMESH_MesherHelper& helper )
6879 const TGeomID convFaceID = getMeshDS()->ShapeToIndex( convFace._face );
6880 const double preci = BRep_Tool::Tolerance( convFace._face );
6881 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( convFace._face );
6883 bool edgesToUpdateFound = false;
6885 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6886 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6888 _EdgesOnShape& eos = * id2eos->second;
6889 if ( !eos._sWOL.IsNull() ) continue;
6890 if ( !eos._hyp.ToSmooth() ) continue;
6891 for ( size_t i = 0; i < eos._edges.size(); ++i )
6893 _LayerEdge* ledge = eos._edges[ i ];
6894 if ( ledge->Is( _LayerEdge::UPD_NORMAL_CONV )) continue; // already checked
6895 if ( ledge->Is( _LayerEdge::MULTI_NORMAL )) continue; // not inflatable
6897 gp_XYZ tgtPos = ( SMESH_NodeXYZ( ledge->_nodes[0] ) +
6898 ledge->_normal * ledge->_lenFactor * ledge->_maxLen );
6900 // the normal must be updated if distance from tgtPos to surface is less than
6903 // find an initial UV for search of a projection of tgtPos to surface
6904 const SMDS_MeshNode* nodeInFace = 0;
6905 SMDS_ElemIteratorPtr fIt = ledge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6906 while ( fIt->more() && !nodeInFace )
6908 const SMDS_MeshElement* f = fIt->next();
6909 if ( convFaceID != f->getshapeId() ) continue;
6911 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
6912 while ( nIt->more() && !nodeInFace )
6914 const SMDS_MeshElement* n = nIt->next();
6915 if ( n->getshapeId() == convFaceID )
6916 nodeInFace = static_cast< const SMDS_MeshNode* >( n );
6921 gp_XY uv = helper.GetNodeUV( convFace._face, nodeInFace );
6924 surface->NextValueOfUV( uv, tgtPos, preci );
6925 double dist = surface->Gap();
6926 if ( dist < 0.95 * ledge->_maxLen )
6928 ledge->Set( _LayerEdge::UPD_NORMAL_CONV );
6929 if ( !ledge->_curvature ) ledge->_curvature = new _Curvature;
6930 ledge->_curvature->_uv.SetCoord( uv.X(), uv.Y() );
6931 edgesToUpdateFound = true;
6936 if ( !convFace._isTooCurved && edgesToUpdateFound )
6938 data._convexFaces.insert( make_pair( convFaceID, convFace )).first->second;
6942 //================================================================================
6944 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6945 * _LayerEdge's on neighbor EDGE's
6947 //================================================================================
6949 bool _ViscousBuilder::updateNormals( _SolidData& data,
6950 SMESH_MesherHelper& helper,
6954 updateNormalsOfC1Vertices( data );
6956 if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6959 // map to store new _normal and _cosin for each intersected edge
6960 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp > edge2newEdge;
6961 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6962 _LayerEdge zeroEdge;
6963 zeroEdge._normal.SetCoord( 0,0,0 );
6964 zeroEdge._maxLen = Precision::Infinite();
6965 zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6967 set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6969 double segLen, dist1, dist2, dist;
6970 vector< pair< _LayerEdge*, double > > intEdgesDist;
6971 _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6973 for ( int iter = 0; iter < 5; ++iter )
6975 edge2newEdge.clear();
6977 for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6979 _CollisionEdges& ce = data._collisionEdges[iE];
6980 _LayerEdge* edge1 = ce._edge;
6981 if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6982 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6983 if ( !eos1 ) continue;
6985 // detect intersections
6986 gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6987 double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6989 intEdgesDist.clear();
6990 double minIntDist = Precision::Infinite();
6991 for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6993 if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6994 ce._intEdges[i ]->Is( _LayerEdge::BLOCKED ) &&
6995 ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6997 double dot = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6998 double fact = ( 1.1 + dot * dot );
6999 SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
7000 SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
7001 gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
7002 gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
7003 dist1 = dist2 = Precision::Infinite();
7004 if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1, dist1, eps ) &&
7005 !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
7008 if ( dist > testLen || dist <= 0 )
7011 if ( dist > testLen || dist <= 0 )
7014 // choose a closest edge
7015 gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
7016 double d1 = intP.SquareDistance( pSrc0 );
7017 double d2 = intP.SquareDistance( pSrc1 );
7018 int iClose = i + ( d2 < d1 );
7019 _LayerEdge* edge2 = ce._intEdges[iClose];
7020 edge2->Unset( _LayerEdge::MARKED );
7022 // choose a closest edge among neighbors
7023 gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
7024 d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
7025 for ( size_t j = 0; j < intEdgesDist.size(); ++j )
7027 _LayerEdge * edgeJ = intEdgesDist[j].first;
7028 if ( edge2->IsNeiborOnEdge( edgeJ ))
7030 d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
7031 ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
7034 intEdgesDist.push_back( make_pair( edge2, dist ));
7035 // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
7037 // iClose = i + !( d2 < d1 );
7038 // intEdges.push_back( ce._intEdges[iClose] );
7039 // ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
7041 minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
7046 // compute new _normals
7047 for ( size_t i = 0; i < intEdgesDist.size(); ++i )
7049 _LayerEdge* edge2 = intEdgesDist[i].first;
7050 double distWgt = edge1->_len / intEdgesDist[i].second;
7051 // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7052 // edge2->Is( _LayerEdge::BLOCKED )) continue;
7053 if ( edge2->Is( _LayerEdge::MARKED )) continue;
7054 edge2->Set( _LayerEdge::MARKED );
7057 gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
7059 double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7060 double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7061 double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7062 // double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7063 // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
7064 // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7065 // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7066 gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
7067 newNormal.Normalize();
7071 double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
7072 if ( cos1 < theMinSmoothCosin )
7074 newCos = cos2 * sgn1;
7076 else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
7078 newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
7082 newCos = edge1->_cosin;
7085 e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
7086 e2neIt->second._normal += distWgt * newNormal;
7087 e2neIt->second._cosin = newCos;
7088 e2neIt->second.SetMaxLen( 0.7 * minIntDist / edge1->_lenFactor );
7089 if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
7090 e2neIt->second._normal += dir2;
7092 e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
7093 e2neIt->second._normal += distWgt * newNormal;
7094 if ( Precision::IsInfinite( zeroEdge._maxLen ))
7096 e2neIt->second._cosin = edge2->_cosin;
7097 e2neIt->second.SetMaxLen( 1.3 * minIntDist / edge1->_lenFactor );
7099 if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
7100 e2neIt->second._normal += dir1;
7104 if ( edge2newEdge.empty() )
7105 break; //return true;
7107 dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
7109 // Update data of edges depending on a new _normal
7112 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7114 _LayerEdge* edge = e2neIt->first;
7115 _LayerEdge& newEdge = e2neIt->second;
7116 _EdgesOnShape* eos = data.GetShapeEdges( edge );
7117 if ( edge->Is( _LayerEdge::BLOCKED && newEdge._maxLen > edge->_len ))
7120 // Check if a new _normal is OK:
7121 newEdge._normal.Normalize();
7122 if ( !isNewNormalOk( data, *edge, newEdge._normal ))
7124 if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
7126 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7127 edge->SetMaxLen( newEdge._maxLen );
7128 edge->SetNewLength( newEdge._maxLen, *eos, helper );
7130 continue; // the new _normal is bad
7132 // the new _normal is OK
7134 // find shapes that need smoothing due to change of _normal
7135 if ( edge->_cosin < theMinSmoothCosin &&
7136 newEdge._cosin > theMinSmoothCosin )
7138 if ( eos->_sWOL.IsNull() )
7140 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7141 while ( fIt->more() )
7142 shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
7144 else // edge inflates along a FACE
7146 TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
7147 PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
7148 while ( const TopoDS_Shape* E = eIt->next() )
7150 gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
7151 double angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
7152 if ( angle < M_PI / 2 )
7153 shapesToSmooth.insert( data.GetShapeEdges( *E ));
7158 double len = edge->_len;
7159 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7160 edge->SetNormal( newEdge._normal );
7161 edge->SetCosin( newEdge._cosin );
7162 edge->SetNewLength( len, *eos, helper );
7163 edge->Set( _LayerEdge::MARKED );
7164 edge->Set( _LayerEdge::NORMAL_UPDATED );
7165 edgesNoAnaSmooth.insert( eos );
7168 // Update normals and other dependent data of not intersecting _LayerEdge's
7169 // neighboring the intersecting ones
7171 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7173 _LayerEdge* edge1 = e2neIt->first;
7174 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7175 if ( !edge1->Is( _LayerEdge::MARKED ))
7178 if ( edge1->IsOnEdge() )
7180 const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
7181 const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
7182 edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
7185 if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
7187 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
7189 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
7190 if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
7191 continue; // j-th neighbor is also intersected
7192 _LayerEdge* prevEdge = edge1;
7193 const int nbSteps = 10;
7194 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
7196 if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
7197 neighbor->Is( _LayerEdge::MARKED ))
7199 _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
7200 if ( !eos ) continue;
7201 _LayerEdge* nextEdge = neighbor;
7202 if ( neighbor->_2neibors )
7205 nextEdge = neighbor->_2neibors->_edges[iNext];
7206 if ( nextEdge == prevEdge )
7207 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
7209 double r = double(step-1)/nbSteps/(iter+1);
7210 if ( !nextEdge->_2neibors )
7213 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
7214 newNorm.Normalize();
7215 if ( !isNewNormalOk( data, *neighbor, newNorm ))
7218 double len = neighbor->_len;
7219 neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7220 neighbor->SetNormal( newNorm );
7221 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
7222 if ( neighbor->_2neibors )
7223 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
7224 neighbor->SetNewLength( len, *eos, helper );
7225 neighbor->Set( _LayerEdge::MARKED );
7226 neighbor->Set( _LayerEdge::NORMAL_UPDATED );
7227 edgesNoAnaSmooth.insert( eos );
7229 if ( !neighbor->_2neibors )
7230 break; // neighbor is on VERTEX
7232 // goto the next neighbor
7233 prevEdge = neighbor;
7234 neighbor = nextEdge;
7241 data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
7246 //================================================================================
7248 * \brief Check if a new normal is OK
7250 //================================================================================
7252 bool _ViscousBuilder::isNewNormalOk( _SolidData& data,
7254 const gp_XYZ& newNormal)
7256 // check a min angle between the newNormal and surrounding faces
7257 vector<_Simplex> simplices;
7258 SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
7259 _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
7260 double newMinDot = 1, curMinDot = 1;
7261 for ( size_t i = 0; i < simplices.size(); ++i )
7263 n1.Set( simplices[i]._nPrev );
7264 n2.Set( simplices[i]._nNext );
7265 gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
7266 double normLen2 = normFace.SquareModulus();
7267 if ( normLen2 < std::numeric_limits<double>::min() )
7269 normFace /= Sqrt( normLen2 );
7270 newMinDot = Min( newNormal * normFace, newMinDot );
7271 curMinDot = Min( edge._normal * normFace, curMinDot );
7274 if ( newMinDot < 0.5 )
7276 ok = ( newMinDot >= curMinDot * 0.9 );
7277 //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
7278 // double initMinDot2 = 1. - edge._cosin * edge._cosin;
7279 // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
7285 //================================================================================
7287 * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
7289 //================================================================================
7291 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData& data,
7292 SMESH_MesherHelper& helper,
7294 const double stepSize )
7296 if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
7297 return true; // no shapes needing smoothing
7299 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7301 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7302 if ( //!eos._toSmooth || _eosC1 have _toSmooth == false
7303 !eos._hyp.ToSmooth() ||
7304 eos.ShapeType() != TopAbs_FACE ||
7305 eos._edges.empty() )
7308 bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
7309 if ( !toSmooth ) continue;
7311 for ( size_t i = 0; i < eos._edges.size(); ++i )
7313 _LayerEdge* edge = eos._edges[i];
7314 if ( !edge->Is( _LayerEdge::SMOOTHED ))
7316 if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
7319 const gp_XYZ& pPrev = edge->PrevPos();
7320 const gp_XYZ& pLast = edge->_pos.back();
7321 gp_XYZ stepVec = pLast - pPrev;
7322 double realStepSize = stepVec.Modulus();
7323 if ( realStepSize < numeric_limits<double>::min() )
7326 edge->_lenFactor = realStepSize / stepSize;
7327 edge->_normal = stepVec / realStepSize;
7328 edge->Set( _LayerEdge::NORMAL_UPDATED );
7335 //================================================================================
7337 * \brief Modify normals of _LayerEdge's on C1 VERTEXes
7339 //================================================================================
7341 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
7343 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7345 _EdgesOnShape& eov = data._edgesOnShape[ iS ];
7346 if ( eov._eosC1.empty() ||
7347 eov.ShapeType() != TopAbs_VERTEX ||
7348 eov._edges.empty() )
7351 gp_XYZ newNorm = eov._edges[0]->_normal;
7352 double curThick = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
7353 bool normChanged = false;
7355 for ( size_t i = 0; i < eov._eosC1.size(); ++i )
7357 _EdgesOnShape* eoe = eov._eosC1[i];
7358 const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
7359 const double eLen = SMESH_Algo::EdgeLength( e );
7360 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
7361 if ( oppV.IsSame( eov._shape ))
7362 oppV = SMESH_MesherHelper::IthVertex( 1, e );
7363 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
7364 if ( !eovOpp || eovOpp->_edges.empty() ) continue;
7365 if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
7367 double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
7368 if ( curThickOpp + curThick < eLen )
7371 double wgt = 2. * curThick / eLen;
7372 newNorm += wgt * eovOpp->_edges[0]->_normal;
7377 eov._edges[0]->SetNormal( newNorm.Normalized() );
7378 eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
7383 //================================================================================
7385 * \brief Modify normals of _LayerEdge's on _ConvexFace's
7387 //================================================================================
7389 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData& data,
7390 SMESH_MesherHelper& helper,
7393 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
7396 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
7397 for ( ; id2face != data._convexFaces.end(); ++id2face )
7399 _ConvexFace & convFace = (*id2face).second;
7400 convFace._normalsFixedOnBorders = false; // to update at each inflation step
7402 if ( convFace._normalsFixed )
7403 continue; // already fixed
7404 if ( convFace.CheckPrisms() )
7405 continue; // nothing to fix
7407 convFace._normalsFixed = true;
7409 BRepAdaptor_Surface surface ( convFace._face, false );
7410 BRepLProp_SLProps surfProp( surface, 2, 1e-6 );
7412 // check if the convex FACE is of spherical shape
7414 Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
7418 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7419 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7421 _EdgesOnShape& eos = *(id2eos->second);
7422 if ( eos.ShapeType() == TopAbs_VERTEX )
7424 _LayerEdge* ledge = eos._edges[ 0 ];
7425 if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7426 centersBox.Add( center );
7428 for ( size_t i = 0; i < eos._edges.size(); ++i )
7429 nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
7431 if ( centersBox.IsVoid() )
7433 debugMsg( "Error: centersBox.IsVoid()" );
7436 const bool isSpherical =
7437 ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7439 int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
7440 vector < _CentralCurveOnEdge > centerCurves( nbEdges );
7444 // set _LayerEdge::_normal as average of all normals
7446 // WARNING: different density of nodes on EDGEs is not taken into account that
7447 // can lead to an improper new normal
7449 gp_XYZ avgNormal( 0,0,0 );
7451 id2eos = convFace._subIdToEOS.begin();
7452 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7454 _EdgesOnShape& eos = *(id2eos->second);
7455 // set data of _CentralCurveOnEdge
7456 if ( eos.ShapeType() == TopAbs_EDGE )
7458 _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
7459 ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
7460 if ( !eos._sWOL.IsNull() )
7461 ceCurve._adjFace.Nullify();
7463 ceCurve._ledges.insert( ceCurve._ledges.end(),
7464 eos._edges.begin(), eos._edges.end());
7466 // summarize normals
7467 for ( size_t i = 0; i < eos._edges.size(); ++i )
7468 avgNormal += eos._edges[ i ]->_normal;
7470 double normSize = avgNormal.SquareModulus();
7471 if ( normSize < 1e-200 )
7473 debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7476 avgNormal /= Sqrt( normSize );
7478 // compute new _LayerEdge::_cosin on EDGEs
7479 double avgCosin = 0;
7482 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7484 _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7485 if ( ceCurve._adjFace.IsNull() )
7487 for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7489 const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7490 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7493 double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7494 ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7495 avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7501 avgCosin /= nbCosin;
7503 // set _LayerEdge::_normal = avgNormal
7504 id2eos = convFace._subIdToEOS.begin();
7505 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7507 _EdgesOnShape& eos = *(id2eos->second);
7508 if ( eos.ShapeType() != TopAbs_EDGE )
7509 for ( size_t i = 0; i < eos._edges.size(); ++i )
7510 eos._edges[ i ]->_cosin = avgCosin;
7512 for ( size_t i = 0; i < eos._edges.size(); ++i )
7514 eos._edges[ i ]->SetNormal( avgNormal );
7515 eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7519 else // if ( isSpherical )
7521 // We suppose that centers of curvature at all points of the FACE
7522 // lie on some curve, let's call it "central curve". For all _LayerEdge's
7523 // having a common center of curvature we define the same new normal
7524 // as a sum of normals of _LayerEdge's on EDGEs among them.
7526 // get all centers of curvature for each EDGE
7528 helper.SetSubShape( convFace._face );
7529 _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7531 TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7532 for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7534 const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7536 // set adjacent FACE
7537 centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7539 // get _LayerEdge's of the EDGE
7540 TGeomID edgeID = meshDS->ShapeToIndex( edge );
7541 _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7542 if ( !eos || eos->_edges.empty() )
7544 // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7545 for ( int iV = 0; iV < 2; ++iV )
7547 TopoDS_Vertex v = helper.IthVertex( iV, edge );
7548 TGeomID vID = meshDS->ShapeToIndex( v );
7549 eos = data.GetShapeEdges( vID );
7550 vertexLEdges[ iV ] = eos->_edges[ 0 ];
7552 edgeLEdge = &vertexLEdges[0];
7553 edgeLEdgeEnd = edgeLEdge + 2;
7555 centerCurves[ iE ]._adjFace.Nullify();
7559 if ( ! eos->_toSmooth )
7560 data.SortOnEdge( edge, eos->_edges );
7561 edgeLEdge = &eos->_edges[ 0 ];
7562 edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7563 vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7564 vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7566 if ( ! eos->_sWOL.IsNull() )
7567 centerCurves[ iE ]._adjFace.Nullify();
7570 // Get curvature centers
7574 if ( edgeLEdge[0]->IsOnEdge() &&
7575 convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7577 centerCurves[ iE ].Append( center, vertexLEdges[0] );
7578 centersBox.Add( center );
7580 for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7581 if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7582 { // EDGE or VERTEXes
7583 centerCurves[ iE ].Append( center, *edgeLEdge );
7584 centersBox.Add( center );
7586 if ( edgeLEdge[-1]->IsOnEdge() &&
7587 convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7589 centerCurves[ iE ].Append( center, vertexLEdges[1] );
7590 centersBox.Add( center );
7592 centerCurves[ iE ]._isDegenerated =
7593 ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7595 } // loop on EDGES of convFace._face to set up data of centerCurves
7597 // Compute new normals for _LayerEdge's on EDGEs
7599 double avgCosin = 0;
7602 for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7604 _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7605 if ( ceCurve._isDegenerated )
7607 const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7608 vector< gp_XYZ > & newNormals = ceCurve._normals;
7609 for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7612 for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7615 isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7617 if ( isOK && !ceCurve._adjFace.IsNull() )
7619 // compute new _LayerEdge::_cosin
7620 const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7621 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7624 double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7625 ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7626 avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7632 // set new normals to _LayerEdge's of NOT degenerated central curves
7633 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7635 if ( centerCurves[ iE ]._isDegenerated )
7637 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7639 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7640 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7643 // set new normals to _LayerEdge's of degenerated central curves
7644 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7646 if ( !centerCurves[ iE ]._isDegenerated ||
7647 centerCurves[ iE ]._ledges.size() < 3 )
7649 // new normal is an average of new normals at VERTEXes that
7650 // was computed on non-degenerated _CentralCurveOnEdge's
7651 gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7652 centerCurves[ iE ]._ledges.back ()->_normal );
7653 double sz = newNorm.Modulus();
7657 double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7658 0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7659 for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7661 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7662 centerCurves[ iE ]._ledges[ iLE ]->_cosin = newCosin;
7663 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7667 // Find new normals for _LayerEdge's based on FACE
7670 avgCosin /= nbCosin;
7671 const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7672 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7673 if ( id2eos != convFace._subIdToEOS.end() )
7677 _EdgesOnShape& eos = * ( id2eos->second );
7678 for ( size_t i = 0; i < eos._edges.size(); ++i )
7680 _LayerEdge* ledge = eos._edges[ i ];
7681 if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7683 for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7685 iE = iE % centerCurves.size();
7686 if ( centerCurves[ iE ]._isDegenerated )
7688 newNorm.SetCoord( 0,0,0 );
7689 if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7691 ledge->SetNormal( newNorm );
7692 ledge->_cosin = avgCosin;
7693 ledge->Set( _LayerEdge::NORMAL_UPDATED );
7700 } // not a quasi-spherical FACE
7702 // Update _LayerEdge's data according to a new normal
7704 dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7705 <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7707 id2eos = convFace._subIdToEOS.begin();
7708 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7710 _EdgesOnShape& eos = * ( id2eos->second );
7711 for ( size_t i = 0; i < eos._edges.size(); ++i )
7713 _LayerEdge* & ledge = eos._edges[ i ];
7714 double len = ledge->_len;
7715 ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7716 ledge->SetCosin( ledge->_cosin );
7717 ledge->SetNewLength( len, eos, helper );
7719 if ( eos.ShapeType() != TopAbs_FACE )
7720 for ( size_t i = 0; i < eos._edges.size(); ++i )
7722 _LayerEdge* ledge = eos._edges[ i ];
7723 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7725 _LayerEdge* neibor = ledge->_neibors[iN];
7726 if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7728 neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7729 neibor->Set( _LayerEdge::MOVED );
7730 neibor->SetSmooLen( neibor->_len );
7734 } // loop on sub-shapes of convFace._face
7736 // Find FACEs adjacent to convFace._face that got necessity to smooth
7737 // as a result of normals modification
7739 set< _EdgesOnShape* > adjFacesToSmooth;
7740 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7742 if ( centerCurves[ iE ]._adjFace.IsNull() ||
7743 centerCurves[ iE ]._adjFaceToSmooth )
7745 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7747 if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7749 adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7754 data.AddShapesToSmooth( adjFacesToSmooth );
7759 } // loop on data._convexFaces
7764 //================================================================================
7766 * \brief Return max curvature of a FACE
7768 //================================================================================
7770 double _ConvexFace::GetMaxCurvature( _SolidData& data,
7772 BRepLProp_SLProps& surfProp,
7773 SMESH_MesherHelper& helper)
7775 double maxCurvature = 0;
7777 TopoDS_Face F = TopoDS::Face( eof._shape );
7779 const int nbTestPnt = 5;
7780 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7781 SMESH_subMeshIteratorPtr smIt = eof._subMesh->getDependsOnIterator(/*includeSelf=*/true);
7782 while ( smIt->more() )
7784 SMESH_subMesh* sm = smIt->next();
7785 const TGeomID subID = sm->GetId();
7787 // find _LayerEdge's of a sub-shape
7789 if (( eos = data.GetShapeEdges( subID )))
7790 this->_subIdToEOS.insert( make_pair( subID, eos ));
7794 // check concavity and curvature and limit data._stepSize
7795 const double minCurvature =
7796 1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
7797 size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
7798 for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
7800 gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
7801 surfProp.SetParameters( uv.X(), uv.Y() );
7802 if ( surfProp.IsCurvatureDefined() )
7804 double curvature = Max( surfProp.MaxCurvature() * oriFactor,
7805 surfProp.MinCurvature() * oriFactor );
7806 maxCurvature = Max( maxCurvature, curvature );
7808 if ( curvature > minCurvature )
7809 this->_isTooCurved = true;
7812 } // loop on sub-shapes of the FACE
7814 return maxCurvature;
7817 //================================================================================
7819 * \brief Finds a center of curvature of a surface at a _LayerEdge
7821 //================================================================================
7823 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge* ledge,
7824 BRepLProp_SLProps& surfProp,
7825 SMESH_MesherHelper& helper,
7826 gp_Pnt & center ) const
7828 gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7829 surfProp.SetParameters( uv.X(), uv.Y() );
7830 if ( !surfProp.IsCurvatureDefined() )
7833 const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7834 double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7835 double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7836 if ( surfCurvatureMin > surfCurvatureMax )
7837 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7839 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7844 //================================================================================
7846 * \brief Check that prisms are not distorted
7848 //================================================================================
7850 bool _ConvexFace::CheckPrisms() const
7853 for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7855 const _LayerEdge* edge = _simplexTestEdges[i];
7856 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7857 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7858 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7860 debugMsg( "Bad simplex of _simplexTestEdges ("
7861 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7862 << " "<< edge->_simplices[j]._nPrev->GetID()
7863 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7870 //================================================================================
7872 * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7873 * stored in this _CentralCurveOnEdge.
7874 * \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7875 * \param [in,out] newNormal - current normal at this point, to be redefined
7876 * \return bool - true if succeeded.
7878 //================================================================================
7880 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7882 if ( this->_isDegenerated )
7885 // find two centers the given one lies between
7887 for ( size_t i = 0, nb = _curvaCenters.size()-1; i < nb; ++i )
7889 double sl2 = 1.001 * _segLength2[ i ];
7891 double d1 = center.SquareDistance( _curvaCenters[ i ]);
7895 double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7896 if ( d2 > sl2 || d2 + d1 < 1e-100 )
7901 double r = d1 / ( d1 + d2 );
7902 gp_XYZ norm = (( 1. - r ) * _ledges[ i ]->_normal +
7903 ( r ) * _ledges[ i+1 ]->_normal );
7907 double sz = newNormal.Modulus();
7916 //================================================================================
7918 * \brief Set shape members
7920 //================================================================================
7922 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge& edge,
7923 const _ConvexFace& convFace,
7925 SMESH_MesherHelper& helper)
7929 PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7930 while ( const TopoDS_Shape* F = fIt->next())
7931 if ( !convFace._face.IsSame( *F ))
7933 _adjFace = TopoDS::Face( *F );
7934 _adjFaceToSmooth = false;
7935 // _adjFace already in a smoothing queue ?
7936 if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7937 _adjFaceToSmooth = eos->_toSmooth;
7942 //================================================================================
7944 * \brief Looks for intersection of it's last segment with faces
7945 * \param distance - returns shortest distance from the last node to intersection
7947 //================================================================================
7949 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
7951 const double& epsilon,
7953 const SMDS_MeshElement** intFace)
7955 vector< const SMDS_MeshElement* > suspectFaces;
7957 gp_Ax1 lastSegment = LastSegment( segLen, eos );
7958 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7960 bool segmentIntersected = false;
7961 distance = Precision::Infinite();
7962 int iFace = -1; // intersected face
7963 for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7965 const SMDS_MeshElement* face = suspectFaces[j];
7966 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7967 face->GetNodeIndex( _nodes[0] ) >= 0 )
7968 continue; // face sharing _LayerEdge node
7969 const int nbNodes = face->NbCornerNodes();
7970 bool intFound = false;
7972 SMDS_MeshElement::iterator nIt = face->begin_nodes();
7975 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7979 const SMDS_MeshNode* tria[3];
7982 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7985 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7991 if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7992 segmentIntersected = true;
7993 if ( distance > dist )
7994 distance = dist, iFace = j;
7997 if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
8001 if ( segmentIntersected )
8004 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
8005 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
8006 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
8007 << ", intersection with face ("
8008 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
8009 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
8010 << ") distance = " << distance << endl;
8014 return segmentIntersected;
8017 //================================================================================
8019 * \brief Returns a point used to check orientation of _simplices
8021 //================================================================================
8023 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
8025 size_t i = Is( NORMAL_UPDATED ) && IsOnFace() ? _pos.size()-2 : 0;
8027 if ( !eos || eos->_sWOL.IsNull() )
8030 if ( eos->SWOLType() == TopAbs_EDGE )
8032 return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
8034 //else // TopAbs_FACE
8036 return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
8039 //================================================================================
8041 * \brief Returns size and direction of the last segment
8043 //================================================================================
8045 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
8047 // find two non-coincident positions
8048 gp_XYZ orig = _pos.back();
8050 int iPrev = _pos.size() - 2;
8051 //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
8052 const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
8053 while ( iPrev >= 0 )
8055 vec = orig - _pos[iPrev];
8056 if ( vec.SquareModulus() > tol*tol )
8066 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
8067 segDir.SetDirection( _normal );
8072 gp_Pnt pPrev = _pos[ iPrev ];
8073 if ( !eos._sWOL.IsNull() )
8075 TopLoc_Location loc;
8076 if ( eos.SWOLType() == TopAbs_EDGE )
8079 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8080 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
8084 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
8085 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
8087 vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
8089 segDir.SetLocation( pPrev );
8090 segDir.SetDirection( vec );
8091 segLen = vec.Modulus();
8097 //================================================================================
8099 * \brief Return the last (or \a which) position of the target node on a FACE.
8100 * \param [in] F - the FACE this _LayerEdge is inflated along
8101 * \param [in] which - index of position
8102 * \return gp_XY - result UV
8104 //================================================================================
8106 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which ) const
8108 if ( F.IsSame( eos._sWOL )) // F is my FACE
8109 return gp_XY( _pos.back().X(), _pos.back().Y() );
8111 if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
8112 return gp_XY( 1e100, 1e100 );
8114 // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
8115 double f, l, u = _pos[ which < 0 ? _pos.size()-1 : which ].X();
8116 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
8117 if ( !C2d.IsNull() && f <= u && u <= l )
8118 return C2d->Value( u ).XY();
8120 return gp_XY( 1e100, 1e100 );
8123 //================================================================================
8125 * \brief Test intersection of the last segment with a given triangle
8126 * using Moller-Trumbore algorithm
8127 * Intersection is detected if distance to intersection is less than _LayerEdge._len
8129 //================================================================================
8131 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
8132 const gp_XYZ& vert0,
8133 const gp_XYZ& vert1,
8134 const gp_XYZ& vert2,
8136 const double& EPSILON) const
8138 const gp_Pnt& orig = lastSegment.Location();
8139 const gp_Dir& dir = lastSegment.Direction();
8141 /* calculate distance from vert0 to ray origin */
8142 //gp_XYZ tvec = orig.XYZ() - vert0;
8144 //if ( tvec * dir > EPSILON )
8145 // intersected face is at back side of the temporary face this _LayerEdge belongs to
8148 gp_XYZ edge1 = vert1 - vert0;
8149 gp_XYZ edge2 = vert2 - vert0;
8151 /* begin calculating determinant - also used to calculate U parameter */
8152 gp_XYZ pvec = dir.XYZ() ^ edge2;
8154 /* if determinant is near zero, ray lies in plane of triangle */
8155 double det = edge1 * pvec;
8157 const double ANGL_EPSILON = 1e-12;
8158 if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
8161 /* calculate distance from vert0 to ray origin */
8162 gp_XYZ tvec = orig.XYZ() - vert0;
8164 /* calculate U parameter and test bounds */
8165 double u = ( tvec * pvec ) / det;
8166 //if (u < 0.0 || u > 1.0)
8167 if ( u < -EPSILON || u > 1.0 + EPSILON )
8170 /* prepare to test V parameter */
8171 gp_XYZ qvec = tvec ^ edge1;
8173 /* calculate V parameter and test bounds */
8174 double v = (dir.XYZ() * qvec) / det;
8175 //if ( v < 0.0 || u + v > 1.0 )
8176 if ( v < -EPSILON || u + v > 1.0 + EPSILON )
8179 /* calculate t, ray intersects triangle */
8180 t = (edge2 * qvec) / det;
8186 //================================================================================
8188 * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
8189 * neighbor _LayerEdge's by it's own inflation vector.
8190 * \param [in] eov - EOS of the VERTEX
8191 * \param [in] eos - EOS of the FACE
8192 * \param [in] step - inflation step
8193 * \param [in,out] badSmooEdges - tangled _LayerEdge's
8195 //================================================================================
8197 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape* eov,
8198 const _EdgesOnShape* eos,
8200 vector< _LayerEdge* > & badSmooEdges )
8202 // check if any of _neibors is in badSmooEdges
8203 if ( std::find_first_of( _neibors.begin(), _neibors.end(),
8204 badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
8207 // get all edges to move
8209 set< _LayerEdge* > edges;
8211 // find a distance between _LayerEdge on VERTEX and its neighbors
8212 gp_XYZ curPosV = SMESH_TNodeXYZ( _nodes.back() );
8214 for ( size_t i = 0; i < _neibors.size(); ++i )
8216 _LayerEdge* nEdge = _neibors[i];
8217 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
8219 edges.insert( nEdge );
8220 dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
8223 // add _LayerEdge's close to curPosV
8227 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8229 _LayerEdge* edgeF = *e;
8230 for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
8232 _LayerEdge* nEdge = edgeF->_neibors[i];
8233 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
8234 dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
8235 edges.insert( nEdge );
8239 while ( nbE < edges.size() );
8241 // move the target node of the got edges
8243 gp_XYZ prevPosV = PrevPos();
8244 if ( eov->SWOLType() == TopAbs_EDGE )
8246 BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
8247 prevPosV = curve.Value( prevPosV.X() ).XYZ();
8249 else if ( eov->SWOLType() == TopAbs_FACE )
8251 BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
8252 prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
8255 SMDS_FacePositionPtr fPos;
8256 //double r = 1. - Min( 0.9, step / 10. );
8257 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8259 _LayerEdge* edgeF = *e;
8260 const gp_XYZ prevVF = edgeF->PrevPos() - prevPosV;
8261 const gp_XYZ newPosF = curPosV + prevVF;
8262 SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8263 tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
8264 edgeF->_pos.back() = newPosF;
8265 dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
8267 // set _curvature to make edgeF updated by putOnOffsetSurface()
8268 if ( !edgeF->_curvature )
8269 if (( fPos = edgeF->_nodes[0]->GetPosition() ))
8271 edgeF->_curvature = new _Curvature;
8272 edgeF->_curvature->_r = 0;
8273 edgeF->_curvature->_k = 0;
8274 edgeF->_curvature->_h2lenRatio = 0;
8275 edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
8278 // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
8279 // SMESH_TNodeXYZ( _nodes[0] ));
8280 // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8282 // _LayerEdge* edgeF = *e;
8283 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8284 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8285 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8286 // edgeF->_pos.back() = newPosF;
8287 // dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
8290 // smooth _LayerEdge's around moved nodes
8291 //size_t nbBadBefore = badSmooEdges.size();
8292 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8294 _LayerEdge* edgeF = *e;
8295 for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
8296 if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
8297 //&& !edges.count( edgeF->_neibors[j] ))
8299 _LayerEdge* edgeFN = edgeF->_neibors[j];
8300 edgeFN->Unset( SMOOTHED );
8301 int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
8304 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
8305 // const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
8306 // int nbBadAfter = edgeFN->_simplices.size();
8308 // for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
8310 // nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
8312 // if ( nbBadAfter <= nbBad )
8314 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
8315 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8316 // edgeF->_pos.back() = newPosF;
8317 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8318 // nbBad = nbBadAfter;
8322 badSmooEdges.push_back( edgeFN );
8325 // move a bit not smoothed around moved nodes
8326 // for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
8328 // _LayerEdge* edgeF = badSmooEdges[i];
8329 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8330 // gp_XYZ newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8331 // gp_XYZ newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
8332 // tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
8333 // edgeF->_pos.back() = newPosF;
8334 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8338 //================================================================================
8340 * \brief Perform smooth of _LayerEdge's based on EDGE's
8341 * \retval bool - true if node has been moved
8343 //================================================================================
8345 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
8346 const TopoDS_Face& F,
8347 SMESH_MesherHelper& helper)
8349 ASSERT( IsOnEdge() );
8351 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
8352 SMESH_TNodeXYZ oldPos( tgtNode );
8353 double dist01, distNewOld;
8355 SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
8356 SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
8357 dist01 = p0.Distance( _2neibors->tgtNode(1) );
8359 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
8360 double lenDelta = 0;
8363 //lenDelta = _curvature->lenDelta( _len );
8364 lenDelta = _curvature->lenDeltaByDist( dist01 );
8365 newPos.ChangeCoord() += _normal * lenDelta;
8368 distNewOld = newPos.Distance( oldPos );
8372 if ( _2neibors->_plnNorm )
8374 // put newPos on the plane defined by source node and _plnNorm
8375 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
8376 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
8377 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
8379 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8380 _pos.back() = newPos.XYZ();
8384 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8385 gp_XY uv( Precision::Infinite(), 0 );
8386 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
8387 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8389 newPos = surface->Value( uv );
8390 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8393 // commented for IPAL0052478
8394 // if ( _curvature && lenDelta < 0 )
8396 // gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
8397 // _len -= prevPos.Distance( oldPos );
8398 // _len += prevPos.Distance( newPos );
8400 bool moved = distNewOld > dist01/50;
8402 dumpMove( tgtNode ); // debug
8407 //================================================================================
8409 * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
8411 //================================================================================
8413 void _LayerEdge::SmoothWoCheck()
8415 if ( Is( DIFFICULT ))
8418 bool moved = Is( SMOOTHED );
8419 for ( size_t i = 0; i < _neibors.size() && !moved; ++i )
8420 moved = _neibors[i]->Is( SMOOTHED );
8424 gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8426 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8427 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8428 _pos.back() = newPos;
8430 dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
8433 //================================================================================
8435 * \brief Checks validity of _neibors on EDGEs and VERTEXes
8437 //================================================================================
8439 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
8441 if ( ! Is( NEAR_BOUNDARY ))
8446 for ( size_t iN = 0; iN < _neibors.size(); ++iN )
8448 _LayerEdge* eN = _neibors[iN];
8449 if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
8452 *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
8453 eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
8454 eN->_pos.size() != _pos.size() );
8456 SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
8457 SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
8458 for ( size_t i = 0; i < eN->_simplices.size(); ++i )
8459 if ( eN->_nodes.size() > 1 &&
8460 eN->_simplices[i].Includes( _nodes.back() ) &&
8461 !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
8466 badNeibors->push_back( eN );
8467 debugMsg("Bad boundary simplex ( "
8468 << " "<< eN->_nodes[0]->GetID()
8469 << " "<< eN->_nodes.back()->GetID()
8470 << " "<< eN->_simplices[i]._nPrev->GetID()
8471 << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
8482 //================================================================================
8484 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8485 * \retval int - nb of bad simplices around this _LayerEdge
8487 //================================================================================
8489 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
8491 if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
8492 return 0; // shape of simplices not changed
8493 if ( _simplices.size() < 2 )
8494 return 0; // _LayerEdge inflated along EDGE or FACE
8496 if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
8499 const gp_XYZ& curPos = _pos.back();
8500 const gp_XYZ& prevPos = _pos[0]; //PrevPos();
8502 // quality metrics (orientation) of tetras around _tgtNode
8504 double vol, minVolBefore = 1e100;
8505 for ( size_t i = 0; i < _simplices.size(); ++i )
8507 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8508 minVolBefore = Min( minVolBefore, vol );
8510 int nbBad = _simplices.size() - nbOkBefore;
8512 bool bndNeedSmooth = false;
8514 nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
8518 // evaluate min angle
8519 if ( nbBad == 0 && !findBest && !bndNeedSmooth )
8521 size_t nbGoodAngles = _simplices.size();
8523 for ( size_t i = 0; i < _simplices.size(); ++i )
8525 if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
8528 if ( nbGoodAngles == _simplices.size() )
8534 if ( Is( ON_CONCAVE_FACE ))
8537 if ( step % 2 == 0 )
8540 if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8542 if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8543 _smooFunction = _funs[ FUN_CENTROIDAL ];
8545 _smooFunction = _funs[ FUN_LAPLACIAN ];
8548 // compute new position for the last _pos using different _funs
8551 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8554 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8555 else if ( _funs[ iFun ] == _smooFunction )
8556 continue; // _smooFunction again
8557 else if ( step > 1 )
8558 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8560 break; // let "easy" functions improve elements around distorted ones
8564 double delta = _curvature->lenDelta( _len );
8566 newPos += _normal * delta;
8569 double segLen = _normal * ( newPos - prevPos );
8570 if ( segLen + delta > 0 )
8571 newPos += _normal * delta;
8573 // double segLenChange = _normal * ( curPos - newPos );
8574 // newPos += 0.5 * _normal * segLenChange;
8578 double minVolAfter = 1e100;
8579 for ( size_t i = 0; i < _simplices.size(); ++i )
8581 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8582 minVolAfter = Min( minVolAfter, vol );
8585 if ( nbOkAfter < nbOkBefore )
8589 ( nbOkAfter == nbOkBefore ) &&
8590 ( minVolAfter <= minVolBefore ))
8593 nbBad = _simplices.size() - nbOkAfter;
8594 minVolBefore = minVolAfter;
8595 nbOkBefore = nbOkAfter;
8598 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8599 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8600 _pos.back() = newPos;
8602 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8603 << (nbBad ? " --BAD" : ""));
8607 continue; // look for a better function
8613 } // loop on smoothing functions
8615 if ( moved ) // notify _neibors
8618 for ( size_t i = 0; i < _neibors.size(); ++i )
8619 if ( !_neibors[i]->Is( MOVED ))
8621 _neibors[i]->Set( MOVED );
8622 toSmooth.push_back( _neibors[i] );
8629 //================================================================================
8631 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8632 * \retval int - nb of bad simplices around this _LayerEdge
8634 //================================================================================
8636 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8638 if ( !_smooFunction )
8639 return 0; // _LayerEdge inflated along EDGE or FACE
8641 return 0; // not inflated
8643 const gp_XYZ& curPos = _pos.back();
8644 const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8646 // quality metrics (orientation) of tetras around _tgtNode
8648 double vol, minVolBefore = 1e100;
8649 for ( size_t i = 0; i < _simplices.size(); ++i )
8651 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8652 minVolBefore = Min( minVolBefore, vol );
8654 int nbBad = _simplices.size() - nbOkBefore;
8656 if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8658 if ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8659 _smooFunction = _funs[ FUN_LAPLACIAN ];
8660 else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8661 _smooFunction = _funs[ FUN_CENTROIDAL ];
8664 // compute new position for the last _pos using different _funs
8666 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8669 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8670 else if ( _funs[ iFun ] == _smooFunction )
8671 continue; // _smooFunction again
8672 else if ( step > 1 )
8673 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8675 break; // let "easy" functions improve elements around distorted ones
8679 double delta = _curvature->lenDelta( _len );
8681 newPos += _normal * delta;
8684 double segLen = _normal * ( newPos - prevPos );
8685 if ( segLen + delta > 0 )
8686 newPos += _normal * delta;
8688 // double segLenChange = _normal * ( curPos - newPos );
8689 // newPos += 0.5 * _normal * segLenChange;
8693 double minVolAfter = 1e100;
8694 for ( size_t i = 0; i < _simplices.size(); ++i )
8696 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8697 minVolAfter = Min( minVolAfter, vol );
8700 if ( nbOkAfter < nbOkBefore )
8702 if (( isConcaveFace || findBest ) &&
8703 ( nbOkAfter == nbOkBefore ) &&
8704 ( minVolAfter <= minVolBefore )
8708 nbBad = _simplices.size() - nbOkAfter;
8709 minVolBefore = minVolAfter;
8710 nbOkBefore = nbOkAfter;
8712 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8713 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8714 _pos.back() = newPos;
8716 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8717 << ( nbBad ? "--BAD" : ""));
8719 // commented for IPAL0052478
8720 // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8721 // _len += prevPos.Distance(newPos);
8723 if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8725 //_smooFunction = _funs[ iFun ];
8726 // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8727 // << "\t nbBad: " << _simplices.size() - nbOkAfter
8728 // << " minVol: " << minVolAfter
8729 // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8731 continue; // look for a better function
8737 } // loop on smoothing functions
8742 //================================================================================
8744 * \brief Chooses a smoothing technique giving a position most close to an initial one.
8745 * For a correct result, _simplices must contain nodes lying on geometry.
8747 //================================================================================
8749 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8750 const TNode2Edge& n2eMap)
8752 if ( _smooFunction ) return;
8754 // use smoothNefPolygon() near concaveVertices
8755 if ( !concaveVertices.empty() )
8757 _smooFunction = _funs[ FUN_CENTROIDAL ];
8759 Set( ON_CONCAVE_FACE );
8761 for ( size_t i = 0; i < _simplices.size(); ++i )
8763 if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8765 _smooFunction = _funs[ FUN_NEFPOLY ];
8767 // set FUN_CENTROIDAL to neighbor edges
8768 for ( i = 0; i < _neibors.size(); ++i )
8770 if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8772 _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8779 // // this choice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8780 // // where the nodes are smoothed too far along a sphere thus creating
8781 // // inverted _simplices
8782 // double dist[theNbSmooFuns];
8783 // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8784 // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8786 // double minDist = Precision::Infinite();
8787 // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8788 // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8790 // gp_Pnt newP = (this->*_funs[i])();
8791 // dist[i] = p.SquareDistance( newP );
8792 // if ( dist[i]*coef[i] < minDist )
8794 // _smooFunction = _funs[i];
8795 // minDist = dist[i]*coef[i];
8801 _smooFunction = _funs[ FUN_LAPLACIAN ];
8804 // for ( size_t i = 0; i < _simplices.size(); ++i )
8805 // minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8806 // if ( minDim == 0 )
8807 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8808 // else if ( minDim == 1 )
8809 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8813 // for ( int i = 0; i < FUN_NB; ++i )
8815 // //cout << dist[i] << " ";
8816 // if ( _smooFunction == _funs[i] ) {
8818 // //debugMsg( fNames[i] );
8822 // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8825 //================================================================================
8827 * \brief Returns a name of _SmooFunction
8829 //================================================================================
8831 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8834 fun = _smooFunction;
8835 for ( int i = 0; i < theNbSmooFuns; ++i )
8836 if ( fun == _funs[i] )
8839 return theNbSmooFuns;
8842 //================================================================================
8844 * \brief Computes a new node position using Laplacian smoothing
8846 //================================================================================
8848 gp_XYZ _LayerEdge::smoothLaplacian()
8850 gp_XYZ newPos (0,0,0);
8851 for ( size_t i = 0; i < _simplices.size(); ++i )
8852 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8853 newPos /= _simplices.size();
8858 //================================================================================
8860 * \brief Computes a new node position using angular-based smoothing
8862 //================================================================================
8864 gp_XYZ _LayerEdge::smoothAngular()
8866 vector< gp_Vec > edgeDir; edgeDir. reserve( _simplices.size() + 1 );
8867 vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
8868 vector< gp_XYZ > points; points. reserve( _simplices.size() + 1 );
8870 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8872 for ( size_t i = 0; i < _simplices.size(); ++i )
8874 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8875 edgeDir.push_back( p - pPrev );
8876 edgeSize.push_back( edgeDir.back().Magnitude() );
8877 if ( edgeSize.back() < numeric_limits<double>::min() )
8880 edgeSize.pop_back();
8884 edgeDir.back() /= edgeSize.back();
8885 points.push_back( p );
8890 edgeDir.push_back ( edgeDir[0] );
8891 edgeSize.push_back( edgeSize[0] );
8892 pN /= points.size();
8894 gp_XYZ newPos(0,0,0);
8896 for ( size_t i = 0; i < points.size(); ++i )
8898 gp_Vec toN = pN - points[i];
8899 double toNLen = toN.Magnitude();
8900 if ( toNLen < numeric_limits<double>::min() )
8905 gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
8906 double bisecLen = bisec.SquareMagnitude();
8907 if ( bisecLen < numeric_limits<double>::min() )
8909 gp_Vec norm = edgeDir[i] ^ toN;
8910 bisec = norm ^ edgeDir[i];
8911 bisecLen = bisec.SquareMagnitude();
8913 bisecLen = Sqrt( bisecLen );
8917 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8918 sumSize += bisecLen;
8920 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8921 sumSize += ( edgeSize[i] + edgeSize[i+1] );
8927 // project newPos to an average plane
8929 gp_XYZ norm(0,0,0); // plane normal
8930 points.push_back( points[0] );
8931 for ( size_t i = 1; i < points.size(); ++i )
8933 gp_XYZ vec1 = points[ i-1 ] - pN;
8934 gp_XYZ vec2 = points[ i ] - pN;
8935 gp_XYZ cross = vec1 ^ vec2;
8938 if ( cross * norm < numeric_limits<double>::min() )
8939 norm += cross.Reversed();
8943 catch (Standard_Failure) { // if |cross| == 0.
8946 gp_XYZ vec = newPos - pN;
8947 double r = ( norm * vec ) / norm.SquareModulus(); // param [0,1] on norm
8948 newPos = newPos - r * norm;
8953 //================================================================================
8955 * \brief Computes a new node position using weigthed node positions
8957 //================================================================================
8959 gp_XYZ _LayerEdge::smoothLengthWeighted()
8961 vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8962 vector< gp_XYZ > points; points. reserve( _simplices.size() );
8964 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8965 for ( size_t i = 0; i < _simplices.size(); ++i )
8967 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8968 edgeSize.push_back( ( p - pPrev ).Modulus() );
8969 if ( edgeSize.back() < numeric_limits<double>::min() )
8971 edgeSize.pop_back();
8975 points.push_back( p );
8979 edgeSize.push_back( edgeSize[0] );
8981 gp_XYZ newPos(0,0,0);
8983 for ( size_t i = 0; i < points.size(); ++i )
8985 newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8986 sumSize += edgeSize[i] + edgeSize[i+1];
8992 //================================================================================
8994 * \brief Computes a new node position using angular-based smoothing
8996 //================================================================================
8998 gp_XYZ _LayerEdge::smoothCentroidal()
9000 gp_XYZ newPos(0,0,0);
9001 gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
9003 for ( size_t i = 0; i < _simplices.size(); ++i )
9005 gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9006 gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
9007 gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
9008 double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
9011 newPos += gc * size;
9018 //================================================================================
9020 * \brief Computes a new node position located inside a Nef polygon
9022 //================================================================================
9024 gp_XYZ _LayerEdge::smoothNefPolygon()
9025 #ifdef OLD_NEF_POLYGON
9027 gp_XYZ newPos(0,0,0);
9029 // get a plane to search a solution on
9031 vector< gp_XYZ > vecs( _simplices.size() + 1 );
9033 const double tol = numeric_limits<double>::min();
9034 gp_XYZ center(0,0,0);
9035 for ( i = 0; i < _simplices.size(); ++i )
9037 vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
9038 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
9039 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9041 vecs.back() = vecs[0];
9042 center /= _simplices.size();
9044 gp_XYZ zAxis(0,0,0);
9045 for ( i = 0; i < _simplices.size(); ++i )
9046 zAxis += vecs[i] ^ vecs[i+1];
9049 for ( i = 0; i < _simplices.size(); ++i )
9052 if ( yAxis.SquareModulus() > tol )
9055 gp_XYZ xAxis = yAxis ^ zAxis;
9056 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9057 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9058 // p0.Distance( _simplices[2]._nPrev ));
9059 // gp_XYZ center = smoothLaplacian();
9060 // gp_XYZ xAxis, yAxis, zAxis;
9061 // for ( i = 0; i < _simplices.size(); ++i )
9063 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9064 // if ( xAxis.SquareModulus() > tol*tol )
9067 // for ( i = 1; i < _simplices.size(); ++i )
9069 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9070 // zAxis = xAxis ^ yAxis;
9071 // if ( zAxis.SquareModulus() > tol*tol )
9074 // if ( i == _simplices.size() ) return newPos;
9076 yAxis = zAxis ^ xAxis;
9077 xAxis /= xAxis.Modulus();
9078 yAxis /= yAxis.Modulus();
9080 // get half-planes of _simplices
9082 vector< _halfPlane > halfPlns( _simplices.size() );
9084 for ( size_t i = 0; i < _simplices.size(); ++i )
9086 gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9087 gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
9088 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
9089 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
9090 gp_XY vec12 = p2 - p1;
9091 double dist12 = vec12.Modulus();
9095 halfPlns[ nbHP ]._pos = p1;
9096 halfPlns[ nbHP ]._dir = vec12;
9097 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9101 // intersect boundaries of half-planes, define state of intersection points
9102 // in relation to all half-planes and calculate internal point of a 2D polygon
9105 gp_XY newPos2D (0,0);
9107 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9108 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9109 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9111 vector< vector< TIntPntState > > allIntPnts( nbHP );
9112 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9114 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9115 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9117 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9118 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9121 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9123 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9125 if ( iHP1 == iHP2 ) continue;
9127 TIntPntState & ips1 = intPnts1[ iHP2 ];
9128 if ( ips1.second == UNDEF )
9130 // find an intersection point of boundaries of iHP1 and iHP2
9132 if ( iHP2 == iPrev ) // intersection with neighbors is known
9133 ips1.first = halfPlns[ iHP1 ]._pos;
9134 else if ( iHP2 == iNext )
9135 ips1.first = halfPlns[ iHP2 ]._pos;
9136 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9137 ips1.second = NO_INT;
9139 // classify the found intersection point
9140 if ( ips1.second != NO_INT )
9142 ips1.second = NOT_OUT;
9143 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9144 if ( i != iHP1 && i != iHP2 &&
9145 halfPlns[ i ].IsOut( ips1.first, tol ))
9146 ips1.second = IS_OUT;
9148 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9149 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9150 TIntPntState & ips2 = intPnts2[ iHP1 ];
9153 if ( ips1.second == NOT_OUT )
9156 segEnds[ bool(segEnds[0]) ] = & ips1.first;
9160 // find a NOT_OUT segment of boundary which is located between
9161 // two NOT_OUT int points
9164 continue; // no such a segment
9168 // sort points along the boundary
9169 map< double, TIntPntState* > ipsByParam;
9170 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9172 TIntPntState & ips1 = intPnts1[ iHP2 ];
9173 if ( ips1.second != NO_INT )
9175 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
9176 double param = op * halfPlns[ iHP1 ]._dir;
9177 ipsByParam.insert( make_pair( param, & ips1 ));
9180 // look for two neighboring NOT_OUT points
9182 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9183 for ( ; u2ips != ipsByParam.end(); ++u2ips )
9185 TIntPntState & ips1 = *(u2ips->second);
9186 if ( ips1.second == NOT_OUT )
9187 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9188 else if ( nbNotOut >= 2 )
9195 if ( nbNotOut >= 2 )
9197 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9200 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9207 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9216 #else // OLD_NEF_POLYGON
9217 { ////////////////////////////////// NEW
9218 gp_XYZ newPos(0,0,0);
9220 // get a plane to search a solution on
9223 gp_XYZ center(0,0,0);
9224 for ( i = 0; i < _simplices.size(); ++i )
9225 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9226 center /= _simplices.size();
9228 vector< gp_XYZ > vecs( _simplices.size() + 1 );
9229 for ( i = 0; i < _simplices.size(); ++i )
9230 vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9231 vecs.back() = vecs[0];
9233 const double tol = numeric_limits<double>::min();
9234 gp_XYZ zAxis(0,0,0);
9235 for ( i = 0; i < _simplices.size(); ++i )
9237 gp_XYZ cross = vecs[i] ^ vecs[i+1];
9240 if ( cross * zAxis < tol )
9241 zAxis += cross.Reversed();
9245 catch (Standard_Failure) { // if |cross| == 0.
9250 for ( i = 0; i < _simplices.size(); ++i )
9253 if ( yAxis.SquareModulus() > tol )
9256 gp_XYZ xAxis = yAxis ^ zAxis;
9257 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9258 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9259 // p0.Distance( _simplices[2]._nPrev ));
9260 // gp_XYZ center = smoothLaplacian();
9261 // gp_XYZ xAxis, yAxis, zAxis;
9262 // for ( i = 0; i < _simplices.size(); ++i )
9264 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9265 // if ( xAxis.SquareModulus() > tol*tol )
9268 // for ( i = 1; i < _simplices.size(); ++i )
9270 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9271 // zAxis = xAxis ^ yAxis;
9272 // if ( zAxis.SquareModulus() > tol*tol )
9275 // if ( i == _simplices.size() ) return newPos;
9277 yAxis = zAxis ^ xAxis;
9278 xAxis /= xAxis.Modulus();
9279 yAxis /= yAxis.Modulus();
9281 // get half-planes of _simplices
9283 vector< _halfPlane > halfPlns( _simplices.size() );
9285 for ( size_t i = 0; i < _simplices.size(); ++i )
9287 const gp_XYZ& OP1 = vecs[ i ];
9288 const gp_XYZ& OP2 = vecs[ i+1 ];
9289 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
9290 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
9291 gp_XY vec12 = p2 - p1;
9292 double dist12 = vec12.Modulus();
9296 halfPlns[ nbHP ]._pos = p1;
9297 halfPlns[ nbHP ]._dir = vec12;
9298 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9302 // intersect boundaries of half-planes, define state of intersection points
9303 // in relation to all half-planes and calculate internal point of a 2D polygon
9306 gp_XY newPos2D (0,0);
9308 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9309 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9310 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9312 vector< vector< TIntPntState > > allIntPnts( nbHP );
9313 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9315 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9316 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9318 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9319 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9322 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9324 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9326 if ( iHP1 == iHP2 ) continue;
9328 TIntPntState & ips1 = intPnts1[ iHP2 ];
9329 if ( ips1.second == UNDEF )
9331 // find an intersection point of boundaries of iHP1 and iHP2
9333 if ( iHP2 == iPrev ) // intersection with neighbors is known
9334 ips1.first = halfPlns[ iHP1 ]._pos;
9335 else if ( iHP2 == iNext )
9336 ips1.first = halfPlns[ iHP2 ]._pos;
9337 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9338 ips1.second = NO_INT;
9340 // classify the found intersection point
9341 if ( ips1.second != NO_INT )
9343 ips1.second = NOT_OUT;
9344 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9345 if ( i != iHP1 && i != iHP2 &&
9346 halfPlns[ i ].IsOut( ips1.first, tol ))
9347 ips1.second = IS_OUT;
9349 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9350 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9351 TIntPntState & ips2 = intPnts2[ iHP1 ];
9354 if ( ips1.second == NOT_OUT )
9357 segEnds[ bool(segEnds[0]) ] = & ips1.first;
9361 // find a NOT_OUT segment of boundary which is located between
9362 // two NOT_OUT int points
9365 continue; // no such a segment
9369 // sort points along the boundary
9370 map< double, TIntPntState* > ipsByParam;
9371 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9373 TIntPntState & ips1 = intPnts1[ iHP2 ];
9374 if ( ips1.second != NO_INT )
9376 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
9377 double param = op * halfPlns[ iHP1 ]._dir;
9378 ipsByParam.insert( make_pair( param, & ips1 ));
9381 // look for two neighboring NOT_OUT points
9383 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9384 for ( ; u2ips != ipsByParam.end(); ++u2ips )
9386 TIntPntState & ips1 = *(u2ips->second);
9387 if ( ips1.second == NOT_OUT )
9388 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9389 else if ( nbNotOut >= 2 )
9396 if ( nbNotOut >= 2 )
9398 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9401 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9408 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9417 #endif // OLD_NEF_POLYGON
9419 //================================================================================
9421 * \brief Add a new segment to _LayerEdge during inflation
9423 //================================================================================
9425 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
9430 if ( len > _maxLen )
9433 Block( eos.GetData() );
9435 const double lenDelta = len - _len;
9436 if ( lenDelta < len * 1e-3 )
9438 Block( eos.GetData() );
9442 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9443 gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
9445 if ( eos._hyp.IsOffsetMethod() )
9449 SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
9450 while ( faceIt->more() )
9452 const SMDS_MeshElement* face = faceIt->next();
9453 if ( !eos.GetNormal( face, faceNorm ))
9456 // translate plane of a face
9457 gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
9459 // find point of intersection of the face plane located at baryCenter
9460 // and _normal located at newXYZ
9461 double d = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
9462 double dot = ( faceNorm.XYZ() * _normal );
9463 if ( dot < std::numeric_limits<double>::min() )
9464 dot = lenDelta * 1e-3;
9465 double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
9466 newXYZ += step * _normal;
9468 _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
9472 newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
9475 n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
9476 _pos.push_back( newXYZ );
9478 if ( !eos._sWOL.IsNull() )
9482 if ( eos.SWOLType() == TopAbs_EDGE )
9484 double u = Precision::Infinite(); // to force projection w/o distance check
9485 uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
9486 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9487 _pos.back().SetCoord( u, 0, 0 );
9488 if ( _nodes.size() > 1 && uvOK )
9490 SMDS_EdgePositionPtr pos = n->GetPosition();
9491 pos->SetUParameter( u );
9496 gp_XY uv( Precision::Infinite(), 0 );
9497 uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
9498 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9499 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
9500 if ( _nodes.size() > 1 && uvOK )
9502 SMDS_FacePositionPtr pos = n->GetPosition();
9503 pos->SetUParameter( uv.X() );
9504 pos->SetVParameter( uv.Y() );
9509 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
9513 n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
9515 Block( eos.GetData() );
9523 if ( eos.ShapeType() != TopAbs_FACE )
9525 for ( size_t i = 0; i < _neibors.size(); ++i )
9526 //if ( _len > _neibors[i]->GetSmooLen() )
9527 _neibors[i]->Set( MOVED );
9531 dumpMove( n ); //debug
9534 //================================================================================
9536 * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
9538 //================================================================================
9540 void _LayerEdge::Block( _SolidData& data )
9542 //if ( Is( BLOCKED )) return;
9545 SMESH_Comment msg( "#BLOCK shape=");
9546 msg << data.GetShapeEdges( this )->_shapeID
9547 << ", nodes " << _nodes[0]->GetID() << ", " << _nodes.back()->GetID();
9548 dumpCmd( msg + " -- BEGIN");
9551 std::queue<_LayerEdge*> queue;
9554 gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9555 while ( !queue.empty() )
9557 _LayerEdge* edge = queue.front(); queue.pop();
9558 pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9559 pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9560 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9562 _LayerEdge* neibor = edge->_neibors[iN];
9563 if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9565 pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9566 pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9567 double minDist = pSrc.SquareDistance( pSrcN );
9568 minDist = Min( pTgt.SquareDistance( pTgtN ), minDist );
9569 minDist = Min( pSrc.SquareDistance( pTgtN ), minDist );
9570 minDist = Min( pTgt.SquareDistance( pSrcN ), minDist );
9571 double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9572 //if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() ) viscous_layers_00/A3
9574 //newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9575 // newMaxLen *= Min( edge->_lenFactor / neibor->_lenFactor,
9576 // neibor->_lenFactor / edge->_lenFactor );
9578 if ( neibor->_maxLen > newMaxLen )
9580 neibor->SetMaxLen( newMaxLen );
9581 if ( neibor->_maxLen < neibor->_len )
9583 _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9584 int lastStep = neibor->Is( BLOCKED ) ? 1 : 0;
9585 while ( neibor->_len > neibor->_maxLen &&
9586 neibor->NbSteps() > lastStep )
9587 neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9588 neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9589 //neibor->Block( data );
9591 queue.push( neibor );
9595 dumpCmd( msg + " -- END");
9598 //================================================================================
9600 * \brief Remove last inflation step
9602 //================================================================================
9604 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9606 if ( _pos.size() > curStep && _nodes.size() > 1 )
9608 _pos.resize( curStep );
9610 gp_Pnt nXYZ = _pos.back();
9611 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9612 SMESH_TNodeXYZ curXYZ( n );
9613 if ( !eos._sWOL.IsNull() )
9615 TopLoc_Location loc;
9616 if ( eos.SWOLType() == TopAbs_EDGE )
9618 SMDS_EdgePositionPtr pos = n->GetPosition();
9619 pos->SetUParameter( nXYZ.X() );
9621 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9622 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9626 SMDS_FacePositionPtr pos = n->GetPosition();
9627 pos->SetUParameter( nXYZ.X() );
9628 pos->SetVParameter( nXYZ.Y() );
9629 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9630 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9633 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9636 if ( restoreLength )
9638 if ( NbSteps() == 0 )
9640 else if ( IsOnFace() && Is( MOVED ))
9641 _len = ( nXYZ.XYZ() - SMESH_NodeXYZ( _nodes[0] )) * _normal;
9643 _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9649 //================================================================================
9651 * \brief Return index of a _pos distant from _normal
9653 //================================================================================
9655 int _LayerEdge::GetSmoothedPos( const double tol )
9658 for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9660 double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9661 if ( normDist > tol * tol )
9667 //================================================================================
9669 * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9671 //================================================================================
9673 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9675 if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9678 // find the 1st smoothed _pos
9679 int iSmoothed = GetSmoothedPos( tol );
9680 if ( !iSmoothed ) return;
9682 gp_XYZ normal = _normal;
9683 if ( Is( NORMAL_UPDATED ))
9686 for ( size_t i = 0; i < _neibors.size(); ++i )
9688 if ( _neibors[i]->IsOnFace() )
9690 double dot = _normal * _neibors[i]->_normal;
9693 normal = _neibors[i]->_normal;
9699 for ( size_t i = 1; i < _pos.size(); ++i )
9701 normal = _pos[i] - _pos[0];
9702 double size = normal.Modulus();
9703 if ( size > RealSmall() )
9710 const double r = 0.2;
9711 for ( int iter = 0; iter < 50; ++iter )
9714 for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9716 gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9717 gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9719 double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9720 double newLen = ( 1-r ) * midLen + r * segLen[i];
9721 const_cast< double& >( segLen[i] ) = newLen;
9722 // check angle between normal and (_pos[i+1], _pos[i] )
9723 gp_XYZ posDir = _pos[i+1] - _pos[i];
9724 double size = posDir.SquareModulus();
9725 if ( size > RealSmall() )
9726 minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9728 if ( minDot > 0.5 * 0.5 )
9734 //================================================================================
9736 * \brief Print flags
9738 //================================================================================
9740 std::string _LayerEdge::DumpFlags() const
9743 for ( int flag = 1; flag < 0x1000000; flag *= 2 )
9744 if ( _flags & flag )
9746 EFlags f = (EFlags) flag;
9748 case TO_SMOOTH: dump << "TO_SMOOTH"; break;
9749 case MOVED: dump << "MOVED"; break;
9750 case SMOOTHED: dump << "SMOOTHED"; break;
9751 case DIFFICULT: dump << "DIFFICULT"; break;
9752 case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
9753 case BLOCKED: dump << "BLOCKED"; break;
9754 case INTERSECTED: dump << "INTERSECTED"; break;
9755 case NORMAL_UPDATED: dump << "NORMAL_UPDATED"; break;
9756 case UPD_NORMAL_CONV: dump << "UPD_NORMAL_CONV"; break;
9757 case MARKED: dump << "MARKED"; break;
9758 case MULTI_NORMAL: dump << "MULTI_NORMAL"; break;
9759 case NEAR_BOUNDARY: dump << "NEAR_BOUNDARY"; break;
9760 case SMOOTHED_C1: dump << "SMOOTHED_C1"; break;
9761 case DISTORTED: dump << "DISTORTED"; break;
9762 case RISKY_SWOL: dump << "RISKY_SWOL"; break;
9763 case SHRUNK: dump << "SHRUNK"; break;
9764 case UNUSED_FLAG: dump << "UNUSED_FLAG"; break;
9768 cout << dump << endl;
9773 //================================================================================
9775 * \brief Create layers of prisms
9777 //================================================================================
9779 bool _ViscousBuilder::refine(_SolidData& data)
9781 SMESH_MesherHelper& helper = data.GetHelper();
9782 helper.SetElementsOnShape(false);
9784 Handle(Geom_Curve) curve;
9785 Handle(ShapeAnalysis_Surface) surface;
9786 TopoDS_Edge geomEdge;
9787 TopoDS_Face geomFace;
9788 TopLoc_Location loc;
9791 vector< gp_XYZ > pos3D;
9792 bool isOnEdge, isTooConvexFace = false;
9793 TGeomID prevBaseId = -1;
9794 TNode2Edge* n2eMap = 0;
9795 TNode2Edge::iterator n2e;
9797 // Create intermediate nodes on each _LayerEdge
9799 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9801 _EdgesOnShape& eos = data._edgesOnShape[iS];
9802 if ( eos._edges.empty() ) continue;
9804 if ( eos._edges[0]->_nodes.size() < 2 )
9805 continue; // on _noShrinkShapes
9807 // get data of a shrink shape
9809 geomEdge.Nullify(); geomFace.Nullify();
9810 curve.Nullify(); surface.Nullify();
9811 if ( !eos._sWOL.IsNull() )
9813 isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9816 geomEdge = TopoDS::Edge( eos._sWOL );
9817 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
9821 geomFace = TopoDS::Face( eos._sWOL );
9822 surface = helper.GetSurface( geomFace );
9825 else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9827 geomFace = TopoDS::Face( eos._shape );
9828 surface = helper.GetSurface( geomFace );
9829 // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9830 for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9831 eos._eosC1[ i ]->_toSmooth = true;
9833 isTooConvexFace = false;
9834 if ( _ConvexFace* cf = data.GetConvexFace( eos._shapeID ))
9835 isTooConvexFace = cf->_isTooCurved;
9838 vector< double > segLen;
9839 for ( size_t i = 0; i < eos._edges.size(); ++i )
9841 _LayerEdge& edge = *eos._edges[i];
9842 if ( edge._pos.size() < 2 )
9845 // get accumulated length of segments
9846 segLen.resize( edge._pos.size() );
9848 if ( eos._sWOL.IsNull() )
9850 bool useNormal = true;
9851 bool usePos = false;
9852 bool smoothed = false;
9853 double preci = 0.1 * edge._len;
9854 if ( eos._toSmooth && edge._pos.size() > 2 )
9856 smoothed = edge.GetSmoothedPos( preci );
9860 if ( !surface.IsNull() && !isTooConvexFace ) // edge smoothed on FACE
9862 useNormal = usePos = false;
9863 gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9864 for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9866 uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9867 if ( surface->Gap() < 2. * edge._len )
9868 segLen[j] = surface->Gap();
9874 else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9876 #ifndef __NODES_AT_POS
9877 useNormal = usePos = false;
9878 edge._pos[1] = edge._pos.back();
9879 edge._pos.resize( 2 );
9881 segLen[ 1 ] = edge._len;
9884 if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9886 useNormal = usePos = false;
9887 _LayerEdge tmpEdge; // get original _normal
9888 tmpEdge._nodes.push_back( edge._nodes[0] );
9889 if ( !setEdgeData( tmpEdge, eos, helper, data ))
9892 for ( size_t j = 1; j < edge._pos.size(); ++j )
9893 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9897 for ( size_t j = 1; j < edge._pos.size(); ++j )
9898 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9902 for ( size_t j = 1; j < edge._pos.size(); ++j )
9903 segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9907 bool swapped = ( edge._pos.size() > 2 );
9911 for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9912 if ( segLen[j] > segLen.back() )
9914 segLen.erase( segLen.begin() + j );
9915 edge._pos.erase( edge._pos.begin() + j );
9918 else if ( segLen[j] < segLen[j-1] )
9920 std::swap( segLen[j], segLen[j-1] );
9921 std::swap( edge._pos[j], edge._pos[j-1] );
9926 // smooth a path formed by edge._pos
9927 #ifndef __NODES_AT_POS
9928 if (( smoothed ) /*&&
9929 ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9930 edge.SmoothPos( segLen, preci );
9933 else if ( eos._isRegularSWOL ) // usual SWOL
9935 if ( edge.Is( _LayerEdge::SMOOTHED ))
9937 SMESH_NodeXYZ p0( edge._nodes[0] );
9938 for ( size_t j = 1; j < edge._pos.size(); ++j )
9940 gp_XYZ pj = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9941 segLen[j] = ( pj - p0 ) * edge._normal;
9946 for ( size_t j = 1; j < edge._pos.size(); ++j )
9947 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9950 else if ( !surface.IsNull() ) // SWOL surface with singularities
9952 pos3D.resize( edge._pos.size() );
9953 for ( size_t j = 0; j < edge._pos.size(); ++j )
9954 pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9956 for ( size_t j = 1; j < edge._pos.size(); ++j )
9957 segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9960 // allocate memory for new nodes if it is not yet refined
9961 const SMDS_MeshNode* tgtNode = edge._nodes.back();
9962 if ( edge._nodes.size() == 2 )
9964 #ifdef __NODES_AT_POS
9965 int nbNodes = edge._pos.size();
9967 int nbNodes = eos._hyp.GetNumberLayers() + 1;
9969 edge._nodes.resize( nbNodes, 0 );
9971 edge._nodes.back() = tgtNode;
9973 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9974 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9975 if ( baseShapeId != prevBaseId )
9977 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9978 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9979 prevBaseId = baseShapeId;
9981 _LayerEdge* edgeOnSameNode = 0;
9982 bool useExistingPos = false;
9983 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9985 edgeOnSameNode = n2e->second;
9986 useExistingPos = ( edgeOnSameNode->_len < edge._len );
9987 const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9988 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
9991 SMDS_EdgePositionPtr epos = lastPos;
9992 epos->SetUParameter( otherTgtPos.X() );
9996 SMDS_FacePositionPtr fpos = lastPos;
9997 fpos->SetUParameter( otherTgtPos.X() );
9998 fpos->SetVParameter( otherTgtPos.Y() );
10001 // calculate height of the first layer
10003 const double T = segLen.back(); //data._hyp.GetTotalThickness();
10004 const double f = eos._hyp.GetStretchFactor();
10005 const int N = eos._hyp.GetNumberLayers();
10006 const double fPowN = pow( f, N );
10007 if ( fPowN - 1 <= numeric_limits<double>::min() )
10010 h0 = T * ( f - 1 )/( fPowN - 1 );
10012 const double zeroLen = std::numeric_limits<double>::min();
10014 // create intermediate nodes
10015 double hSum = 0, hi = h0/f;
10017 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
10019 // compute an intermediate position
10022 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
10024 int iPrevSeg = iSeg-1;
10025 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
10027 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
10028 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
10029 #ifdef __NODES_AT_POS
10030 pos = edge._pos[ iStep ];
10032 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
10033 if ( !eos._sWOL.IsNull() )
10035 // compute XYZ by parameters <pos>
10040 pos = curve->Value( u ).Transformed(loc);
10042 else if ( eos._isRegularSWOL )
10044 uv.SetCoord( pos.X(), pos.Y() );
10046 pos = surface->Value( pos.X(), pos.Y() );
10050 uv.SetCoord( pos.X(), pos.Y() );
10051 gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
10052 uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
10054 pos = surface->Value( uv );
10057 // create or update the node
10060 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
10061 if ( !eos._sWOL.IsNull() )
10064 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
10066 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
10070 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
10075 if ( !eos._sWOL.IsNull() )
10077 // make average pos from new and current parameters
10080 //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
10081 if ( useExistingPos )
10082 u = helper.GetNodeU( geomEdge, node );
10083 pos = curve->Value( u ).Transformed(loc);
10085 SMDS_EdgePositionPtr epos = node->GetPosition();
10086 epos->SetUParameter( u );
10090 //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
10091 if ( useExistingPos )
10092 uv = helper.GetNodeUV( geomFace, node );
10093 pos = surface->Value( uv );
10095 SMDS_FacePositionPtr fpos = node->GetPosition();
10096 fpos->SetUParameter( uv.X() );
10097 fpos->SetVParameter( uv.Y() );
10100 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
10102 } // loop on edge._nodes
10104 if ( !eos._sWOL.IsNull() ) // prepare for shrink()
10107 edge._pos.back().SetCoord( u, 0,0);
10109 edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
10111 if ( edgeOnSameNode )
10112 edgeOnSameNode->_pos.back() = edge._pos.back();
10115 } // loop on eos._edges to create nodes
10118 if ( !getMeshDS()->IsEmbeddedMode() )
10119 // Log node movement
10120 for ( size_t i = 0; i < eos._edges.size(); ++i )
10122 SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
10123 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
10130 helper.SetElementsOnShape(true);
10132 vector< vector<const SMDS_MeshNode*>* > nnVec;
10133 set< vector<const SMDS_MeshNode*>* > nnSet;
10134 set< int > degenEdgeInd;
10135 vector<const SMDS_MeshElement*> degenVols;
10137 TopExp_Explorer exp( data._solid, TopAbs_FACE );
10138 for ( ; exp.More(); exp.Next() )
10140 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
10141 if ( data._ignoreFaceIds.count( faceID ))
10143 const bool isReversedFace = data._reversedFaceIds.count( faceID );
10144 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
10145 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
10146 while ( fIt->more() )
10148 const SMDS_MeshElement* face = fIt->next();
10149 const int nbNodes = face->NbCornerNodes();
10150 nnVec.resize( nbNodes );
10152 degenEdgeInd.clear();
10153 size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
10154 SMDS_NodeIteratorPtr nIt = face->nodeIterator();
10155 for ( int iN = 0; iN < nbNodes; ++iN )
10157 const SMDS_MeshNode* n = nIt->next();
10158 _LayerEdge* edge = data._n2eMap[ n ];
10159 const int i = isReversedFace ? nbNodes-1-iN : iN;
10160 nnVec[ i ] = & edge->_nodes;
10161 maxZ = std::max( maxZ, nnVec[ i ]->size() );
10162 minZ = std::min( minZ, nnVec[ i ]->size() );
10164 if ( helper.HasDegeneratedEdges() )
10165 nnSet.insert( nnVec[ i ]);
10170 if ( 0 < nnSet.size() && nnSet.size() < 3 )
10178 for ( size_t iZ = 1; iZ < minZ; ++iZ )
10179 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
10180 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
10182 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10184 for ( int iN = 0; iN < nbNodes; ++iN )
10185 if ( nnVec[ iN ]->size() < iZ+1 )
10186 degenEdgeInd.insert( iN );
10188 if ( degenEdgeInd.size() == 1 ) // PYRAM
10190 int i2 = *degenEdgeInd.begin();
10191 int i0 = helper.WrapIndex( i2 - 1, nbNodes );
10192 int i1 = helper.WrapIndex( i2 + 1, nbNodes );
10193 helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
10194 (*nnVec[i1])[iZ ], (*nnVec[i0])[iZ ], (*nnVec[i2]).back());
10198 int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
10199 helper.AddVolume( (*nnVec[ 0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
10200 (*nnVec[ 1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
10201 (*nnVec[ 2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
10202 (*nnVec[ i3 ])[ iZ ]);
10210 for ( size_t iZ = 1; iZ < minZ; ++iZ )
10211 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
10212 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
10213 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
10214 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
10216 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10218 for ( int iN = 0; iN < nbNodes; ++iN )
10219 if ( nnVec[ iN ]->size() < iZ+1 )
10220 degenEdgeInd.insert( iN );
10222 switch ( degenEdgeInd.size() )
10226 int i2 = *degenEdgeInd.begin();
10227 int i3 = *degenEdgeInd.rbegin();
10228 bool ok = ( i3 - i2 == 1 );
10229 if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
10230 int i0 = helper.WrapIndex( i3 + 1, nbNodes );
10231 int i1 = helper.WrapIndex( i0 + 1, nbNodes );
10233 const SMDS_MeshElement* vol =
10234 helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
10235 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
10237 degenVols.push_back( vol );
10241 default: // degen HEX
10243 const SMDS_MeshElement* vol =
10244 helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
10245 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
10246 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
10247 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
10248 nnVec[0]->size() > iZ ? (*nnVec[0])[iZ] : nnVec[0]->back(),
10249 nnVec[1]->size() > iZ ? (*nnVec[1])[iZ] : nnVec[1]->back(),
10250 nnVec[2]->size() > iZ ? (*nnVec[2])[iZ] : nnVec[2]->back(),
10251 nnVec[3]->size() > iZ ? (*nnVec[3])[iZ] : nnVec[3]->back());
10252 degenVols.push_back( vol );
10259 return error("Not supported type of element", data._index);
10261 } // switch ( nbNodes )
10262 } // while ( fIt->more() )
10265 if ( !degenVols.empty() )
10267 SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
10268 if ( !err || err->IsOK() )
10270 SMESH_BadInputElements* badElems =
10271 new SMESH_BadInputElements( getMeshDS(), COMPERR_WARNING, "Bad quality volumes created" );
10272 badElems->myBadElements.insert( badElems->myBadElements.end(),
10273 degenVols.begin(),degenVols.end() );
10274 err.reset( badElems );
10281 //================================================================================
10283 * \brief Shrink 2D mesh on faces to let space for inflated layers
10285 //================================================================================
10287 bool _ViscousBuilder::shrink(_SolidData& theData)
10289 // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
10290 // _LayerEdge's inflated along FACE or EDGE)
10291 map< TGeomID, list< _SolidData* > > f2sdMap;
10292 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10294 _SolidData& data = _sdVec[i];
10295 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
10296 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
10297 if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrinkedFaces.Contains( s2s->second ))
10299 f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
10301 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
10302 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
10303 // by StdMeshers_QuadToTriaAdaptor
10304 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
10306 SMESH_ProxyMesh::SubMesh* proxySub =
10307 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
10308 if ( proxySub->NbElements() == 0 )
10310 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10311 while ( fIt->more() )
10313 const SMDS_MeshElement* f = fIt->next();
10314 // as a result 3D algo will use elements from proxySub and not from smDS
10315 proxySub->AddElement( f );
10316 f->setIsMarked( true );
10318 // Mark nodes on the FACE to discriminate them from nodes
10319 // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
10320 for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
10322 const SMDS_MeshNode* n = f->GetNode( iN );
10323 if ( n->GetPosition()->GetDim() == 2 )
10324 n->setIsMarked( true );
10332 SMESH_MesherHelper helper( *_mesh );
10333 helper.ToFixNodeParameters( true );
10336 map< TGeomID, _Shrinker1D > e2shrMap;
10337 vector< _EdgesOnShape* > subEOS;
10338 vector< _LayerEdge* > lEdges;
10340 // loop on FACEs to shrink mesh on
10341 map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
10342 for ( ; f2sd != f2sdMap.end(); ++f2sd )
10344 list< _SolidData* > & dataList = f2sd->second;
10345 if ( dataList.front()->_n2eMap.empty() ||
10346 dataList.back() ->_n2eMap.empty() )
10347 continue; // not yet computed
10348 if ( dataList.front() != &theData &&
10349 dataList.back() != &theData )
10352 _SolidData& data = *dataList.front();
10353 _SolidData* data2 = dataList.size() > 1 ? dataList.back() : 0;
10354 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
10355 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
10356 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
10358 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
10360 _shrinkedFaces.Add( F );
10361 helper.SetSubShape( F );
10363 // ===========================
10364 // Prepare data for shrinking
10365 // ===========================
10367 // Collect nodes to smooth (they are marked at the beginning of this method)
10368 vector < const SMDS_MeshNode* > smoothNodes;
10370 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
10371 while ( nIt->more() )
10373 const SMDS_MeshNode* n = nIt->next();
10374 if ( n->isMarked() )
10375 smoothNodes.push_back( n );
10378 // Find out face orientation
10379 double refSign = 1;
10380 const set<TGeomID> ignoreShapes;
10382 if ( !smoothNodes.empty() )
10384 vector<_Simplex> simplices;
10385 _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
10386 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
10387 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
10388 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
10389 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
10393 // Find _LayerEdge's inflated along F
10397 SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
10398 /*complexFirst=*/true); //!!!
10399 while ( subIt->more() )
10401 const TGeomID subID = subIt->next()->GetId();
10402 if ( data._noShrinkShapes.count( subID ))
10404 _EdgesOnShape* eos = data.GetShapeEdges( subID );
10405 if ( !eos || eos->_sWOL.IsNull() )
10406 if ( data2 ) // check in adjacent SOLID
10408 eos = data2->GetShapeEdges( subID );
10409 if ( !eos || eos->_sWOL.IsNull() )
10412 subEOS.push_back( eos );
10414 for ( size_t i = 0; i < eos->_edges.size(); ++i )
10416 lEdges.push_back( eos->_edges[ i ] );
10417 prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
10422 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
10423 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10424 while ( fIt->more() )
10425 if ( const SMDS_MeshElement* f = fIt->next() )
10426 dumpChangeNodes( f );
10429 // Replace source nodes by target nodes in mesh faces to shrink
10430 dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
10431 const SMDS_MeshNode* nodes[20];
10432 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10434 _EdgesOnShape& eos = * subEOS[ iS ];
10435 for ( size_t i = 0; i < eos._edges.size(); ++i )
10437 _LayerEdge& edge = *eos._edges[i];
10438 const SMDS_MeshNode* srcNode = edge._nodes[0];
10439 const SMDS_MeshNode* tgtNode = edge._nodes.back();
10440 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
10441 while ( fIt->more() )
10443 const SMDS_MeshElement* f = fIt->next();
10444 if ( !smDS->Contains( f ) || !f->isMarked() )
10446 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
10447 for ( int iN = 0; nIt->more(); ++iN )
10449 const SMDS_MeshNode* n = nIt->next();
10450 nodes[iN] = ( n == srcNode ? tgtNode : n );
10452 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
10453 dumpChangeNodes( f );
10459 // find out if a FACE is concave
10460 const bool isConcaveFace = isConcave( F, helper );
10462 // Create _SmoothNode's on face F
10463 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
10465 dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
10466 const bool sortSimplices = isConcaveFace;
10467 for ( size_t i = 0; i < smoothNodes.size(); ++i )
10469 const SMDS_MeshNode* n = smoothNodes[i];
10470 nodesToSmooth[ i ]._node = n;
10471 // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
10472 _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
10473 // fix up incorrect uv of nodes on the FACE
10474 helper.GetNodeUV( F, n, 0, &isOkUV);
10479 //if ( nodesToSmooth.empty() ) continue;
10481 // Find EDGE's to shrink and set simpices to LayerEdge's
10482 set< _Shrinker1D* > eShri1D;
10484 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10486 _EdgesOnShape& eos = * subEOS[ iS ];
10487 if ( eos.SWOLType() == TopAbs_EDGE )
10489 SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
10490 _Shrinker1D& shrinker = e2shrMap[ edgeSM->GetId() ];
10491 eShri1D.insert( & shrinker );
10492 shrinker.AddEdge( eos._edges[0], eos, helper );
10493 VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
10494 // restore params of nodes on EDGE if the EDGE has been already
10495 // shrinked while shrinking other FACE
10496 shrinker.RestoreParams();
10498 for ( size_t i = 0; i < eos._edges.size(); ++i )
10500 _LayerEdge& edge = * eos._edges[i];
10501 _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
10503 // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
10504 // not-marked nodes are those added by refine()
10505 edge._nodes.back()->setIsMarked( true );
10510 bool toFixTria = false; // to improve quality of trias by diagonal swap
10511 if ( isConcaveFace )
10513 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
10514 if ( hasTria != hasQuad ) {
10515 toFixTria = hasTria;
10518 set<int> nbNodesSet;
10519 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10520 while ( fIt->more() && nbNodesSet.size() < 2 )
10521 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
10522 toFixTria = ( *nbNodesSet.begin() == 3 );
10526 // ==================
10527 // Perform shrinking
10528 // ==================
10530 bool shrinked = true;
10531 int nbBad, shriStep=0, smooStep=0;
10532 _SmoothNode::SmoothType smoothType
10533 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
10534 SMESH_Comment errMsg;
10538 // Move boundary nodes (actually just set new UV)
10539 // -----------------------------------------------
10540 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
10542 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10544 _EdgesOnShape& eos = * subEOS[ iS ];
10545 for ( size_t i = 0; i < eos._edges.size(); ++i )
10547 shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
10552 // Move nodes on EDGE's
10553 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
10554 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
10555 for ( ; shr != eShri1D.end(); ++shr )
10556 (*shr)->Compute( /*set3D=*/false, helper );
10559 // -----------------
10560 int nbNoImpSteps = 0;
10563 while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
10565 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10567 int oldBadNb = nbBad;
10570 // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
10571 _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
10572 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10574 moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
10575 smooTy, /*set3D=*/isConcaveFace);
10577 if ( nbBad < oldBadNb )
10587 errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
10588 if ( shriStep > 200 )
10589 errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
10590 if ( !errMsg.empty() )
10593 // Fix narrow triangles by swapping diagonals
10594 // ---------------------------------------
10597 set<const SMDS_MeshNode*> usedNodes;
10598 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
10600 // update working data
10601 set<const SMDS_MeshNode*>::iterator n;
10602 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
10604 n = usedNodes.find( nodesToSmooth[ i ]._node );
10605 if ( n != usedNodes.end())
10607 _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
10608 nodesToSmooth[ i ]._simplices,
10609 ignoreShapes, NULL,
10610 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
10611 usedNodes.erase( n );
10614 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
10616 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
10617 if ( n != usedNodes.end())
10619 _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
10620 lEdges[i]->_simplices,
10622 usedNodes.erase( n );
10626 // TODO: check effect of this additional smooth
10627 // additional laplacian smooth to increase allowed shrink step
10628 // for ( int st = 1; st; --st )
10630 // dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10631 // for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10633 // nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10634 // _SmoothNode::LAPLACIAN,/*set3D=*/false);
10638 } // while ( shrinked )
10640 if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
10642 debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
10645 SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
10647 vector< const SMDS_MeshElement* > facesToRm;
10650 facesToRm.reserve( psm->NbElements() );
10651 for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
10652 facesToRm.push_back( ite->next() );
10654 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10655 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10658 for ( size_t i = 0; i < facesToRm.size(); ++i )
10659 getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
10663 TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
10664 for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
10665 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10666 nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
10667 subEOS[iS]->_edges[i]->_nodes.end() );
10669 SMDS_NodeIteratorPtr itn = smDS->GetNodes();
10670 while ( itn->more() ) {
10671 const SMDS_MeshNode* n = itn->next();
10672 if ( !nodesToKeep.count( n ))
10673 getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
10676 // restore position and UV of target nodes
10678 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10679 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10681 _LayerEdge* edge = subEOS[iS]->_edges[i];
10682 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
10683 if ( edge->_pos.empty() ||
10684 edge->Is( _LayerEdge::SHRUNK )) continue;
10685 if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
10687 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
10688 pos->SetUParameter( edge->_pos[0].X() );
10689 pos->SetVParameter( edge->_pos[0].Y() );
10690 p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10694 SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
10695 pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10696 p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10698 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10699 dumpMove( tgtNode );
10701 // shrink EDGE sub-meshes and set proxy sub-meshes
10702 UVPtStructVec uvPtVec;
10703 set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10704 for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10706 _Shrinker1D* shr = (*shrIt);
10707 shr->Compute( /*set3D=*/true, helper );
10709 // set proxy mesh of EDGEs w/o layers
10710 map< double, const SMDS_MeshNode* > nodes;
10711 SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10712 // remove refinement nodes
10713 const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10714 const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10715 map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10716 if ( u2n->second == sn0 || u2n->second == sn1 )
10718 while ( u2n->second != tn0 && u2n->second != tn1 )
10720 nodes.erase( nodes.begin(), u2n );
10722 u2n = --nodes.end();
10723 if ( u2n->second == sn0 || u2n->second == sn1 )
10725 while ( u2n->second != tn0 && u2n->second != tn1 )
10727 nodes.erase( ++u2n, nodes.end() );
10729 // set proxy sub-mesh
10730 uvPtVec.resize( nodes.size() );
10731 u2n = nodes.begin();
10732 BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10733 for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10735 uvPtVec[ i ].node = u2n->second;
10736 uvPtVec[ i ].param = u2n->first;
10737 uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10739 StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10740 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10743 // set proxy mesh of EDGEs with layers
10744 vector< _LayerEdge* > edges;
10745 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10747 _EdgesOnShape& eos = * subEOS[ iS ];
10748 if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10750 const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10751 data.SortOnEdge( E, eos._edges );
10754 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10755 if ( !eov->_edges.empty() )
10756 edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10758 edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10760 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10761 if ( !eov->_edges.empty() )
10762 edges.push_back( eov->_edges[0] ); // on last VERTEX
10764 uvPtVec.resize( edges.size() );
10765 for ( size_t i = 0; i < edges.size(); ++i )
10767 uvPtVec[ i ].node = edges[i]->_nodes.back();
10768 uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10769 uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10771 BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10772 StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10773 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10775 // temporary clear the FACE sub-mesh from faces made by refine()
10776 vector< const SMDS_MeshElement* > elems;
10777 elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10778 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10779 elems.push_back( ite->next() );
10780 for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10781 elems.push_back( ite->next() );
10784 // compute the mesh on the FACE
10785 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10786 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10788 // re-fill proxy sub-meshes of the FACE
10789 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10790 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10791 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10792 psm->AddElement( ite->next() );
10795 for ( size_t i = 0; i < elems.size(); ++i )
10796 smDS->AddElement( elems[i] );
10798 if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10799 return error( errMsg );
10801 } // end of re-meshing in case of failed smoothing
10804 // No wrongly shaped faces remain; final smooth. Set node XYZ.
10805 bool isStructuredFixed = false;
10806 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10807 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10808 if ( !isStructuredFixed )
10810 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10811 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10813 for ( int st = 3; st; --st )
10816 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10817 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10818 case 3: smoothType = _SmoothNode::ANGULAR; break;
10820 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10821 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10823 nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10824 smoothType,/*set3D=*/st==1 );
10829 if ( !getMeshDS()->IsEmbeddedMode() )
10830 // Log node movement
10831 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10833 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10834 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10838 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10839 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10841 VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
10843 } // loop on FACES to shrink mesh on
10846 // Replace source nodes by target nodes in shrinked mesh edges
10848 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10849 for ( ; e2shr != e2shrMap.end(); ++e2shr )
10850 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10855 //================================================================================
10857 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10859 //================================================================================
10861 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
10862 _EdgesOnShape& eos,
10863 SMESH_MesherHelper& helper,
10864 const SMESHDS_SubMesh* faceSubMesh)
10866 const SMDS_MeshNode* srcNode = edge._nodes[0];
10867 const SMDS_MeshNode* tgtNode = edge._nodes.back();
10869 if ( eos.SWOLType() == TopAbs_FACE )
10871 if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10874 edge.Set( _LayerEdge::SHRUNK );
10875 return srcNode == tgtNode;
10877 gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() ); //helper.GetNodeUV( F, srcNode );
10878 gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10879 gp_Vec2d uvDir( srcUV, tgtUV );
10880 double uvLen = uvDir.Magnitude();
10882 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10885 //edge._pos.resize(1);
10886 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10888 // set UV of source node to target node
10889 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
10890 pos->SetUParameter( srcUV.X() );
10891 pos->SetVParameter( srcUV.Y() );
10893 else // _sWOL is TopAbs_EDGE
10895 if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10898 edge.Set( _LayerEdge::SHRUNK );
10899 return srcNode == tgtNode;
10901 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
10902 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10903 if ( !edgeSM || edgeSM->NbElements() == 0 )
10904 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10906 const SMDS_MeshNode* n2 = 0;
10907 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10908 while ( eIt->more() && !n2 )
10910 const SMDS_MeshElement* e = eIt->next();
10911 if ( !edgeSM->Contains(e)) continue;
10912 n2 = e->GetNode( 0 );
10913 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10916 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10918 double uSrc = helper.GetNodeU( E, srcNode, n2 );
10919 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10920 double u2 = helper.GetNodeU( E, n2, srcNode );
10922 //edge._pos.clear();
10924 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10926 // tgtNode is located so that it does not make faces with wrong orientation
10927 edge.Set( _LayerEdge::SHRUNK );
10930 //edge._pos.resize(1);
10931 edge._pos[0].SetCoord( U_TGT, uTgt );
10932 edge._pos[0].SetCoord( U_SRC, uSrc );
10933 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10935 edge._simplices.resize( 1 );
10936 edge._simplices[0]._nPrev = n2;
10938 // set U of source node to the target node
10939 SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
10940 pos->SetUParameter( uSrc );
10945 //================================================================================
10947 * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10949 //================================================================================
10951 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10953 if ( edge._nodes.size() == 1 )
10958 const SMDS_MeshNode* srcNode = edge._nodes[0];
10959 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10960 if ( S.IsNull() ) return;
10964 switch ( S.ShapeType() )
10969 TopLoc_Location loc;
10970 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10971 if ( curve.IsNull() ) return;
10972 SMDS_EdgePositionPtr ePos = srcNode->GetPosition();
10973 p = curve->Value( ePos->GetUParameter() );
10976 case TopAbs_VERTEX:
10978 p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10983 getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10984 dumpMove( srcNode );
10988 //================================================================================
10990 * \brief Try to fix triangles with high aspect ratio by swapping diagonals
10992 //================================================================================
10994 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
10995 SMESH_MesherHelper& helper,
10998 set<const SMDS_MeshNode*> * involvedNodes)
11000 SMESH::Controls::AspectRatio qualifier;
11001 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
11002 const double maxAspectRatio = is2D ? 4. : 2;
11003 _NodeCoordHelper xyz( F, helper, is2D );
11005 // find bad triangles
11007 vector< const SMDS_MeshElement* > badTrias;
11008 vector< double > badAspects;
11009 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
11010 SMDS_ElemIteratorPtr fIt = sm->GetElements();
11011 while ( fIt->more() )
11013 const SMDS_MeshElement * f = fIt->next();
11014 if ( f->NbCornerNodes() != 3 ) continue;
11015 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
11016 double aspect = qualifier.GetValue( points );
11017 if ( aspect > maxAspectRatio )
11019 badTrias.push_back( f );
11020 badAspects.push_back( aspect );
11025 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
11026 SMDS_ElemIteratorPtr fIt = sm->GetElements();
11027 while ( fIt->more() )
11029 const SMDS_MeshElement * f = fIt->next();
11030 if ( f->NbCornerNodes() == 3 )
11031 dumpChangeNodes( f );
11035 if ( badTrias.empty() )
11038 // find couples of faces to swap diagonal
11040 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
11041 vector< T2Trias > triaCouples;
11043 TIDSortedElemSet involvedFaces, emptySet;
11044 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
11047 double aspRatio [3];
11050 if ( !involvedFaces.insert( badTrias[iTia] ).second )
11052 for ( int iP = 0; iP < 3; ++iP )
11053 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
11055 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
11056 int bestCouple = -1;
11057 for ( int iSide = 0; iSide < 3; ++iSide )
11059 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
11060 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
11061 trias [iSide].first = badTrias[iTia];
11062 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
11064 if (( ! trias[iSide].second ) ||
11065 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
11066 ( ! sm->Contains( trias[iSide].second )))
11069 // aspect ratio of an adjacent tria
11070 for ( int iP = 0; iP < 3; ++iP )
11071 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
11072 double aspectInit = qualifier.GetValue( points2 );
11074 // arrange nodes as after diag-swaping
11075 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
11076 i3 = helper.WrapIndex( i1-1, 3 );
11078 i3 = helper.WrapIndex( i1+1, 3 );
11080 points1( 1+ iSide ) = points2( 1+ i3 );
11081 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
11083 // aspect ratio after diag-swaping
11084 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
11085 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
11088 // prevent inversion of a triangle
11089 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
11090 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
11091 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
11094 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
11095 bestCouple = iSide;
11098 if ( bestCouple >= 0 )
11100 triaCouples.push_back( trias[bestCouple] );
11101 involvedFaces.insert ( trias[bestCouple].second );
11105 involvedFaces.erase( badTrias[iTia] );
11108 if ( triaCouples.empty() )
11113 SMESH_MeshEditor editor( helper.GetMesh() );
11114 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11115 for ( size_t i = 0; i < triaCouples.size(); ++i )
11117 dumpChangeNodes( triaCouples[i].first );
11118 dumpChangeNodes( triaCouples[i].second );
11119 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
11122 if ( involvedNodes )
11123 for ( size_t i = 0; i < triaCouples.size(); ++i )
11125 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
11126 triaCouples[i].first->end_nodes() );
11127 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
11128 triaCouples[i].second->end_nodes() );
11131 // just for debug dump resulting triangles
11132 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11133 for ( size_t i = 0; i < triaCouples.size(); ++i )
11135 dumpChangeNodes( triaCouples[i].first );
11136 dumpChangeNodes( triaCouples[i].second );
11140 //================================================================================
11142 * \brief Move target node to it's final position on the FACE during shrinking
11144 //================================================================================
11146 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
11147 const TopoDS_Face& F,
11148 _EdgesOnShape& eos,
11149 SMESH_MesherHelper& helper )
11152 return false; // already at the target position
11154 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
11156 if ( eos.SWOLType() == TopAbs_FACE )
11158 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
11159 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
11160 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
11161 const double uvLen = tgtUV.Distance( curUV );
11162 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
11164 // Select shrinking step such that not to make faces with wrong orientation.
11165 double stepSize = 1e100;
11166 for ( size_t i = 0; i < _simplices.size(); ++i )
11168 if ( !_simplices[i]._nPrev->isMarked() ||
11169 !_simplices[i]._nNext->isMarked() )
11170 continue; // simplex of quadrangle created by addBoundaryElements()
11172 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
11173 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
11174 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
11175 gp_XY dirN = uvN2 - uvN1;
11176 double det = uvDir.Crossed( dirN );
11177 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
11178 gp_XY dirN2Cur = curUV - uvN1;
11179 double step = dirN.Crossed( dirN2Cur ) / det;
11181 stepSize = Min( step, stepSize );
11184 if ( uvLen <= stepSize )
11190 else if ( stepSize > 0 )
11192 newUV = curUV + uvDir.XY() * stepSize * kSafe;
11198 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11199 pos->SetUParameter( newUV.X() );
11200 pos->SetVParameter( newUV.Y() );
11203 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11204 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11205 dumpMove( tgtNode );
11208 else // _sWOL is TopAbs_EDGE
11210 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
11211 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
11212 SMDS_EdgePositionPtr tgtPos = tgtNode->GetPosition();
11214 const double u2 = helper.GetNodeU( E, n2, tgtNode );
11215 const double uSrc = _pos[0].Coord( U_SRC );
11216 const double lenTgt = _pos[0].Coord( LEN_TGT );
11218 double newU = _pos[0].Coord( U_TGT );
11219 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
11221 Set( _LayerEdge::SHRUNK );
11226 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
11228 tgtPos->SetUParameter( newU );
11230 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
11231 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11232 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11233 dumpMove( tgtNode );
11240 //================================================================================
11242 * \brief Perform smooth on the FACE
11243 * \retval bool - true if the node has been moved
11245 //================================================================================
11247 bool _SmoothNode::Smooth(int& nbBad,
11248 Handle(Geom_Surface)& surface,
11249 SMESH_MesherHelper& helper,
11250 const double refSign,
11254 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
11256 // get uv of surrounding nodes
11257 vector<gp_XY> uv( _simplices.size() );
11258 for ( size_t i = 0; i < _simplices.size(); ++i )
11259 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
11261 // compute new UV for the node
11262 gp_XY newPos (0,0);
11263 if ( how == TFI && _simplices.size() == 4 )
11266 for ( size_t i = 0; i < _simplices.size(); ++i )
11267 if ( _simplices[i]._nOpp )
11268 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
11270 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
11272 newPos = helper.calcTFI ( 0.5, 0.5,
11273 corners[0], corners[1], corners[2], corners[3],
11274 uv[1], uv[2], uv[3], uv[0] );
11276 else if ( how == ANGULAR )
11278 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
11280 else if ( how == CENTROIDAL && _simplices.size() > 3 )
11282 // average centers of diagonals wieghted with their reciprocal lengths
11283 if ( _simplices.size() == 4 )
11285 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
11286 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
11287 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
11291 double sumWeight = 0;
11292 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
11293 for ( int i = 0; i < nb; ++i )
11296 int iTo = i + _simplices.size() - 1;
11297 for ( int j = iFrom; j < iTo; ++j )
11299 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
11300 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
11302 newPos += w * ( uv[i]+uv[i2] );
11305 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
11310 // Laplacian smooth
11311 for ( size_t i = 0; i < _simplices.size(); ++i )
11313 newPos /= _simplices.size();
11316 // count quality metrics (orientation) of triangles around the node
11317 int nbOkBefore = 0;
11318 gp_XY tgtUV = helper.GetNodeUV( face, _node );
11319 for ( size_t i = 0; i < _simplices.size(); ++i )
11320 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
11323 for ( size_t i = 0; i < _simplices.size(); ++i )
11324 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
11326 if ( nbOkAfter < nbOkBefore )
11328 nbBad += _simplices.size() - nbOkBefore;
11332 SMDS_FacePositionPtr pos = _node->GetPosition();
11333 pos->SetUParameter( newPos.X() );
11334 pos->SetVParameter( newPos.Y() );
11341 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
11342 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
11346 nbBad += _simplices.size() - nbOkAfter;
11347 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
11350 //================================================================================
11352 * \brief Computes new UV using angle based smoothing technique
11354 //================================================================================
11356 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
11357 const gp_XY& uvToFix,
11358 const double refSign)
11360 uv.push_back( uv.front() );
11362 vector< gp_XY > edgeDir ( uv.size() );
11363 vector< double > edgeSize( uv.size() );
11364 for ( size_t i = 1; i < edgeDir.size(); ++i )
11366 edgeDir [i-1] = uv[i] - uv[i-1];
11367 edgeSize[i-1] = edgeDir[i-1].Modulus();
11368 if ( edgeSize[i-1] < numeric_limits<double>::min() )
11369 edgeDir[i-1].SetX( 100 );
11371 edgeDir[i-1] /= edgeSize[i-1] * refSign;
11373 edgeDir.back() = edgeDir.front();
11374 edgeSize.back() = edgeSize.front();
11378 double sumSize = 0;
11379 for ( size_t i = 1; i < edgeDir.size(); ++i )
11381 if ( edgeDir[i-1].X() > 1. ) continue;
11383 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
11384 if ( i == edgeDir.size() ) break;
11386 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
11387 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
11388 gp_XY bisec = norm1 + norm2;
11389 double bisecSize = bisec.Modulus();
11390 if ( bisecSize < numeric_limits<double>::min() )
11392 bisec = -edgeDir[i1] + edgeDir[i];
11393 bisecSize = bisec.Modulus();
11395 bisec /= bisecSize;
11397 gp_XY dirToN = uvToFix - p;
11398 double distToN = dirToN.Modulus();
11399 if ( bisec * dirToN < 0 )
11400 distToN = -distToN;
11402 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
11404 sumSize += edgeSize[i1] + edgeSize[i];
11406 newPos /= /*nbEdges * */sumSize;
11410 //================================================================================
11412 * \brief Delete _SolidData
11414 //================================================================================
11416 _SolidData::~_SolidData()
11418 TNode2Edge::iterator n2e = _n2eMap.begin();
11419 for ( ; n2e != _n2eMap.end(); ++n2e )
11421 _LayerEdge* & e = n2e->second;
11424 delete e->_curvature;
11425 if ( e->_2neibors )
11426 delete e->_2neibors->_plnNorm;
11427 delete e->_2neibors;
11438 //================================================================================
11440 * \brief Keep a _LayerEdge inflated along the EDGE
11442 //================================================================================
11444 void _Shrinker1D::AddEdge( const _LayerEdge* e,
11445 _EdgesOnShape& eos,
11446 SMESH_MesherHelper& helper )
11449 if ( _nodes.empty() )
11451 _edges[0] = _edges[1] = 0;
11454 // check _LayerEdge
11455 if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
11457 if ( eos.SWOLType() != TopAbs_EDGE )
11458 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
11459 if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
11460 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
11462 // store _LayerEdge
11463 _geomEdge = TopoDS::Edge( eos._sWOL );
11465 BRep_Tool::Range( _geomEdge, f,l );
11466 double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
11467 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
11471 const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
11472 const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
11474 if ( _nodes.empty() )
11476 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
11477 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
11479 TopLoc_Location loc;
11480 Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
11481 GeomAdaptor_Curve aCurve(C, f,l);
11482 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
11484 int nbExpectNodes = eSubMesh->NbNodes();
11485 _initU .reserve( nbExpectNodes );
11486 _normPar.reserve( nbExpectNodes );
11487 _nodes .reserve( nbExpectNodes );
11488 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
11489 while ( nIt->more() )
11491 const SMDS_MeshNode* node = nIt->next();
11493 // skip refinement nodes
11494 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
11495 node == tgtNode0 || node == tgtNode1 )
11497 bool hasMarkedFace = false;
11498 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
11499 while ( fIt->more() && !hasMarkedFace )
11500 hasMarkedFace = fIt->next()->isMarked();
11501 if ( !hasMarkedFace )
11504 _nodes.push_back( node );
11505 _initU.push_back( helper.GetNodeU( _geomEdge, node ));
11506 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
11507 _normPar.push_back( len / totLen );
11512 // remove target node of the _LayerEdge from _nodes
11513 size_t nbFound = 0;
11514 for ( size_t i = 0; i < _nodes.size(); ++i )
11515 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
11516 _nodes[i] = 0, nbFound++;
11517 if ( nbFound == _nodes.size() )
11522 //================================================================================
11524 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
11526 //================================================================================
11528 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
11530 if ( _done || _nodes.empty())
11532 const _LayerEdge* e = _edges[0];
11533 if ( !e ) e = _edges[1];
11536 _done = (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
11537 ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
11540 if ( set3D || _done )
11542 Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
11543 GeomAdaptor_Curve aCurve(C, f,l);
11546 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11548 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11549 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
11551 for ( size_t i = 0; i < _nodes.size(); ++i )
11553 if ( !_nodes[i] ) continue;
11554 double len = totLen * _normPar[i];
11555 GCPnts_AbscissaPoint discret( aCurve, len, f );
11556 if ( !discret.IsDone() )
11557 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
11558 double u = discret.Parameter();
11559 SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
11560 pos->SetUParameter( u );
11561 gp_Pnt p = C->Value( u );
11562 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
11567 BRep_Tool::Range( _geomEdge, f,l );
11569 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11571 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11573 for ( size_t i = 0; i < _nodes.size(); ++i )
11575 if ( !_nodes[i] ) continue;
11576 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
11577 SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
11578 pos->SetUParameter( u );
11583 //================================================================================
11585 * \brief Restore initial parameters of nodes on EDGE
11587 //================================================================================
11589 void _Shrinker1D::RestoreParams()
11592 for ( size_t i = 0; i < _nodes.size(); ++i )
11594 if ( !_nodes[i] ) continue;
11595 SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
11596 pos->SetUParameter( _initU[i] );
11601 //================================================================================
11603 * \brief Replace source nodes by target nodes in shrinked mesh edges
11605 //================================================================================
11607 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
11609 const SMDS_MeshNode* nodes[3];
11610 for ( int i = 0; i < 2; ++i )
11612 if ( !_edges[i] ) continue;
11614 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
11615 if ( !eSubMesh ) return;
11616 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
11617 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
11618 const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
11619 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11620 while ( eIt->more() )
11622 const SMDS_MeshElement* e = eIt->next();
11623 if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
11625 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
11626 for ( int iN = 0; iN < e->NbNodes(); ++iN )
11628 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
11629 nodes[iN] = ( n == srcNode ? tgtNode : n );
11631 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
11636 //================================================================================
11638 * \brief Creates 2D and 1D elements on boundaries of new prisms
11640 //================================================================================
11642 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
11644 SMESH_MesherHelper helper( *_mesh );
11646 vector< const SMDS_MeshNode* > faceNodes;
11648 //for ( size_t i = 0; i < _sdVec.size(); ++i )
11650 //_SolidData& data = _sdVec[i];
11651 TopTools_IndexedMapOfShape geomEdges;
11652 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
11653 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
11655 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
11656 const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
11657 if ( data._noShrinkShapes.count( edgeID ))
11660 // Get _LayerEdge's based on E
11662 map< double, const SMDS_MeshNode* > u2nodes;
11663 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
11666 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
11667 TNode2Edge & n2eMap = data._n2eMap;
11668 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
11670 //check if 2D elements are needed on E
11671 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
11672 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
11673 ledges.push_back( n2e->second );
11675 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
11676 continue; // no layers on E
11677 ledges.push_back( n2eMap[ u2n->second ]);
11679 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
11680 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
11681 int nbSharedPyram = 0;
11682 SMDS_ElemIteratorPtr vIt = tgtN1->GetInverseElementIterator(SMDSAbs_Volume);
11683 while ( vIt->more() )
11685 const SMDS_MeshElement* v = vIt->next();
11686 nbSharedPyram += int( v->GetNodeIndex( tgtN0 ) >= 0 );
11688 if ( nbSharedPyram > 1 )
11689 continue; // not free border of the pyramid
11692 faceNodes.push_back( ledges[0]->_nodes[0] );
11693 faceNodes.push_back( ledges[1]->_nodes[0] );
11694 if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
11695 if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
11697 if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
11698 continue; // faces already created
11700 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
11701 ledges.push_back( n2eMap[ u2n->second ]);
11703 // Find out orientation and type of face to create
11705 bool reverse = false, isOnFace;
11708 map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
11709 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
11711 F = e2f->second.Oriented( TopAbs_FORWARD );
11712 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
11713 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
11714 reverse = !reverse, F.Reverse();
11715 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11716 reverse = !reverse;
11718 else if ( !data._ignoreFaceIds.count( e2f->first ))
11720 // find FACE with layers sharing E
11721 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
11723 F = *( fIt->next() );
11725 // Find the sub-mesh to add new faces
11726 SMESHDS_SubMesh* sm = 0;
11728 sm = getMeshDS()->MeshElements( F );
11730 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11732 return error("error in addBoundaryElements()", data._index);
11734 // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
11735 // faces for 3D meshing (PAL23414)
11736 SMESHDS_SubMesh* adjSM = 0;
11739 const TGeomID faceID = sm->GetID();
11740 PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
11741 while ( const TopoDS_Shape* solid = soIt->next() )
11742 if ( !solid->IsSame( data._solid ))
11744 size_t iData = _solids.FindIndex( *solid ) - 1;
11745 if ( iData < _sdVec.size() &&
11746 _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
11747 _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
11749 SMESH_ProxyMesh::SubMesh* proxySub =
11750 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
11751 if ( proxySub && proxySub->NbElements() > 0 )
11758 const int dj1 = reverse ? 0 : 1;
11759 const int dj2 = reverse ? 1 : 0;
11760 vector< const SMDS_MeshElement*> ff; // new faces row
11761 SMESHDS_Mesh* m = getMeshDS();
11762 for ( size_t j = 1; j < ledges.size(); ++j )
11764 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
11765 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
11766 ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
11767 if ( nn1.size() == nn2.size() )
11770 for ( size_t z = 1; z < nn1.size(); ++z )
11771 sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11773 for ( size_t z = 1; z < nn1.size(); ++z )
11774 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11776 else if ( nn1.size() == 1 )
11779 for ( size_t z = 1; z < nn2.size(); ++z )
11780 sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11782 for ( size_t z = 1; z < nn2.size(); ++z )
11783 sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11788 for ( size_t z = 1; z < nn1.size(); ++z )
11789 sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11791 for ( size_t z = 1; z < nn1.size(); ++z )
11792 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11795 if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
11797 for ( size_t z = 0; z < ff.size(); ++z )
11799 adjSM->AddElement( ff[ z ]);
11805 for ( int isFirst = 0; isFirst < 2; ++isFirst )
11807 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11808 _EdgesOnShape* eos = data.GetShapeEdges( edge );
11809 if ( eos && eos->SWOLType() == TopAbs_EDGE )
11811 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
11812 if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
11814 helper.SetSubShape( eos->_sWOL );
11815 helper.SetElementsOnShape( true );
11816 for ( size_t z = 1; z < nn.size(); ++z )
11817 helper.AddEdge( nn[z-1], nn[z] );
11821 } // loop on EDGE's
11822 } // loop on _SolidData's