Salome HOME
Merge branch 'V9_6_BR'
[modules/smesh.git] / src / StdMeshers / StdMeshers_Import_1D.cxx
1 // Copyright (C) 2007-2020  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SMESH SMESH : implementation of SMESH idl descriptions
24 //  File   : StdMeshers_Import_1D.cxx
25 //  Module : SMESH
26 //
27 #include "StdMeshers_Import_1D.hxx"
28 #include "StdMeshers_ImportSource.hxx"
29
30 #include "SMDS_MeshElement.hxx"
31 #include "SMDS_MeshNode.hxx"
32 #include "SMESHDS_Group.hxx"
33 #include "SMESHDS_Mesh.hxx"
34 #include "SMESH_Comment.hxx"
35 #include "SMESH_Gen.hxx"
36 #include "SMESH_Group.hxx"
37 #include "SMESH_HypoFilter.hxx"
38 #include "SMESH_Mesh.hxx"
39 #include "SMESH_MeshEditor.hxx"
40 #include "SMESH_MesherHelper.hxx"
41 #include "SMESH_Octree.hxx"
42 #include "SMESH_subMesh.hxx"
43 #include "SMESH_subMeshEventListener.hxx"
44
45 #include "Utils_SALOME_Exception.hxx"
46 #include "utilities.h"
47
48 #include <BRepAdaptor_Curve.hxx>
49 #include <BRep_Builder.hxx>
50 #include <BRep_Tool.hxx>
51 #include <BndLib_Add3dCurve.hxx>
52 #include <GCPnts_TangentialDeflection.hxx>
53 #include <ShapeAnalysis_Curve.hxx>
54 #include <TopExp.hxx>
55 #include <TopExp_Explorer.hxx>
56 #include <TopoDS.hxx>
57 #include <TopoDS_Compound.hxx>
58 #include <TopoDS_Edge.hxx>
59 #include <TopoDS_Vertex.hxx>
60
61 using namespace std;
62
63 //================================================================================
64 namespace // INTERNAL STUFF
65 //================================================================================
66 {
67   /*!
68    * \brief Compute point position on a curve. Use octree to fast reject far points
69    */
70   class CurveProjector : public SMESH_Octree
71   {
72   public:
73     CurveProjector( const TopoDS_Edge& edge, double enlarge );
74
75     bool IsOnCurve( const gp_XYZ& point, double & distance2, double & u );
76
77     bool IsOut( const gp_XYZ& point ) const { return getBox()->IsOut( point ); }
78
79   protected:
80     CurveProjector() {}
81     SMESH_Octree* newChild() const { return new CurveProjector; }
82     void          buildChildrenData();
83     Bnd_B3d*      buildRootBox();
84
85   private:
86     struct CurveSegment : public Bnd_B3d
87     {
88       double _chord, _chord2, _length2;
89       gp_Pnt _pFirst, _pLast;
90       gp_Lin _line;
91       Handle(Geom_Curve) _curve;
92
93       CurveSegment() {}
94       void Init( const gp_Pnt& pf, const gp_Pnt& pl,
95                  double uf, double ul, double tol, Handle(Geom_Curve)& curve );
96       bool IsOn( const gp_XYZ& point, double & distance2, double & u );
97       bool IsInContact( const Bnd_B3d& bb );
98     };
99     std::vector< CurveSegment > _segments;
100   };
101
102   //===============================================================================
103   /*!
104    * \brief Create an octree of curve segments
105    */
106   //================================================================================
107
108   CurveProjector::CurveProjector( const TopoDS_Edge& edge, double enlarge )
109     :SMESH_Octree( 0 )
110   {
111     double f,l;
112     Handle(Geom_Curve) curve = BRep_Tool::Curve( edge, f, l );
113     double curDeflect = 0.3; // Curvature deflection
114     double angDeflect = 1e+100; // Angular deflection - don't control chordal error
115     GCPnts_TangentialDeflection div( BRepAdaptor_Curve( edge ), angDeflect, curDeflect );
116     _segments.resize( div.NbPoints() - 1 );
117     for ( int i = 1; i < div.NbPoints(); ++i )
118       try {
119         _segments[ i - 1 ].Init( div.Value( i ),     div.Value( i+1 ),
120                                  div.Parameter( i ), div.Parameter( i+1 ),
121                                  enlarge, curve );
122       }
123       catch ( Standard_Failure ) {
124         _segments.resize( _segments.size() - 1 );
125         --i;
126       }
127     if ( _segments.size() < 3 )
128       myIsLeaf = true;
129
130     compute();
131
132     if ( _segments.size() == 1 )
133       myBox->Enlarge( enlarge );
134   }
135
136   //================================================================================
137   /*!
138    * \brief Return the maximal box
139    */
140   //================================================================================
141
142   Bnd_B3d* CurveProjector::buildRootBox()
143   {
144     Bnd_B3d* box = new Bnd_B3d;
145     for ( size_t i = 0; i < _segments.size(); ++i )
146       box->Add( _segments[i] );
147     return box;
148   }
149
150   //================================================================================
151   /*!
152    * \brief Redistribute segments among children
153    */
154   //================================================================================
155
156   void CurveProjector::buildChildrenData()
157   {
158     bool allIn = true;
159     for ( size_t i = 0; i < _segments.size(); ++i )
160     {
161       for (int j = 0; j < 8; j++)
162       {
163         if ( _segments[i].IsInContact( *myChildren[j]->getBox() ))
164           ((CurveProjector*)myChildren[j])->_segments.push_back( _segments[i]);
165         else
166           allIn = false;
167       }
168     }
169     if ( allIn && _segments.size() < 3 )
170     {
171       myIsLeaf = true;
172       for (int j = 0; j < 8; j++)
173         static_cast<CurveProjector*>( myChildren[j])->myIsLeaf = true;
174     }
175     else
176     {
177       SMESHUtils::FreeVector( _segments ); // = _segments.clear() + free memory
178
179       for (int j = 0; j < 8; j++)
180       {
181         CurveProjector* child = static_cast<CurveProjector*>( myChildren[j]);
182         if ( child->_segments.size() < 3 )
183           child->myIsLeaf = true;
184       }
185     }
186   }
187
188   //================================================================================
189   /*!
190    * \brief Return true if a point is close to the curve
191    *  \param [in] point - the point
192    *  \param [out] distance2 - distance to the curve
193    *  \param [out] u - parameter on the curve
194    *  \return bool - is the point is close to the curve
195    */
196   //================================================================================
197
198   bool CurveProjector::IsOnCurve( const gp_XYZ& point, double & distance2, double & u )
199   {
200     if ( getBox()->IsOut( point ))
201       return false;
202
203     bool ok = false;
204     double dist2, param;
205     distance2 = Precision::Infinite();
206
207     if ( isLeaf() )
208     {
209       for ( size_t i = 0; i < _segments.size(); ++i )
210         if ( !_segments[i].IsOut( point ) &&
211              _segments[i].IsOn( point, dist2, param ) &&
212              dist2 < distance2 )
213         {
214           distance2 = dist2;
215           u         = param;
216           ok        = true;
217         }
218       return ok;
219     }
220     else
221     {
222       for (int i = 0; i < 8; i++)
223         if (((CurveProjector*) myChildren[i])->IsOnCurve( point, dist2, param ) &&
224             dist2 < distance2 )
225         {
226           distance2 = dist2;
227           u         = param;
228           ok        = true;
229         }
230     }
231     return ok;
232   }
233
234   //================================================================================
235   /*!
236    * \brief Initialize
237    */
238   //================================================================================
239
240   void CurveProjector::CurveSegment::Init(const gp_Pnt&       pf,
241                                           const gp_Pnt&       pl,
242                                           const double        uf,
243                                           const double        ul,
244                                           const double        tol,
245                                           Handle(Geom_Curve)& curve )
246   {
247     _pFirst  = pf;
248     _pLast   = pl;
249     _curve   = curve;
250     _length2 = pf.SquareDistance( pl );
251     _line.SetLocation( pf );
252     _line.SetDirection( gp_Vec( pf, pl ));
253     _chord2  = Max( _line.     SquareDistance( curve->Value( uf + 0.25 * ( ul - uf ))),
254                     Max( _line.SquareDistance( curve->Value( uf + 0.5  * ( ul - uf ))),
255                          _line.SquareDistance( curve->Value( uf + 0.75 * ( ul - uf )))));
256     _chord2  = Max( tol, _chord2 );
257     _chord   = Sqrt( _chord2 );
258
259     Bnd_Box bb;
260     BndLib_Add3dCurve::Add( GeomAdaptor_Curve( curve, uf, ul ), tol, bb );
261     Add( bb.CornerMin() );
262     Add( bb.CornerMax() );
263   }
264
265   //================================================================================
266   /*!
267    * \brief Return true if a point is close to the curve segment
268    *  \param [in] point - the point
269    *  \param [out] distance2 - distance to the curve
270    *  \param [out] u - parameter on the curve
271    *  \return bool - is the point is close to the curve segment
272    */
273   //================================================================================
274
275   bool CurveProjector::CurveSegment::IsOn( const gp_XYZ& point, double & distance2, double & u )
276   {
277     distance2 = _line.SquareDistance( point );
278     if ( distance2 > _chord2 )
279       return false;
280
281     // check if the point projection falls into the segment range
282     {
283       gp_Vec edge( _pFirst, _pLast );
284       gp_Vec n1p ( _pFirst, point  );
285       u = ( edge * n1p ) / _length2; // param [0,1] on the edge
286       if ( u < 0. )
287       {
288         if ( _pFirst.SquareDistance( point ) > _chord2 )
289           return false;
290       }
291       else if ( u > 1. )
292       {
293         if ( _pLast.SquareDistance( point ) > _chord2 )
294           return false;
295       }
296     }
297     gp_Pnt proj;
298     distance2 = ShapeAnalysis_Curve().Project( _curve, point, Precision::Confusion(),
299                                                proj, u, false );
300     distance2 *= distance2;
301     return true;
302   }
303
304   //================================================================================
305   /*!
306    * \brief Check if the segment is in contact with a box
307    */
308   //================================================================================
309
310   bool CurveProjector::CurveSegment::IsInContact( const Bnd_B3d& bb )
311   {
312     if ( bb.IsOut( _line.Position(), /*isRay=*/true, _chord ))
313       return false;
314
315     gp_Ax1 axRev = _line.Position().Reversed();
316     axRev.SetLocation( _pLast );
317     return !bb.IsOut( axRev, /*isRay=*/true, _chord );
318   }
319
320   //================================================================================
321   //================================================================================
322
323   int getSubmeshIDForCopiedMesh(const SMESHDS_Mesh* srcMeshDS, SMESH_Mesh* tgtMesh);
324
325   enum _ListenerDataType
326     {
327       WAIT_HYP_MODIF=1, // data indicating awaiting for valid parameters of src hyp
328       LISTEN_SRC_MESH, // data storing submesh depending on source mesh state
329       SRC_HYP // data storing ImportSource hyp
330     };
331   //================================================================================
332   /*!
333    * \brief _ListenerData holding ImportSource hyp holding in its turn
334    *  imported groups
335    */
336   struct _ListenerData : public SMESH_subMeshEventListenerData
337   {
338     const StdMeshers_ImportSource1D* _srcHyp;
339     _ListenerData(const StdMeshers_ImportSource1D* h, _ListenerDataType type=SRC_HYP):
340       SMESH_subMeshEventListenerData(/*isDeletable=*/true), _srcHyp(h)
341     {
342       myType = type;
343     }
344   };
345   //================================================================================
346   /*!
347    * \brief Comparator of sub-meshes
348    */
349   struct _SubLess
350   {
351     bool operator()(const SMESH_subMesh* sm1, const SMESH_subMesh* sm2 ) const
352     {
353       if ( sm1 == sm2 ) return false;
354       if ( !sm1 || !sm2 ) return sm1 < sm2;
355       const TopoDS_Shape& s1 = sm1->GetSubShape();
356       const TopoDS_Shape& s2 = sm2->GetSubShape();
357       TopAbs_ShapeEnum t1 = s1.IsNull() ? TopAbs_SHAPE : s1.ShapeType();
358       TopAbs_ShapeEnum t2 = s2.IsNull() ? TopAbs_SHAPE : s2.ShapeType();
359       if ( t1 == t2)
360         return (sm1 < sm2);
361       return t1 < t2; // to have: face < edge
362     }
363   };
364   //================================================================================
365   /*!
366    * \brief Container of data dedicated to one source mesh
367    */
368   struct _ImportData
369   {
370     const SMESH_Mesh* _srcMesh;
371     StdMeshers_Import_1D::TNodeNodeMap _n2n;
372     StdMeshers_Import_1D::TElemElemMap _e2e;
373
374     set< SMESH_subMesh*, _SubLess > _subM; // submeshes relating to this srcMesh
375     set< SMESH_subMesh*, _SubLess > _copyMeshSubM; // submeshes requesting mesh copying
376     set< SMESH_subMesh*, _SubLess > _copyGroupSubM; // submeshes requesting group copying
377     set< SMESH_subMesh*, _SubLess > _computedSubM;
378
379     SMESHDS_SubMesh*     _importMeshSubDS; // submesh storing a copy of _srcMesh
380     int                  _importMeshSubID; // id of _importMeshSubDS
381
382     _ImportData(const SMESH_Mesh* srcMesh=0):
383       _srcMesh(srcMesh), _importMeshSubDS(0),_importMeshSubID(-1) {}
384
385     void removeImportedMesh( SMESHDS_Mesh* meshDS )
386     {
387       if ( !_importMeshSubDS ) return;
388       SMDS_ElemIteratorPtr eIt = _importMeshSubDS->GetElements();
389       while ( eIt->more() )
390         meshDS->RemoveFreeElement( eIt->next(), 0, /*fromGroups=*/false );
391       SMDS_NodeIteratorPtr nIt = _importMeshSubDS->GetNodes();
392       while ( nIt->more() )
393         meshDS->RemoveFreeNode( nIt->next(), 0, /*fromGroups=*/false );
394       _importMeshSubDS->Clear();
395       _n2n.clear();
396       _e2e.clear();
397     }
398     void removeGroups( SMESH_subMesh* subM, const StdMeshers_ImportSource1D* srcHyp )
399     {
400       if ( !srcHyp ) return;
401       SMESH_Mesh*           tgtMesh = subM->GetFather();
402       const SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
403       const SMESHDS_Mesh* srcMeshDS = _srcMesh->GetMeshDS();
404       vector<SMESH_Group*>*  groups =
405         const_cast<StdMeshers_ImportSource1D*>(srcHyp)->GetResultGroups(*srcMeshDS,*tgtMeshDS);
406       if ( groups )
407       {
408         for ( unsigned i = 0; i < groups->size(); ++i )
409           tgtMesh->RemoveGroup( groups->at(i)->GetGroupDS()->GetID() );
410         groups->clear();
411       }
412     }
413     void trackHypParams( SMESH_subMesh* sm, const StdMeshers_ImportSource1D* srcHyp )
414     {
415       if ( !srcHyp ) return;
416       bool toCopyMesh, toCopyGroups;
417       srcHyp->GetCopySourceMesh(toCopyMesh, toCopyGroups);
418
419       if ( toCopyMesh )_copyMeshSubM.insert( sm );
420       else             _copyMeshSubM.erase( sm );
421
422       if ( toCopyGroups ) _copyGroupSubM.insert( sm );
423       else                _copyGroupSubM.erase( sm );
424     }
425     void addComputed( SMESH_subMesh* sm )
426     {
427       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true,
428                                                                /*complexShapeFirst=*/true);
429       while ( smIt->more() )
430       {
431         sm = smIt->next();
432         switch ( sm->GetSubShape().ShapeType() )
433         {
434         case TopAbs_EDGE:
435           if ( SMESH_Algo::isDegenerated( TopoDS::Edge( sm->GetSubShape() )))
436             continue;
437         case TopAbs_FACE:
438           _subM.insert( sm );
439           if ( !sm->IsEmpty() )
440             _computedSubM.insert( sm );
441         case TopAbs_VERTEX:
442           break;
443         default:;
444         }
445       }
446     }
447   };
448   //================================================================================
449   /*!
450    * Listener notified on events relating to imported submesh
451    */
452   class _Listener : public SMESH_subMeshEventListener
453   {
454     typedef map< SMESH_Mesh*, list< _ImportData > > TMesh2ImpData;
455     TMesh2ImpData _tgtMesh2ImportData;
456
457     _Listener():SMESH_subMeshEventListener(/*isDeletable=*/false,
458                                            "StdMeshers_Import_1D::_Listener") {}
459
460   public:
461     // return pointer to a static listener
462     static _Listener* get() { static _Listener theListener; return &theListener; }
463
464     static _ImportData* getImportData(const SMESH_Mesh* srcMesh, SMESH_Mesh* tgtMesh);
465
466     static void storeImportSubmesh(SMESH_subMesh*                   importSub,
467                                    const SMESH_Mesh*                srcMesh,
468                                    const StdMeshers_ImportSource1D* srcHyp);
469
470     virtual void ProcessEvent(const int                       event,
471                               const int                       eventType,
472                               SMESH_subMesh*                  subMesh,
473                               SMESH_subMeshEventListenerData* data,
474                               const SMESH_Hypothesis*         hyp);
475     void removeSubmesh( SMESH_subMesh* sm, _ListenerData* data );
476     void clearSubmesh ( SMESH_subMesh* sm, _ListenerData* data, bool clearAllSub );
477     void clearN2N     ( SMESH_Mesh* tgtMesh );
478
479     // mark sm as missing src hyp with valid groups
480     static void waitHypModification(SMESH_subMesh* sm)
481     {
482       sm->SetEventListener
483         (get(), SMESH_subMeshEventListenerData::MakeData( sm, WAIT_HYP_MODIF ), sm);
484     }
485   };
486   //--------------------------------------------------------------------------------
487   /*!
488    * \brief Find or create ImportData for given meshes
489    */
490   _ImportData* _Listener::getImportData(const SMESH_Mesh* srcMesh,
491                                         SMESH_Mesh*       tgtMesh)
492   {
493     list< _ImportData >& dList = get()->_tgtMesh2ImportData[tgtMesh];
494     list< _ImportData >::iterator d = dList.begin();
495     for ( ; d != dList.end(); ++d )
496       if ( d->_srcMesh == srcMesh )
497         return &*d;
498     dList.push_back(_ImportData(srcMesh));
499     return &dList.back();
500   }
501
502   //--------------------------------------------------------------------------------
503   /*!
504    * \brief Remember an imported sub-mesh and set needed even listeners
505    *  \param importSub - submesh computed by Import algo
506    *  \param srcMesh - source mesh
507    *  \param srcHyp - ImportSource hypothesis
508    */
509   void _Listener::storeImportSubmesh(SMESH_subMesh*                   importSub,
510                                      const SMESH_Mesh*                srcMesh,
511                                      const StdMeshers_ImportSource1D* srcHyp)
512   {
513     // set listener to hear events of the submesh computed by "Import" algo
514     importSub->SetEventListener( get(), new _ListenerData(srcHyp), importSub );
515
516     // set listeners to hear events of the source mesh
517     SMESH_subMesh* smToNotify = importSub;
518     vector<SMESH_subMesh*> smToListen = srcHyp->GetSourceSubMeshes( srcMesh );
519     for ( size_t i = 0; i < smToListen.size(); ++i )
520     {
521       SMESH_subMeshEventListenerData* data = new _ListenerData(srcHyp, LISTEN_SRC_MESH);
522       data->mySubMeshes.push_back( smToNotify );
523       importSub->SetEventListener( get(), data, smToListen[i] );
524     }
525     // remember the submesh importSub and its sub-submeshes
526     _ImportData* iData = _Listener::getImportData( srcMesh, importSub->GetFather());
527     iData->trackHypParams( importSub, srcHyp );
528     iData->addComputed( importSub );
529     if ( !iData->_copyMeshSubM.empty() && iData->_importMeshSubID < 1 )
530     {
531       SMESH_Mesh* tgtMesh = importSub->GetFather();
532       iData->_importMeshSubID = getSubmeshIDForCopiedMesh( srcMesh->GetMeshDS(),tgtMesh);
533       iData->_importMeshSubDS = tgtMesh->GetMeshDS()->NewSubMesh( iData->_importMeshSubID );
534     }
535   }
536   //--------------------------------------------------------------------------------
537   /*!
538    * \brief Remove imported mesh and/or groups if needed
539    *  \param sm - submesh losing Import algo
540    *  \param data - data holding imported groups
541    */
542   void _Listener::removeSubmesh( SMESH_subMesh* sm, _ListenerData* data )
543   {
544     list< _ImportData > &  dList = _tgtMesh2ImportData[ sm->GetFather() ];
545     list< _ImportData >::iterator d = dList.begin();
546     for ( ; d != dList.end(); ++d )
547       if ( (*d)._subM.erase( sm ))
548       {
549         d->_computedSubM.erase( sm );
550         bool rmMesh   = d->_copyMeshSubM.erase( sm ) && d->_copyMeshSubM.empty();
551         bool rmGroups = (d->_copyGroupSubM.erase( sm ) && d->_copyGroupSubM.empty()) || rmMesh;
552         if ( rmMesh )
553           d->removeImportedMesh( sm->GetFather()->GetMeshDS() );
554         if ( rmGroups && data && data->myType == SRC_HYP )
555           d->removeGroups( sm, data->_srcHyp );
556       }
557   }
558   //--------------------------------------------------------------------------------
559   /*!
560    * \brief Clear _ImportData::_n2n.
561    *        _n2n is useful within one mesh.Compute() only
562    */
563   void _Listener::clearN2N( SMESH_Mesh* tgtMesh )
564   {
565     list< _ImportData >& dList = get()->_tgtMesh2ImportData[tgtMesh];
566     list< _ImportData >::iterator d = dList.begin();
567     for ( ; d != dList.end(); ++d )
568       d->_n2n.clear();
569   }
570   //--------------------------------------------------------------------------------
571   /*!
572    * \brief Clear submeshes and remove imported mesh and/or groups if necessary
573    *  \param sm - cleared submesh
574    *  \param data - data holding imported groups
575    */
576   void _Listener::clearSubmesh(SMESH_subMesh* sm, _ListenerData* data, bool clearAllSub)
577   {
578     list< _ImportData > &  dList = _tgtMesh2ImportData[ sm->GetFather() ];
579     list< _ImportData >::iterator d = dList.begin();
580     for ( ; d != dList.end(); ++d )
581     {
582       if ( !d->_subM.count( sm )) continue;
583       if ( (*d)._computedSubM.erase( sm ) )
584       {
585         bool copyMesh = !d->_copyMeshSubM.empty();
586         if ( copyMesh || clearAllSub )
587         {
588           // remove imported mesh and groups
589           d->removeImportedMesh( sm->GetFather()->GetMeshDS() );
590
591           if ( data && data->myType == SRC_HYP )
592             d->removeGroups( sm, data->_srcHyp );
593
594           // clear the rest submeshes
595           if ( !d->_computedSubM.empty() )
596           {
597             d->_computedSubM.clear();
598             set< SMESH_subMesh*, _SubLess>::iterator sub = d->_subM.begin();
599             for ( ; sub != d->_subM.end(); ++sub )
600             {
601               SMESH_subMesh* subM = *sub;
602               _ListenerData* hypData = (_ListenerData*) subM->GetEventListenerData( get() );
603               if ( hypData && hypData->myType == SRC_HYP )
604                 d->removeGroups( sm, hypData->_srcHyp );
605
606               subM->ComputeStateEngine( SMESH_subMesh::CLEAN );
607               if ( subM->GetSubShape().ShapeType() == TopAbs_FACE )
608                 subM->ComputeSubMeshStateEngine( SMESH_subMesh::CLEAN );
609             }
610           }
611         }
612         sm->ComputeStateEngine( SMESH_subMesh::CLEAN );
613         if ( sm->GetSubShape().ShapeType() == TopAbs_FACE )
614           sm->ComputeSubMeshStateEngine( SMESH_subMesh::CLEAN );
615       }
616       if ( data && data->myType == SRC_HYP )
617         d->trackHypParams( sm, data->_srcHyp );
618       d->_n2n.clear();
619       d->_e2e.clear();
620     }
621   }
622   //--------------------------------------------------------------------------------
623   /*!
624    * \brief Remove imported mesh and/or groups
625    */
626   void _Listener::ProcessEvent(const int                       event,
627                                const int                       eventType,
628                                SMESH_subMesh*                  subMesh,
629                                SMESH_subMeshEventListenerData* data,
630                                const SMESH_Hypothesis*         /*hyp*/)
631   {
632     if ( data && data->myType == WAIT_HYP_MODIF )
633     {
634       // event of Import submesh
635       if ( SMESH_subMesh::MODIF_HYP  == event &&
636            SMESH_subMesh::ALGO_EVENT == eventType )
637       {
638         // re-call SetEventListener() to take into account valid parameters
639         // of ImportSource hypothesis
640         if ( SMESH_Algo* algo = subMesh->GetAlgo() )
641           algo->SetEventListener( subMesh );
642       }
643     }
644     else if ( data && data->myType == LISTEN_SRC_MESH )
645     {
646       // event of source mesh
647       if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
648       {
649         switch ( event ) {
650         case SMESH_subMesh::CLEAN:
651           // source mesh cleaned -> clean target mesh
652           clearSubmesh( data->mySubMeshes.front(), (_ListenerData*) data, /*all=*/true );
653           break;
654         case SMESH_subMesh::SUBMESH_COMPUTED: {
655           // source mesh computed -> reset FAILED state of Import submeshes to
656           // READY_TO_COMPUTE
657           SMESH_Mesh* srcMesh = subMesh->GetFather();
658           if ( srcMesh->NbEdges() > 0 || srcMesh->NbFaces() > 0 )
659           {
660             SMESH_Mesh* m = data->mySubMeshes.front()->GetFather();
661             if ( SMESH_subMesh* sm1 = m->GetSubMeshContaining(1))
662             {
663               sm1->ComputeStateEngine(SMESH_subMesh::SUBMESH_COMPUTED );
664               sm1->ComputeSubMeshStateEngine( SMESH_subMesh::SUBMESH_COMPUTED );
665             }
666           }
667           break;
668         }
669         default:;
670         }
671       }
672       if ( !data->mySubMeshes.empty() )
673         clearN2N( data->mySubMeshes.front()->GetFather() );
674     }
675     else // event of Import submesh
676     {
677       // find out what happens: import hyp modified or removed
678       bool removeImport = false, modifHyp = false;
679       if ( SMESH_subMesh::ALGO_EVENT == eventType )
680         modifHyp = true;
681       if ( subMesh->GetAlgoState() != SMESH_subMesh::HYP_OK )
682       {
683         removeImport = true;
684       }
685       else if (( SMESH_subMesh::REMOVE_ALGO == event ||
686                  SMESH_subMesh::REMOVE_FATHER_ALGO == event ) &&
687                SMESH_subMesh::ALGO_EVENT == eventType )
688       {
689         SMESH_Algo* algo = subMesh->GetAlgo();
690         removeImport = ( strncmp( "Import", algo->GetName(), 6 ) != 0 );
691       }
692
693       if ( removeImport )
694       {
695         // treate removal of Import algo from subMesh
696         removeSubmesh( subMesh, (_ListenerData*) data );
697       }
698       else if ( modifHyp ||
699                 ( SMESH_subMesh::CLEAN         == event &&
700                   SMESH_subMesh::COMPUTE_EVENT == eventType))
701       {
702         // treate modification of ImportSource hypothesis
703         clearSubmesh( subMesh, (_ListenerData*) data, /*all=*/false );
704       }
705       else if ( SMESH_subMesh::CHECK_COMPUTE_STATE == event &&
706                 SMESH_subMesh::COMPUTE_EVENT       == eventType )
707       {
708         // check compute state of all submeshes impoting from same src mesh;
709         // this is to take into account 1D computed submeshes hidden by 2D import algo;
710         // else source mesh is not copied as _subM.size != _computedSubM.size()
711         list< _ImportData > &  dList = _tgtMesh2ImportData[ subMesh->GetFather() ];
712         list< _ImportData >::iterator d = dList.begin();
713         for ( ; d != dList.end(); ++d )
714           if ( d->_subM.count( subMesh ))
715           {
716             set<SMESH_subMesh*,_SubLess>::iterator smIt = d->_subM.begin();
717             for( ; smIt != d->_subM.end(); ++smIt )
718               if ( (*smIt)->IsMeshComputed() )
719                 d->_computedSubM.insert( *smIt);
720           }
721       }
722       // Clear _ImportData::_n2n if it's no more useful, i.e. when
723       // the event is not within mesh.Compute()
724       if ( SMESH_subMesh::ALGO_EVENT == eventType )
725         clearN2N( subMesh->GetFather() );
726     }
727   }
728
729   //================================================================================
730   /*!
731    * \brief Return an ID of submesh to store nodes and elements of a copied mesh
732    */
733   //================================================================================
734
735   int getSubmeshIDForCopiedMesh(const SMESHDS_Mesh* srcMeshDS,
736                                 SMESH_Mesh*         tgtMesh)
737   {
738     // To get SMESH_subMesh corresponding to srcMeshDS we need to have a shape
739     // for which SMESHDS_Mesh::IsGroupOfSubShapes() returns true.
740     // And this shape must be different from sub-shapes of the main shape.
741     // So we create a compound containing
742     // 1) some sub-shapes of SMESH_Mesh::PseudoShape() corresponding to
743     //    srcMeshDS->GetPersistentId()
744     // 2) the 1-st vertex of the main shape to assure
745     //    SMESHDS_Mesh::IsGroupOfSubShapes(shape)==true
746     TopoDS_Shape shapeForSrcMesh;
747     TopTools_IndexedMapOfShape pseudoSubShapes;
748     TopExp::MapShapes( SMESH_Mesh::PseudoShape(), pseudoSubShapes );
749
750     // index of pseudoSubShapes corresponding to srcMeshDS
751     int    subIndex = 1 + srcMeshDS->GetPersistentId() % pseudoSubShapes.Extent();
752     int nbSubShapes = 1 + srcMeshDS->GetPersistentId() / pseudoSubShapes.Extent();
753
754     // try to find already present shapeForSrcMesh
755     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
756     for ( int i = tgtMeshDS->MaxShapeIndex(); i > 0 && shapeForSrcMesh.IsNull(); --i )
757     {
758       const TopoDS_Shape& s = tgtMeshDS->IndexToShape(i);
759       if ( s.ShapeType() != TopAbs_COMPOUND ) break;
760       TopoDS_Iterator sSubIt( s );
761       for ( int iSub = 0; iSub < nbSubShapes && sSubIt.More(); ++iSub, sSubIt.Next() )
762         if ( pseudoSubShapes( subIndex+iSub ).IsSame( sSubIt.Value()))
763           if ( iSub+1 == nbSubShapes )
764           {
765             shapeForSrcMesh = s;
766             break;
767           }
768     }
769     if ( shapeForSrcMesh.IsNull() )
770     {
771       // make a new shapeForSrcMesh
772       BRep_Builder aBuilder;
773       TopoDS_Compound comp;
774       aBuilder.MakeCompound( comp );
775       shapeForSrcMesh = comp;
776       for ( int iSub = 0; iSub < nbSubShapes; ++iSub )
777         if ( subIndex+iSub <= pseudoSubShapes.Extent() )
778           aBuilder.Add( comp, pseudoSubShapes( subIndex+iSub ));
779       TopExp_Explorer vExp( tgtMeshDS->ShapeToMesh(), TopAbs_VERTEX );
780       aBuilder.Add( comp, vExp.Current() );
781     }
782     SMESH_subMesh* sm = tgtMesh->GetSubMesh( shapeForSrcMesh );
783     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
784     if ( !smDS )
785       smDS = tgtMeshDS->NewSubMesh( sm->GetId() );
786
787     // make ordinary submesh from a complex one
788     if ( smDS->IsComplexSubmesh() )
789     {
790       list< const SMESHDS_SubMesh* > subSM;
791       SMESHDS_SubMeshIteratorPtr smIt = smDS->GetSubMeshIterator();
792       while ( smIt->more() ) subSM.push_back( smIt->next() );
793       list< const SMESHDS_SubMesh* >::iterator sub = subSM.begin();
794       for ( ; sub != subSM.end(); ++sub)
795         smDS->RemoveSubMesh( *sub );
796     }
797     return sm->GetId();
798   }
799
800   //================================================================================
801   /*!
802    * \brief Return a submesh to store nodes and elements of a copied mesh
803    * and set event listeners in order to clear
804    * imported mesh and groups as soon as submesh state requires it
805    */
806   //================================================================================
807
808   SMESHDS_SubMesh* getSubmeshForCopiedMesh(const SMESH_Mesh*                    srcMesh,
809                                            SMESH_Mesh*                          tgtMesh,
810                                            const TopoDS_Shape&                  tgtShape,
811                                            StdMeshers_Import_1D::TNodeNodeMap*& n2n,
812                                            StdMeshers_Import_1D::TElemElemMap*& e2e,
813                                            bool &                               toCopyGroups)
814   {
815     StdMeshers_Import_1D::getMaps( srcMesh, tgtMesh, n2n,e2e );
816
817     _ImportData* iData = _Listener::getImportData(srcMesh,tgtMesh);
818
819     SMESH_subMesh* importedSM = tgtMesh->GetSubMesh( tgtShape );
820     iData->addComputed( importedSM );
821     if ( iData->_computedSubM.size() != iData->_subM.size() )
822       return 0; // not all submeshes computed yet
823
824     toCopyGroups = !iData->_copyGroupSubM.empty();
825
826     if ( !iData->_copyMeshSubM.empty())
827     {
828       // make submesh to store a copied mesh
829       int smID = getSubmeshIDForCopiedMesh( srcMesh->GetMeshDS(), tgtMesh );
830       SMESHDS_SubMesh* subDS = tgtMesh->GetMeshDS()->NewSubMesh( smID );
831
832       iData->_importMeshSubID = smID;
833       iData->_importMeshSubDS = subDS;
834       return subDS;
835     }
836     return 0;
837   }
838
839   //================================================================================
840   /*!
841    * \brief Return minimal square length of edges of 1D and 2D elements sharing the node
842    */
843   //================================================================================
844
845   double getMinEdgeLength2( const SMDS_MeshNode* n )
846   {
847     SMESH_NodeXYZ p = n;
848     double minLen2 = Precision::Infinite();
849     for ( SMDS_ElemIteratorPtr eIt = n->GetInverseElementIterator(); eIt->more();  )
850     {
851       const SMDS_MeshElement*      e = eIt->next();
852       const SMDSAbs_ElementType type = e->GetType();
853       if ( type != SMDSAbs_Edge && type != SMDSAbs_Face )
854         continue;
855       int i = e->GetNodeIndex( n );
856       int iNext = SMESH_MesherHelper::WrapIndex( i + 1, e->NbCornerNodes() );
857       minLen2 = Min( minLen2, p.SquareDistance( e->GetNode( iNext )));
858       if ( type != SMDSAbs_Face )
859         continue;
860       int iPrev = SMESH_MesherHelper::WrapIndex( i - 1, e->NbCornerNodes() );
861       minLen2 = Min( minLen2, p.SquareDistance( e->GetNode( iPrev )));
862     }
863     return minLen2;
864   }
865
866 } // namespace
867
868 //=============================================================================
869 /*!
870  * Creates StdMeshers_Import_1D
871  */
872 //=============================================================================
873
874 StdMeshers_Import_1D::StdMeshers_Import_1D(int hypId, SMESH_Gen * gen)
875   :SMESH_1D_Algo(hypId, gen), _sourceHyp(0)
876 {
877   _name = "Import_1D";
878   _shapeType = (1 << TopAbs_EDGE);
879
880   _compatibleHypothesis.push_back("ImportSource1D");
881 }
882
883 //=============================================================================
884 /*!
885  * Check presence of a hypothesis
886  */
887 //=============================================================================
888
889 bool StdMeshers_Import_1D::CheckHypothesis
890                          (SMESH_Mesh&                          aMesh,
891                           const TopoDS_Shape&                  aShape,
892                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
893 {
894   _sourceHyp = 0;
895
896   const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(aMesh, aShape);
897   if ( hyps.size() == 0 )
898   {
899     aStatus = SMESH_Hypothesis::HYP_MISSING;
900     return false;  // can't work with no hypothesis
901   }
902
903   if ( hyps.size() > 1 )
904   {
905     aStatus = SMESH_Hypothesis::HYP_ALREADY_EXIST;
906     return false;
907   }
908
909   const SMESHDS_Hypothesis *theHyp = hyps.front();
910
911   string hypName = theHyp->GetName();
912
913   if (hypName == _compatibleHypothesis.front())
914   {
915     _sourceHyp = (StdMeshers_ImportSource1D *)theHyp;
916     aStatus = _sourceHyp->GetGroups().empty() ? HYP_BAD_PARAMETER : HYP_OK;
917     if ( aStatus == HYP_BAD_PARAMETER )
918       _Listener::waitHypModification( aMesh.GetSubMesh( aShape ));
919     return aStatus == HYP_OK;
920   }
921
922   aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
923   return false;
924 }
925
926 //=============================================================================
927 /*!
928  * Import elements from the other mesh
929  */
930 //=============================================================================
931
932 bool StdMeshers_Import_1D::Compute(SMESH_Mesh & theMesh, const TopoDS_Shape & theShape)
933 {
934   if ( !_sourceHyp ) return false;
935
936   //MESSAGE("---------> StdMeshers_Import_1D::Compute");
937   const vector<SMESH_Group*>& srcGroups = _sourceHyp->GetGroups(/*loaded=*/true);
938   if ( srcGroups.empty() )
939     return error("Invalid source groups");
940
941   SMESH_MesherHelper helper(theMesh);
942   helper.SetSubShape(theShape);
943   SMESHDS_Mesh* tgtMesh = theMesh.GetMeshDS();
944
945   const TopoDS_Edge& geomEdge = TopoDS::Edge( theShape );
946   const double edgeTol = BRep_Tool::Tolerance( geomEdge );
947   const int shapeID = tgtMesh->ShapeToIndex( geomEdge );
948
949
950   double geomTol = Precision::Confusion();
951   for ( size_t iG = 0; iG < srcGroups.size(); ++iG )
952   {
953     const SMESHDS_GroupBase* srcGroup = srcGroups[iG]->GetGroupDS();
954     for ( SMDS_ElemIteratorPtr srcElems = srcGroup->GetElements(); srcElems->more(); )
955     {
956       const SMDS_MeshElement* edge = srcElems->next();
957       geomTol = Sqrt( 0.5 * ( getMinEdgeLength2( edge->GetNode(0) ) +
958                               getMinEdgeLength2( edge->GetNode(1) ))) / 25;
959       iG = srcGroups.size();
960       break;
961     }
962   }
963   CurveProjector curveProjector( geomEdge, geomTol );
964
965   // get nodes on vertices
966   set<int> vertexIDs;
967   list < SMESH_TNodeXYZ > vertexNodes;
968   list < SMESH_TNodeXYZ >::iterator vNIt;
969   TopExp_Explorer vExp( theShape, TopAbs_VERTEX );
970   for ( ; vExp.More(); vExp.Next() )
971   {
972     const TopoDS_Vertex& v = TopoDS::Vertex( vExp.Current() );
973     if ( !vertexIDs.insert( tgtMesh->ShapeToIndex( v )).second )
974       continue; // closed edge
975     const SMDS_MeshNode* n = SMESH_Algo::VertexNode( v, tgtMesh );
976     if ( !n )
977     {
978       _gen->Compute(theMesh,v,/*anUpward=*/true);
979       n = SMESH_Algo::VertexNode( v, tgtMesh );
980       //MESSAGE("_gen->Compute " << n);
981       if ( !n ) return false; // very strange
982     }
983     vertexNodes.push_back( SMESH_TNodeXYZ( n ));
984     //MESSAGE("SMESH_Algo::VertexNode " << n->GetID() << " " << n->X() << " " << n->Y() << " " << n->Z() );
985   }
986
987   // import edges from groups
988   TNodeNodeMap* n2n;
989   TElemElemMap* e2e;
990   for ( size_t iG = 0; iG < srcGroups.size(); ++iG )
991   {
992     const SMESHDS_GroupBase* srcGroup = srcGroups[iG]->GetGroupDS();
993
994     const int meshID = srcGroup->GetMesh()->GetPersistentId();
995     const SMESH_Mesh* srcMesh = GetMeshByPersistentID( meshID );
996     if ( !srcMesh ) continue;
997     getMaps( srcMesh, &theMesh, n2n, e2e );
998
999     SMDS_ElemIteratorPtr srcElems = srcGroup->GetElements();
1000     vector<const SMDS_MeshNode*> newNodes;
1001     while ( srcElems->more() ) // loop on group contents
1002     {
1003       const SMDS_MeshElement* edge = srcElems->next();
1004       gp_XYZ middle = 0.5 * ( SMESH_NodeXYZ( edge->GetNode(0)) +
1005                               SMESH_NodeXYZ( edge->GetNode(1)));
1006       if ( curveProjector.IsOut( middle ))
1007         continue;
1008
1009       // find or create nodes of a new edge
1010       newNodes.resize( edge->NbNodes() );
1011       newNodes.back() = 0;
1012       int nbNodesOnVertex = 0;
1013       SMDS_MeshElement::iterator node = edge->begin_nodes();
1014       for ( size_t i = 0; i < newNodes.size(); ++i, ++node )
1015       {
1016         TNodeNodeMap::iterator n2nIt = n2n->insert( make_pair( *node, nullptr )).first;
1017         if ( n2nIt->second )
1018         {
1019           int sId = n2nIt->second->getshapeId();
1020           if ( sId != shapeID )
1021           {
1022             if ( vertexIDs.count( sId ))
1023               ++nbNodesOnVertex;
1024             else
1025               break;
1026           }
1027         }
1028         else if ( !vertexNodes.empty() )
1029         {
1030           // find an existing vertex node
1031           double checktol = max(1.E-10, 10*edgeTol*edgeTol);
1032           for ( vNIt = vertexNodes.begin(); vNIt != vertexNodes.end(); ++vNIt)
1033             if ( vNIt->SquareDistance( *node ) < checktol)
1034             {
1035               (*n2nIt).second = vNIt->_node;
1036               vertexNodes.erase( vNIt );
1037               ++nbNodesOnVertex;
1038               break;
1039             }
1040         }
1041         if ( !n2nIt->second )
1042         {
1043           // find out if the node lies on theShape
1044           SMESH_NodeXYZ xyz = *node;
1045           double dist2, u;
1046           if ( curveProjector.IsOnCurve( xyz, dist2, u ))
1047           {
1048             // tolerance relative to the length of surrounding edges
1049             double mytol2 = getMinEdgeLength2( *node ) / 25 / 25;
1050             if ( dist2 < mytol2 )
1051             {
1052               SMDS_MeshNode* newNode = tgtMesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1053               n2nIt->second = newNode;
1054               tgtMesh->SetNodeOnEdge( newNode, shapeID, u );
1055             }
1056           }
1057         }
1058         if ( !(newNodes[i] = n2nIt->second ))
1059           break;
1060       }
1061       if ( !newNodes.back() )
1062       {
1063         //MESSAGE("not all nodes of edge lie on theShape");
1064         continue; // not all nodes of edge lie on theShape
1065       }
1066
1067       // make a new edge
1068       SMDS_MeshElement * newEdge;
1069       if ( newNodes.size() == 3 )
1070         newEdge = tgtMesh->AddEdge( newNodes[0], newNodes[1], newNodes[2] );
1071       else
1072         newEdge = tgtMesh->AddEdge( newNodes[0], newNodes[1]);
1073       tgtMesh->SetMeshElementOnShape( newEdge, shapeID );
1074       e2e->insert( make_pair( edge, newEdge ));
1075
1076       if ( nbNodesOnVertex >= 2 ) // EDGE is meshed by a sole segment
1077       {
1078         iG = srcGroups.size(); // stop looingp on groups
1079         break;
1080       }
1081     }  // loop on group contents
1082   } // loop on groups
1083
1084   if ( n2n->empty())
1085     return error("Empty source groups");
1086
1087   // check if the whole geom edge is covered by imported segments;
1088   // the check consist in passing by segments from one vetrex node to another
1089   bool isEdgeMeshed = false;
1090   if ( SMESHDS_SubMesh* tgtSM = tgtMesh->MeshElements( theShape ))
1091   {
1092     const TopoDS_Vertex& v = ( vExp.ReInit(), TopoDS::Vertex( vExp.Current() ));
1093     const SMDS_MeshNode* n = SMESH_Algo::VertexNode( v, tgtMesh );
1094     const SMDS_MeshElement* seg = 0;
1095     SMDS_ElemIteratorPtr segIt = n->GetInverseElementIterator(SMDSAbs_Edge);
1096     while ( segIt->more() && !seg )
1097       if ( !tgtSM->Contains( seg = segIt->next()))
1098         seg = 0;
1099     int nbPassedSegs = 0;
1100     while ( seg )
1101     {
1102       ++nbPassedSegs;
1103       const SMDS_MeshNode* n2 = seg->GetNode(0);
1104       n = ( n2 == n ? seg->GetNode(1) : n2 );
1105       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
1106         break;
1107       const SMDS_MeshElement* seg2 = 0;
1108       segIt = n->GetInverseElementIterator(SMDSAbs_Edge);
1109       while ( segIt->more() && !seg2 )
1110         if ( seg == ( seg2 = segIt->next()))
1111           seg2 = 0;
1112       seg = seg2;
1113     }
1114     if (nbPassedSegs > 0 && tgtSM->NbElements() > nbPassedSegs )
1115       return error( "Source elements overlap one another");
1116
1117     isEdgeMeshed = ( tgtSM->NbElements() == nbPassedSegs &&
1118                      n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
1119   }
1120   if ( !isEdgeMeshed )
1121     return error( "Source elements don't cover totally the geometrical edge" );
1122
1123   // copy meshes
1124   vector<SMESH_Mesh*> srcMeshes = _sourceHyp->GetSourceMeshes();
1125   for ( size_t i = 0; i < srcMeshes.size(); ++i )
1126     importMesh( srcMeshes[i], theMesh, _sourceHyp, theShape );
1127
1128   return true;
1129 }
1130
1131 //================================================================================
1132 /*!
1133  * \brief Copy mesh and groups
1134  */
1135 //================================================================================
1136
1137 void StdMeshers_Import_1D::importMesh(const SMESH_Mesh*          srcMesh,
1138                                       SMESH_Mesh &               tgtMesh,
1139                                       StdMeshers_ImportSource1D* srcHyp,
1140                                       const TopoDS_Shape&        tgtShape)
1141 {
1142   // get submesh to store the imported mesh
1143   TNodeNodeMap* n2n;
1144   TElemElemMap* e2e;
1145   bool toCopyGroups;
1146   SMESHDS_SubMesh* tgtSubMesh =
1147     getSubmeshForCopiedMesh( srcMesh, &tgtMesh, tgtShape, n2n, e2e, toCopyGroups );
1148   if ( !tgtSubMesh || tgtSubMesh->NbNodes() + tgtSubMesh->NbElements() > 0 )
1149     return; // not to copy srcMeshDS twice
1150
1151   SMESHDS_Mesh* tgtMeshDS = tgtMesh.GetMeshDS();
1152   SMESH_MeshEditor additor( &tgtMesh );
1153
1154   // 1. Copy mesh
1155
1156   SMESH_MeshEditor::ElemFeatures elemType;
1157   vector<const SMDS_MeshNode*> newNodes;
1158   const SMESHDS_Mesh* srcMeshDS = srcMesh->GetMeshDS();
1159   SMDS_ElemIteratorPtr eIt = srcMeshDS->elementsIterator();
1160   while ( eIt->more() )
1161   {
1162     const SMDS_MeshElement* elem = eIt->next();
1163     TElemElemMap::iterator e2eIt = e2e->insert( make_pair( elem, (SMDS_MeshElement*)0 )).first;
1164     if ( e2eIt->second ) continue; // already copied by Compute()
1165     newNodes.resize( elem->NbNodes() );
1166     SMDS_MeshElement::iterator node = elem->begin_nodes();
1167     for ( unsigned i = 0; i < newNodes.size(); ++i, ++node )
1168     {
1169       TNodeNodeMap::iterator n2nIt = n2n->insert( make_pair( *node, (SMDS_MeshNode*)0 )).first;
1170       if ( !n2nIt->second )
1171       {
1172         (*n2nIt).second = tgtMeshDS->AddNode( (*node)->X(), (*node)->Y(), (*node)->Z());
1173         tgtSubMesh->AddNode( n2nIt->second );
1174       }
1175       newNodes[i] = n2nIt->second;
1176     }
1177     const SMDS_MeshElement* newElem =
1178       tgtMeshDS->FindElement( newNodes, elem->GetType(), /*noMedium=*/false );
1179     if ( !newElem )
1180     {
1181       newElem = additor.AddElement( newNodes, elemType.Init( elem, /*basicOnly=*/false ));
1182       tgtSubMesh->AddElement( newElem );
1183     }
1184     if ( toCopyGroups )
1185       (*e2eIt).second = newElem;
1186   }
1187   // copy free nodes
1188   if ( srcMeshDS->NbNodes() > (int) n2n->size() )
1189   {
1190     SMDS_NodeIteratorPtr nIt = srcMeshDS->nodesIterator();
1191     while( nIt->more() )
1192     {
1193       const SMDS_MeshNode* node = nIt->next();
1194       if ( node->NbInverseElements() == 0 )
1195       {
1196         const SMDS_MeshNode* newNode = tgtMeshDS->AddNode( node->X(), node->Y(), node->Z());
1197         n2n->insert( make_pair( node, newNode ));
1198         tgtSubMesh->AddNode( newNode );
1199       }
1200     }
1201   }
1202
1203   // 2. Copy groups
1204
1205   vector<SMESH_Group*> resultGroups;
1206   if ( toCopyGroups )
1207   {
1208     // collect names of existing groups to assure uniqueness of group names within a type
1209     map< SMDSAbs_ElementType, set<string> > namesByType;
1210     SMESH_Mesh::GroupIteratorPtr groupIt = tgtMesh.GetGroups();
1211     while ( groupIt->more() )
1212     {
1213       SMESH_Group* tgtGroup = groupIt->next();
1214       namesByType[ tgtGroup->GetGroupDS()->GetType() ].insert( tgtGroup->GetName() );
1215     }
1216     if (srcMesh)
1217     {
1218       SMESH_Mesh::GroupIteratorPtr groupIt = srcMesh->GetGroups();
1219       while ( groupIt->more() )
1220       {
1221         SMESH_Group* srcGroup = groupIt->next();
1222         SMESHDS_GroupBase* srcGroupDS = srcGroup->GetGroupDS();
1223         string name = srcGroup->GetName();
1224         int nb = 1;
1225         while ( !namesByType[ srcGroupDS->GetType() ].insert( name ).second )
1226           name = SMESH_Comment(srcGroup->GetName()) << "_imported_" << nb++;
1227         SMESH_Group* newGroup = tgtMesh.AddGroup( srcGroupDS->GetType(), name.c_str() );
1228         SMESHDS_Group* newGroupDS = (SMESHDS_Group*)newGroup->GetGroupDS();
1229         resultGroups.push_back( newGroup );
1230
1231         eIt = srcGroupDS->GetElements();
1232         if ( srcGroupDS->GetType() == SMDSAbs_Node )
1233           while (eIt->more())
1234           {
1235             TNodeNodeMap::iterator n2nIt = n2n->find((const SMDS_MeshNode*) eIt->next() );
1236             if ( n2nIt != n2n->end() && n2nIt->second )
1237               newGroupDS->SMDSGroup().Add((*n2nIt).second );
1238           }
1239         else
1240           while (eIt->more())
1241           {
1242             TElemElemMap::iterator e2eIt = e2e->find( eIt->next() );
1243             if ( e2eIt != e2e->end() && e2eIt->second )
1244               newGroupDS->SMDSGroup().Add((*e2eIt).second );
1245           }
1246       }
1247     }
1248   }
1249   n2n->clear();
1250   e2e->clear();
1251
1252   // Remember created groups in order to remove them as soon as the srcHyp is
1253   // modified or something other similar happens. This imformation must be persistent,
1254   // for that store them in a hypothesis as it stores its values in the file anyway
1255   srcHyp->StoreResultGroups( resultGroups, *srcMeshDS, *tgtMeshDS );
1256 }
1257
1258 //=============================================================================
1259 /*!
1260  * \brief Set needed event listeners and create a submesh for a copied mesh
1261  *
1262  * This method is called only if a submesh has HYP_OK algo_state.
1263  */
1264 //=============================================================================
1265
1266 void StdMeshers_Import_1D::setEventListener(SMESH_subMesh*             subMesh,
1267                                             StdMeshers_ImportSource1D* sourceHyp)
1268 {
1269   if ( sourceHyp )
1270   {
1271     vector<SMESH_Mesh*> srcMeshes = sourceHyp->GetSourceMeshes();
1272     if ( srcMeshes.empty() )
1273       _Listener::waitHypModification( subMesh );
1274     for ( unsigned i = 0; i < srcMeshes.size(); ++i )
1275       // set a listener to remove the imported mesh and groups
1276       _Listener::storeImportSubmesh( subMesh, srcMeshes[i], sourceHyp );
1277   }
1278 }
1279 void StdMeshers_Import_1D::SetEventListener(SMESH_subMesh* subMesh)
1280 {
1281   if ( !_sourceHyp )
1282   {
1283     const TopoDS_Shape& tgtShape = subMesh->GetSubShape();
1284     SMESH_Mesh*         tgtMesh  = subMesh->GetFather();
1285     Hypothesis_Status aStatus;
1286     CheckHypothesis( *tgtMesh, tgtShape, aStatus );
1287   }
1288   setEventListener( subMesh, _sourceHyp );
1289 }
1290
1291 void StdMeshers_Import_1D::SubmeshRestored(SMESH_subMesh* subMesh)
1292 {
1293   SetEventListener(subMesh);
1294 }
1295
1296 //=============================================================================
1297 /*!
1298  * Predict nb of mesh entities created by Compute()
1299  */
1300 //=============================================================================
1301
1302 bool StdMeshers_Import_1D::Evaluate(SMESH_Mesh &         theMesh,
1303                                     const TopoDS_Shape & theShape,
1304                                     MapShapeNbElems&     aResMap)
1305 {
1306   if ( !_sourceHyp ) return false;
1307
1308   const vector<SMESH_Group*>& srcGroups = _sourceHyp->GetGroups();
1309   if ( srcGroups.empty() )
1310     return error("Invalid source groups");
1311
1312   vector<int> aVec(SMDSEntity_Last,0);
1313
1314   bool toCopyMesh, toCopyGroups;
1315   _sourceHyp->GetCopySourceMesh(toCopyMesh, toCopyGroups);
1316   if ( toCopyMesh ) // the whole mesh is copied
1317   {
1318     vector<SMESH_Mesh*> srcMeshes = _sourceHyp->GetSourceMeshes();
1319     for ( unsigned i = 0; i < srcMeshes.size(); ++i )
1320     {
1321       SMESH_subMesh* sm = getSubMeshOfCopiedMesh( theMesh, *srcMeshes[i]);
1322       if ( !sm || aResMap.count( sm )) continue; // already counted
1323       aVec.assign( SMDSEntity_Last, 0);
1324       const SMDS_MeshInfo& aMeshInfo = srcMeshes[i]->GetMeshDS()->GetMeshInfo();
1325       for (int i = 0; i < SMDSEntity_Last; i++)
1326         aVec[i] = aMeshInfo.NbEntities((SMDSAbs_EntityType)i);
1327     }
1328   }
1329   else
1330   {
1331     SMESH_MesherHelper helper(theMesh);
1332
1333     const TopoDS_Edge& geomEdge = TopoDS::Edge( theShape );
1334     const double edgeTol = helper.MaxTolerance( geomEdge );
1335
1336     // take into account nodes on vertices
1337     TopExp_Explorer vExp( theShape, TopAbs_VERTEX );
1338     for ( ; vExp.More(); vExp.Next() )
1339       theMesh.GetSubMesh( vExp.Current())->Evaluate( aResMap );
1340
1341     // count edges imported from groups
1342     int nbEdges = 0, nbQuadEdges = 0;
1343     for ( size_t iG = 0; iG < srcGroups.size(); ++iG )
1344     {
1345       const SMESHDS_GroupBase* srcGroup = srcGroups[iG]->GetGroupDS();
1346       SMDS_ElemIteratorPtr srcElems = srcGroup->GetElements();
1347       SMDS_MeshNode *tmpNode = helper.AddNode(0,0,0);
1348       while ( srcElems->more() ) // loop on group contents
1349       {
1350         const SMDS_MeshElement* edge = srcElems->next();
1351         // find out if edge is located on geomEdge by projecting
1352         // a middle of edge to geomEdge
1353         SMESH_TNodeXYZ p1( edge->GetNode(0));
1354         SMESH_TNodeXYZ p2( edge->GetNode(1));
1355         gp_XYZ middle = ( p1 + p2 ) / 2.;
1356         tmpNode->setXYZ( middle.X(), middle.Y(), middle.Z());
1357         double u = 0;
1358         if ( helper.CheckNodeU( geomEdge, tmpNode, u, 10 * edgeTol, /*force=*/true ))
1359           ++( edge->IsQuadratic() ? nbQuadEdges : nbEdges);
1360       }
1361       helper.GetMeshDS()->RemoveNode(tmpNode);
1362     }
1363
1364     int nbNodes = nbEdges + 2 * nbQuadEdges - 1;
1365
1366     aVec[SMDSEntity_Node     ] = nbNodes;
1367     aVec[SMDSEntity_Edge     ] = nbEdges;
1368     aVec[SMDSEntity_Quad_Edge] = nbQuadEdges;
1369   }
1370
1371   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1372   aResMap.insert( make_pair( sm, aVec ));
1373
1374   return true;
1375 }
1376
1377 //================================================================================
1378 /*!
1379  * \brief Return node-node and element-element maps for import of geiven source mesh
1380  */
1381 //================================================================================
1382
1383 void StdMeshers_Import_1D::getMaps(const SMESH_Mesh* srcMesh,
1384                                    SMESH_Mesh*       tgtMesh,
1385                                    TNodeNodeMap*&    n2n,
1386                                    TElemElemMap*&    e2e)
1387 {
1388   _ImportData* iData = _Listener::getImportData(srcMesh,tgtMesh);
1389   n2n = &iData->_n2n;
1390   e2e = &iData->_e2e;
1391   if ( iData->_copyMeshSubM.empty() )
1392   {
1393     // n2n->clear(); -- for sharing nodes on EDGEs
1394     e2e->clear();
1395   }
1396 }
1397
1398 //================================================================================
1399 /*!
1400  * \brief Return submesh corresponding to the copied mesh
1401  */
1402 //================================================================================
1403
1404 SMESH_subMesh* StdMeshers_Import_1D::getSubMeshOfCopiedMesh( SMESH_Mesh& tgtMesh,
1405                                                              SMESH_Mesh& srcMesh )
1406 {
1407   _ImportData* iData = _Listener::getImportData(&srcMesh,&tgtMesh);
1408   if ( iData->_copyMeshSubM.empty() ) return 0;
1409   SMESH_subMesh* sm = tgtMesh.GetSubMeshContaining( iData->_importMeshSubID );
1410   return sm;
1411 }
1412