Salome HOME
Addition of MEDCouplingPointSet::areAllNodesFetched() method.
[tools/medcoupling.git] / src / MEDCoupling / MEDCouplingUMesh.cxx
1 // Copyright (C) 2007-2015  CEA/DEN, EDF R&D
2 //
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.
7 //
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.
12 //
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
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19 // Author : Anthony Geay (CEA/DEN)
20
21 #include "MEDCouplingUMesh.hxx"
22 #include "MEDCoupling1GTUMesh.hxx"
23 #include "MEDCouplingMemArray.txx"
24 #include "MEDCouplingFieldDouble.hxx"
25 #include "CellModel.hxx"
26 #include "VolSurfUser.txx"
27 #include "InterpolationUtils.hxx"
28 #include "PointLocatorAlgos.txx"
29 #include "BBTree.txx"
30 #include "BBTreeDst.txx"
31 #include "SplitterTetra.hxx"
32 #include "DirectedBoundingBox.hxx"
33 #include "InterpKernelMatrixTools.hxx"
34 #include "InterpKernelMeshQuality.hxx"
35 #include "InterpKernelCellSimplify.hxx"
36 #include "InterpKernelGeo2DEdgeArcCircle.hxx"
37 #include "InterpKernelAutoPtr.hxx"
38 #include "InterpKernelGeo2DNode.hxx"
39 #include "InterpKernelGeo2DEdgeLin.hxx"
40 #include "InterpKernelGeo2DEdgeArcCircle.hxx"
41 #include "InterpKernelGeo2DQuadraticPolygon.hxx"
42
43 #include <sstream>
44 #include <fstream>
45 #include <numeric>
46 #include <cstring>
47 #include <limits>
48 #include <list>
49
50 using namespace ParaMEDMEM;
51
52 double MEDCouplingUMesh::EPS_FOR_POLYH_ORIENTATION=1.e-14;
53
54 const INTERP_KERNEL::NormalizedCellType MEDCouplingUMesh::MEDMEM_ORDER[N_MEDMEM_ORDER] = { INTERP_KERNEL::NORM_POINT1, INTERP_KERNEL::NORM_SEG2, INTERP_KERNEL::NORM_SEG3, INTERP_KERNEL::NORM_SEG4, INTERP_KERNEL::NORM_POLYL, INTERP_KERNEL::NORM_TRI3, INTERP_KERNEL::NORM_QUAD4, INTERP_KERNEL::NORM_TRI6, INTERP_KERNEL::NORM_TRI7, INTERP_KERNEL::NORM_QUAD8, INTERP_KERNEL::NORM_QUAD9, INTERP_KERNEL::NORM_POLYGON, INTERP_KERNEL::NORM_QPOLYG, INTERP_KERNEL::NORM_TETRA4, INTERP_KERNEL::NORM_PYRA5, INTERP_KERNEL::NORM_PENTA6, INTERP_KERNEL::NORM_HEXA8, INTERP_KERNEL::NORM_HEXGP12, INTERP_KERNEL::NORM_TETRA10, INTERP_KERNEL::NORM_PYRA13, INTERP_KERNEL::NORM_PENTA15, INTERP_KERNEL::NORM_HEXA20, INTERP_KERNEL::NORM_HEXA27, INTERP_KERNEL::NORM_POLYHED };
55
56 MEDCouplingUMesh *MEDCouplingUMesh::New()
57 {
58   return new MEDCouplingUMesh;
59 }
60
61 MEDCouplingUMesh *MEDCouplingUMesh::New(const std::string& meshName, int meshDim)
62 {
63   MEDCouplingUMesh *ret=new MEDCouplingUMesh;
64   ret->setName(meshName);
65   ret->setMeshDimension(meshDim);
66   return ret;
67 }
68
69 /*!
70  * Returns a new MEDCouplingMesh which is a full copy of \a this one. No data is shared
71  * between \a this and the new mesh.
72  *  \return MEDCouplingMesh * - a new instance of MEDCouplingMesh. The caller is to
73  *          delete this mesh using decrRef() as it is no more needed. 
74  */
75 MEDCouplingMesh *MEDCouplingUMesh::deepCpy() const
76 {
77   return clone(true);
78 }
79
80 /*!
81  * Returns a new MEDCouplingMesh which is a copy of \a this one.
82  *  \param [in] recDeepCpy - if \a true, the copy is deep, else all data arrays of \a
83  * this mesh are shared by the new mesh.
84  *  \return MEDCouplingMesh * - a new instance of MEDCouplingMesh. The caller is to
85  *          delete this mesh using decrRef() as it is no more needed. 
86  */
87 MEDCouplingUMesh *MEDCouplingUMesh::clone(bool recDeepCpy) const
88 {
89   return new MEDCouplingUMesh(*this,recDeepCpy);
90 }
91
92 /*!
93  * This method behaves mostly like MEDCouplingUMesh::deepCpy method, except that only nodal connectivity arrays are deeply copied.
94  * The coordinates are shared between \a this and the returned instance.
95  * 
96  * \return MEDCouplingUMesh * - A new object instance holding the copy of \a this (deep for connectivity, shallow for coordiantes)
97  * \sa MEDCouplingUMesh::deepCpy
98  */
99 MEDCouplingPointSet *MEDCouplingUMesh::deepCpyConnectivityOnly() const
100 {
101   checkConnectivityFullyDefined();
102   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret=clone(false);
103   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> c(getNodalConnectivity()->deepCpy()),ci(getNodalConnectivityIndex()->deepCpy());
104   ret->setConnectivity(c,ci);
105   return ret.retn();
106 }
107
108 void MEDCouplingUMesh::shallowCopyConnectivityFrom(const MEDCouplingPointSet *other)
109 {
110   if(!other)
111     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::shallowCopyConnectivityFrom : input pointer is null !");
112   const MEDCouplingUMesh *otherC=dynamic_cast<const MEDCouplingUMesh *>(other);
113   if(!otherC)
114     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::shallowCopyConnectivityFrom : input pointer is not an MEDCouplingUMesh instance !");
115   MEDCouplingUMesh *otherC2=const_cast<MEDCouplingUMesh *>(otherC);//sorry :(
116   setConnectivity(otherC2->getNodalConnectivity(),otherC2->getNodalConnectivityIndex(),true);
117 }
118
119 std::size_t MEDCouplingUMesh::getHeapMemorySizeWithoutChildren() const
120 {
121   std::size_t ret(MEDCouplingPointSet::getHeapMemorySizeWithoutChildren());
122   return ret;
123 }
124
125 std::vector<const BigMemoryObject *> MEDCouplingUMesh::getDirectChildrenWithNull() const
126 {
127   std::vector<const BigMemoryObject *> ret(MEDCouplingPointSet::getDirectChildrenWithNull());
128   ret.push_back(_nodal_connec);
129   ret.push_back(_nodal_connec_index);
130   return ret;
131 }
132
133 void MEDCouplingUMesh::updateTime() const
134 {
135   MEDCouplingPointSet::updateTime();
136   if(_nodal_connec)
137     {
138       updateTimeWith(*_nodal_connec);
139     }
140   if(_nodal_connec_index)
141     {
142       updateTimeWith(*_nodal_connec_index);
143     }
144 }
145
146 MEDCouplingUMesh::MEDCouplingUMesh():_mesh_dim(-2),_nodal_connec(0),_nodal_connec_index(0)
147 {
148 }
149
150 /*!
151  * Checks if \a this mesh is well defined. If no exception is thrown by this method,
152  * then \a this mesh is most probably is writable, exchangeable and available for most
153  * of algorithms. When a mesh is constructed from scratch, it is a good habit to call
154  * this method to check that all is in order with \a this mesh.
155  *  \throw If the mesh dimension is not set.
156  *  \throw If the coordinates array is not set (if mesh dimension != -1 ).
157  *  \throw If \a this mesh contains elements of dimension different from the mesh dimension.
158  *  \throw If the connectivity data array has more than one component.
159  *  \throw If the connectivity data array has a named component.
160  *  \throw If the connectivity index data array has more than one component.
161  *  \throw If the connectivity index data array has a named component.
162  */
163 void MEDCouplingUMesh::checkCoherency() const
164 {
165   if(_mesh_dim<-1)
166     throw INTERP_KERNEL::Exception("No mesh dimension specified !");
167   if(_mesh_dim!=-1)
168     MEDCouplingPointSet::checkCoherency();
169   for(std::set<INTERP_KERNEL::NormalizedCellType>::const_iterator iter=_types.begin();iter!=_types.end();iter++)
170     {
171       if((int)INTERP_KERNEL::CellModel::GetCellModel(*iter).getDimension()!=_mesh_dim)
172         {
173           std::ostringstream message;
174           message << "Mesh invalid because dimension is " << _mesh_dim << " and there is presence of cell(s) with type " << (*iter);
175           throw INTERP_KERNEL::Exception(message.str().c_str());
176         }
177     }
178   if(_nodal_connec)
179     {
180       if(_nodal_connec->getNumberOfComponents()!=1)
181         throw INTERP_KERNEL::Exception("Nodal connectivity array is expected to be with number of components set to one !");
182       if(_nodal_connec->getInfoOnComponent(0)!="")
183         throw INTERP_KERNEL::Exception("Nodal connectivity array is expected to have no info on its single component !");
184     }
185   else
186     if(_mesh_dim!=-1)
187       throw INTERP_KERNEL::Exception("Nodal connectivity array is not defined !");
188   if(_nodal_connec_index)
189     {
190       if(_nodal_connec_index->getNumberOfComponents()!=1)
191         throw INTERP_KERNEL::Exception("Nodal connectivity index array is expected to be with number of components set to one !");
192       if(_nodal_connec_index->getInfoOnComponent(0)!="")
193         throw INTERP_KERNEL::Exception("Nodal connectivity index array is expected to have no info on its single component !");
194     }
195   else
196     if(_mesh_dim!=-1)
197       throw INTERP_KERNEL::Exception("Nodal connectivity index array is not defined !");
198 }
199
200 /*!
201  * Checks if \a this mesh is well defined. If no exception is thrown by this method,
202  * then \a this mesh is most probably is writable, exchangeable and available for all
203  * algorithms. <br> In addition to the checks performed by checkCoherency(), this
204  * method thoroughly checks the nodal connectivity.
205  *  \param [in] eps - a not used parameter.
206  *  \throw If the mesh dimension is not set.
207  *  \throw If the coordinates array is not set (if mesh dimension != -1 ).
208  *  \throw If \a this mesh contains elements of dimension different from the mesh dimension.
209  *  \throw If the connectivity data array has more than one component.
210  *  \throw If the connectivity data array has a named component.
211  *  \throw If the connectivity index data array has more than one component.
212  *  \throw If the connectivity index data array has a named component.
213  *  \throw If number of nodes defining an element does not correspond to the type of element.
214  *  \throw If the nodal connectivity includes an invalid node id.
215  */
216 void MEDCouplingUMesh::checkCoherency1(double eps) const
217 {
218   checkCoherency();
219   if(_mesh_dim==-1)
220     return ;
221   int meshDim=getMeshDimension();
222   int nbOfNodes=getNumberOfNodes();
223   int nbOfCells=getNumberOfCells();
224   const int *ptr=_nodal_connec->getConstPointer();
225   const int *ptrI=_nodal_connec_index->getConstPointer();
226   for(int i=0;i<nbOfCells;i++)
227     {
228       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)ptr[ptrI[i]]);
229       if((int)cm.getDimension()!=meshDim)
230         {
231           std::ostringstream oss;
232           oss << "MEDCouplingUMesh::checkCoherency1 : cell << #" << i<< " with type Type " << cm.getRepr() << " in 'this' whereas meshdim == " << meshDim << " !";
233           throw INTERP_KERNEL::Exception(oss.str().c_str());
234         }
235       int nbOfNodesInCell=ptrI[i+1]-ptrI[i]-1;
236       if(!cm.isDynamic())
237         if(nbOfNodesInCell!=(int)cm.getNumberOfNodes())
238           {
239             std::ostringstream oss;
240             oss << "MEDCouplingUMesh::checkCoherency1 : cell #" << i << " with static Type '" << cm.getRepr() << "' has " <<  cm.getNumberOfNodes();
241             oss << " nodes whereas in connectivity there is " << nbOfNodesInCell << " nodes ! Looks very bad !";
242             throw INTERP_KERNEL::Exception(oss.str().c_str());
243           }
244       for(const int *w=ptr+ptrI[i]+1;w!=ptr+ptrI[i+1];w++)
245         {
246           int nodeId=*w;
247           if(nodeId>=0)
248             {
249               if(nodeId>=nbOfNodes)
250                 {
251                   std::ostringstream oss; oss << "Cell #" << i << " is consituted of node #" << nodeId << " whereas there are only " << nbOfNodes << " nodes !";
252                   throw INTERP_KERNEL::Exception(oss.str().c_str());
253                 }
254             }
255           else if(nodeId<-1)
256             {
257               std::ostringstream oss; oss << "Cell #" << i << " is consituted of node #" << nodeId << " in connectivity ! sounds bad !";
258               throw INTERP_KERNEL::Exception(oss.str().c_str());
259             }
260           else
261             {
262               if((INTERP_KERNEL::NormalizedCellType)(ptr[ptrI[i]])!=INTERP_KERNEL::NORM_POLYHED)
263                 {
264                   std::ostringstream oss; oss << "Cell #" << i << " is consituted of node #-1 in connectivity ! sounds bad !";
265                   throw INTERP_KERNEL::Exception(oss.str().c_str());
266                 }
267             }
268         }
269     }
270 }
271
272
273 /*!
274  * Checks if \a this mesh is well defined. If no exception is thrown by this method,
275  * then \a this mesh is most probably is writable, exchangeable and available for all
276  * algorithms. <br> This method performs the same checks as checkCoherency1() does. 
277  *  \param [in] eps - a not used parameter.
278  *  \throw If the mesh dimension is not set.
279  *  \throw If the coordinates array is not set (if mesh dimension != -1 ).
280  *  \throw If \a this mesh contains elements of dimension different from the mesh dimension.
281  *  \throw If the connectivity data array has more than one component.
282  *  \throw If the connectivity data array has a named component.
283  *  \throw If the connectivity index data array has more than one component.
284  *  \throw If the connectivity index data array has a named component.
285  *  \throw If number of nodes defining an element does not correspond to the type of element.
286  *  \throw If the nodal connectivity includes an invalid node id.
287  */
288 void MEDCouplingUMesh::checkCoherency2(double eps) const
289 {
290   checkCoherency1(eps);
291 }
292
293 /*!
294  * Sets dimension of \a this mesh. The mesh dimension in general depends on types of
295  * elements contained in the mesh. For more info on the mesh dimension see
296  * \ref MEDCouplingUMeshPage.
297  *  \param [in] meshDim - a new mesh dimension.
298  *  \throw If \a meshDim is invalid. A valid range is <em> -1 <= meshDim <= 3</em>.
299  */
300 void MEDCouplingUMesh::setMeshDimension(int meshDim)
301 {
302   if(meshDim<-1 || meshDim>3)
303     throw INTERP_KERNEL::Exception("Invalid meshDim specified ! Must be greater or equal to -1 and lower or equal to 3 !");
304   _mesh_dim=meshDim;
305   declareAsNew();
306 }
307
308 /*!
309  * Allocates memory to store an estimation of the given number of cells. Closer is the estimation to the number of cells effectively inserted,
310  * less will be the needs to realloc. If the number of cells to be inserted is not known simply put 0 to this parameter.
311  * If a nodal connectivity previouly existed before the call of this method, it will be reset.
312  *
313  *  \param [in] nbOfCells - estimation of the number of cell \a this mesh will contain.
314  *
315  *  \if ENABLE_EXAMPLES
316  *  \ref medcouplingcppexamplesUmeshStdBuild1 "Here is a C++ example".<br>
317  *  \ref medcouplingpyexamplesUmeshStdBuild1 "Here is a Python example".
318  *  \endif
319  */
320 void MEDCouplingUMesh::allocateCells(int nbOfCells)
321 {
322   if(nbOfCells<0)
323     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::allocateCells : the input number of cells should be >= 0 !");
324   if(_nodal_connec_index)
325     {
326       _nodal_connec_index->decrRef();
327     }
328   if(_nodal_connec)
329     {
330       _nodal_connec->decrRef();
331     }
332   _nodal_connec_index=DataArrayInt::New();
333   _nodal_connec_index->reserve(nbOfCells+1);
334   _nodal_connec_index->pushBackSilent(0);
335   _nodal_connec=DataArrayInt::New();
336   _nodal_connec->reserve(2*nbOfCells);
337   _types.clear();
338   declareAsNew();
339 }
340
341 /*!
342  * Appends a cell to the connectivity array. For deeper understanding what is
343  * happening see \ref MEDCouplingUMeshNodalConnectivity.
344  *  \param [in] type - type of cell to add.
345  *  \param [in] size - number of nodes constituting this cell.
346  *  \param [in] nodalConnOfCell - the connectivity of the cell to add.
347  * 
348  *  \if ENABLE_EXAMPLES
349  *  \ref medcouplingcppexamplesUmeshStdBuild1 "Here is a C++ example".<br>
350  *  \ref medcouplingpyexamplesUmeshStdBuild1 "Here is a Python example".
351  *  \endif
352  */
353 void MEDCouplingUMesh::insertNextCell(INTERP_KERNEL::NormalizedCellType type, int size, const int *nodalConnOfCell)
354 {
355   const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(type);
356   if(_nodal_connec_index==0)
357     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::insertNextCell : nodal connectivity not set ! invoke allocateCells before calling insertNextCell !");
358   if((int)cm.getDimension()==_mesh_dim)
359     {
360       if(!cm.isDynamic())
361         if(size!=(int)cm.getNumberOfNodes())
362           {
363             std::ostringstream oss; oss << "MEDCouplingUMesh::insertNextCell : Trying to push a " << cm.getRepr() << " cell with a size of " << size;
364             oss << " ! Expecting " << cm.getNumberOfNodes() << " !";
365             throw INTERP_KERNEL::Exception(oss.str().c_str());
366           }
367       int idx=_nodal_connec_index->back();
368       int val=idx+size+1;
369       _nodal_connec_index->pushBackSilent(val);
370       _nodal_connec->writeOnPlace(idx,type,nodalConnOfCell,size);
371       _types.insert(type);
372     }
373   else
374     {
375       std::ostringstream oss; oss << "MEDCouplingUMesh::insertNextCell : cell type " << cm.getRepr() << " has a dimension " << cm.getDimension();
376       oss << " whereas Mesh Dimension of current UMesh instance is set to " << _mesh_dim << " ! Please invoke \"setMeshDimension\" method before or invoke ";
377       oss << "\"MEDCouplingUMesh::New\" static method with 2 parameters name and meshDimension !";
378       throw INTERP_KERNEL::Exception(oss.str().c_str());
379     }
380 }
381
382 /*!
383  * Compacts data arrays to release unused memory. This method is to be called after
384  * finishing cell insertion using \a this->insertNextCell().
385  * 
386  *  \if ENABLE_EXAMPLES
387  *  \ref medcouplingcppexamplesUmeshStdBuild1 "Here is a C++ example".<br>
388  *  \ref medcouplingpyexamplesUmeshStdBuild1 "Here is a Python example".
389  *  \endif
390  */
391 void MEDCouplingUMesh::finishInsertingCells()
392 {
393   _nodal_connec->pack();
394   _nodal_connec_index->pack();
395   _nodal_connec->declareAsNew();
396   _nodal_connec_index->declareAsNew();
397   updateTime();
398 }
399
400 /*!
401  * Entry point for iteration over cells of this. Warning the returned cell iterator should be deallocated.
402  * Useful for python users.
403  */
404 MEDCouplingUMeshCellIterator *MEDCouplingUMesh::cellIterator()
405 {
406   return new MEDCouplingUMeshCellIterator(this);
407 }
408
409 /*!
410  * Entry point for iteration over cells groups geo types per geotypes. Warning the returned cell iterator should be deallocated.
411  * If \a this is not so that that cells are grouped by geo types this method will throw an exception.
412  * In this case MEDCouplingUMesh::sortCellsInMEDFileFrmt or MEDCouplingUMesh::rearrange2ConsecutiveCellTypes methods for example can be called before invoking this method.
413  * Useful for python users.
414  */
415 MEDCouplingUMeshCellByTypeEntry *MEDCouplingUMesh::cellsByType()
416 {
417   if(!checkConsecutiveCellTypes())
418     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::cellsByType : this mesh is not sorted by type !");
419   return new MEDCouplingUMeshCellByTypeEntry(this);
420 }
421
422 /*!
423  * Returns a set of all cell types available in \a this mesh.
424  * \return std::set<INTERP_KERNEL::NormalizedCellType> - the set of cell types.
425  * \warning this method does not throw any exception even if \a this is not defined.
426  * \sa MEDCouplingUMesh::getAllGeoTypesSorted
427  */
428 std::set<INTERP_KERNEL::NormalizedCellType> MEDCouplingUMesh::getAllGeoTypes() const
429 {
430   return _types;
431 }
432
433 /*!
434  * This method returns the sorted list of geometric types in \a this.
435  * Sorted means in the same order than the cells in \a this. A single entry in return vector means the maximal chunk of consecutive cells in \a this
436  * having the same geometric type. So a same geometric type can appear more than once if the cells are not sorted per geometric type.
437  *
438  * \throw if connectivity in \a this is not correctly defined.
439  *  
440  * \sa MEDCouplingMesh::getAllGeoTypes
441  */
442 std::vector<INTERP_KERNEL::NormalizedCellType> MEDCouplingUMesh::getAllGeoTypesSorted() const
443 {
444   std::vector<INTERP_KERNEL::NormalizedCellType> ret;
445   checkConnectivityFullyDefined();
446   int nbOfCells(getNumberOfCells());
447   if(nbOfCells==0)
448     return ret;
449   if(getMeshLength()<1)
450     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getAllGeoTypesSorted : the connectivity in this seems invalid !");
451   const int *c(_nodal_connec->begin()),*ci(_nodal_connec_index->begin());
452   ret.push_back((INTERP_KERNEL::NormalizedCellType)c[*ci++]);
453   for(int i=1;i<nbOfCells;i++,ci++)
454     if(ret.back()!=((INTERP_KERNEL::NormalizedCellType)c[*ci]))
455       ret.push_back((INTERP_KERNEL::NormalizedCellType)c[*ci]);
456   return ret;
457 }
458
459 /*!
460  * This method is a method that compares \a this and \a other.
461  * This method compares \b all attributes, even names and component names.
462  */
463 bool MEDCouplingUMesh::isEqualIfNotWhy(const MEDCouplingMesh *other, double prec, std::string& reason) const
464 {
465   if(!other)
466     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::isEqualIfNotWhy : input other pointer is null !");
467   std::ostringstream oss; oss.precision(15);
468   const MEDCouplingUMesh *otherC=dynamic_cast<const MEDCouplingUMesh *>(other);
469   if(!otherC)
470     {
471       reason="mesh given in input is not castable in MEDCouplingUMesh !";
472       return false;
473     }
474   if(!MEDCouplingPointSet::isEqualIfNotWhy(other,prec,reason))
475     return false;
476   if(_mesh_dim!=otherC->_mesh_dim)
477     {
478       oss << "umesh dimension mismatch : this mesh dimension=" << _mesh_dim << " other mesh dimension=" <<  otherC->_mesh_dim;
479       reason=oss.str();
480       return false;
481     }
482   if(_types!=otherC->_types)
483     {
484       oss << "umesh geometric type mismatch :\nThis geometric types are :";
485       for(std::set<INTERP_KERNEL::NormalizedCellType>::const_iterator iter=_types.begin();iter!=_types.end();iter++)
486         { const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(*iter); oss << cm.getRepr() << ", "; }
487       oss << "\nOther geometric types are :";
488       for(std::set<INTERP_KERNEL::NormalizedCellType>::const_iterator iter=otherC->_types.begin();iter!=otherC->_types.end();iter++)
489         { const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(*iter); oss << cm.getRepr() << ", "; }
490       reason=oss.str();
491       return false;
492     }
493   if(_nodal_connec!=0 || otherC->_nodal_connec!=0)
494     if(_nodal_connec==0 || otherC->_nodal_connec==0)
495       {
496         reason="Only one UMesh between the two this and other has its nodal connectivity DataArrayInt defined !";
497         return false;
498       }
499   if(_nodal_connec!=otherC->_nodal_connec)
500     if(!_nodal_connec->isEqualIfNotWhy(*otherC->_nodal_connec,reason))
501       {
502         reason.insert(0,"Nodal connectivity DataArrayInt differ : ");
503         return false;
504       }
505   if(_nodal_connec_index!=0 || otherC->_nodal_connec_index!=0)
506     if(_nodal_connec_index==0 || otherC->_nodal_connec_index==0)
507       {
508         reason="Only one UMesh between the two this and other has its nodal connectivity index DataArrayInt defined !";
509         return false;
510       }
511   if(_nodal_connec_index!=otherC->_nodal_connec_index)
512     if(!_nodal_connec_index->isEqualIfNotWhy(*otherC->_nodal_connec_index,reason))
513       {
514         reason.insert(0,"Nodal connectivity index DataArrayInt differ : ");
515         return false;
516       }
517   return true;
518 }
519
520 /*!
521  * Checks if data arrays of this mesh (node coordinates, nodal
522  * connectivity of cells, etc) of two meshes are same. Textual data like name etc. are
523  * not considered.
524  *  \param [in] other - the mesh to compare with.
525  *  \param [in] prec - precision value used to compare node coordinates.
526  *  \return bool - \a true if the two meshes are same.
527  */
528 bool MEDCouplingUMesh::isEqualWithoutConsideringStr(const MEDCouplingMesh *other, double prec) const
529 {
530   const MEDCouplingUMesh *otherC=dynamic_cast<const MEDCouplingUMesh *>(other);
531   if(!otherC)
532     return false;
533   if(!MEDCouplingPointSet::isEqualWithoutConsideringStr(other,prec))
534     return false;
535   if(_mesh_dim!=otherC->_mesh_dim)
536     return false;
537   if(_types!=otherC->_types)
538     return false;
539   if(_nodal_connec!=0 || otherC->_nodal_connec!=0)
540     if(_nodal_connec==0 || otherC->_nodal_connec==0)
541       return false;
542   if(_nodal_connec!=otherC->_nodal_connec)
543     if(!_nodal_connec->isEqualWithoutConsideringStr(*otherC->_nodal_connec))
544       return false;
545   if(_nodal_connec_index!=0 || otherC->_nodal_connec_index!=0)
546     if(_nodal_connec_index==0 || otherC->_nodal_connec_index==0)
547       return false;
548   if(_nodal_connec_index!=otherC->_nodal_connec_index)
549     if(!_nodal_connec_index->isEqualWithoutConsideringStr(*otherC->_nodal_connec_index))
550       return false;
551   return true;
552 }
553
554 /*!
555  * Checks if \a this and \a other meshes are geometrically equivalent with high
556  * probability, else an exception is thrown. The meshes are considered equivalent if
557  * (1) meshes contain the same number of nodes and the same number of elements of the
558  * same types (2) three cells of the two meshes (first, last and middle) are based
559  * on coincident nodes (with a specified precision).
560  *  \param [in] other - the mesh to compare with.
561  *  \param [in] prec - the precision used to compare nodes of the two meshes.
562  *  \throw If the two meshes do not match.
563  */
564 void MEDCouplingUMesh::checkFastEquivalWith(const MEDCouplingMesh *other, double prec) const
565 {
566   MEDCouplingPointSet::checkFastEquivalWith(other,prec);
567   const MEDCouplingUMesh *otherC=dynamic_cast<const MEDCouplingUMesh *>(other);
568   if(!otherC)
569     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::checkFastEquivalWith : Two meshes are not not unstructured !"); 
570 }
571
572 /*!
573  * Returns the reverse nodal connectivity. The reverse nodal connectivity enumerates
574  * cells each node belongs to.
575  * \warning For speed reasons, this method does not check if node ids in the nodal
576  *          connectivity correspond to the size of node coordinates array.
577  * \param [in,out] revNodal - an array holding ids of cells sharing each node.
578  * \param [in,out] revNodalIndx - an array, of length \a this->getNumberOfNodes() + 1,
579  *        dividing cell ids in \a revNodal into groups each referring to one
580  *        node. Its every element (except the last one) is an index pointing to the
581  *         first id of a group of cells. For example cells sharing the node #1 are 
582  *        described by following range of indices: 
583  *        [ \a revNodalIndx[1], \a revNodalIndx[2] ) and the cell ids are
584  *        \a revNodal[ \a revNodalIndx[1] ], \a revNodal[ \a revNodalIndx[1] + 1], ...
585  *        Number of cells sharing the *i*-th node is
586  *        \a revNodalIndx[ *i*+1 ] - \a revNodalIndx[ *i* ].
587  * \throw If the coordinates array is not set.
588  * \throw If the nodal connectivity of cells is not defined.
589  * 
590  * \if ENABLE_EXAMPLES
591  * \ref cpp_mcumesh_getReverseNodalConnectivity "Here is a C++ example".<br>
592  * \ref  py_mcumesh_getReverseNodalConnectivity "Here is a Python example".
593  * \endif
594  */
595 void MEDCouplingUMesh::getReverseNodalConnectivity(DataArrayInt *revNodal, DataArrayInt *revNodalIndx) const
596 {
597   checkFullyDefined();
598   int nbOfNodes=getNumberOfNodes();
599   int *revNodalIndxPtr=(int *)malloc((nbOfNodes+1)*sizeof(int));
600   revNodalIndx->useArray(revNodalIndxPtr,true,C_DEALLOC,nbOfNodes+1,1);
601   std::fill(revNodalIndxPtr,revNodalIndxPtr+nbOfNodes+1,0);
602   const int *conn=_nodal_connec->getConstPointer();
603   const int *connIndex=_nodal_connec_index->getConstPointer();
604   int nbOfCells=getNumberOfCells();
605   int nbOfEltsInRevNodal=0;
606   for(int eltId=0;eltId<nbOfCells;eltId++)
607     {
608       const int *strtNdlConnOfCurCell=conn+connIndex[eltId]+1;
609       const int *endNdlConnOfCurCell=conn+connIndex[eltId+1];
610       for(const int *iter=strtNdlConnOfCurCell;iter!=endNdlConnOfCurCell;iter++)
611         if(*iter>=0)//for polyhedrons
612           {
613             nbOfEltsInRevNodal++;
614             revNodalIndxPtr[(*iter)+1]++;
615           }
616     }
617   std::transform(revNodalIndxPtr+1,revNodalIndxPtr+nbOfNodes+1,revNodalIndxPtr,revNodalIndxPtr+1,std::plus<int>());
618   int *revNodalPtr=(int *)malloc((nbOfEltsInRevNodal)*sizeof(int));
619   revNodal->useArray(revNodalPtr,true,C_DEALLOC,nbOfEltsInRevNodal,1);
620   std::fill(revNodalPtr,revNodalPtr+nbOfEltsInRevNodal,-1);
621   for(int eltId=0;eltId<nbOfCells;eltId++)
622     {
623       const int *strtNdlConnOfCurCell=conn+connIndex[eltId]+1;
624       const int *endNdlConnOfCurCell=conn+connIndex[eltId+1];
625       for(const int *iter=strtNdlConnOfCurCell;iter!=endNdlConnOfCurCell;iter++)
626         if(*iter>=0)//for polyhedrons
627           *std::find_if(revNodalPtr+revNodalIndxPtr[*iter],revNodalPtr+revNodalIndxPtr[*iter+1],std::bind2nd(std::equal_to<int>(),-1))=eltId;
628     }
629 }
630
631 /// @cond INTERNAL
632
633 int MEDCouplingFastNbrer(int id, unsigned nb, const INTERP_KERNEL::CellModel& cm, bool compute, const int *conn1, const int *conn2)
634 {
635   return id;
636 }
637
638 int MEDCouplingOrientationSensitiveNbrer(int id, unsigned nb, const INTERP_KERNEL::CellModel& cm, bool compute, const int *conn1, const int *conn2)
639 {
640   if(!compute)
641     return id+1;
642   else
643     {
644       if(cm.getOrientationStatus(nb,conn1,conn2))
645         return id+1;
646       else
647         return -(id+1);
648     }
649 }
650
651 class MinusOneSonsGenerator
652 {
653 public:
654   MinusOneSonsGenerator(const INTERP_KERNEL::CellModel& cm):_cm(cm) { }
655   unsigned getNumberOfSons2(const int *conn, int lgth) const { return _cm.getNumberOfSons2(conn,lgth); }
656   unsigned fillSonCellNodalConnectivity2(int sonId, const int *nodalConn, int lgth, int *sonNodalConn, INTERP_KERNEL::NormalizedCellType& typeOfSon) const { return _cm.fillSonCellNodalConnectivity2(sonId,nodalConn,lgth,sonNodalConn,typeOfSon); }
657   static const int DELTA=1;
658 private:
659   const INTERP_KERNEL::CellModel& _cm;
660 };
661
662 class MinusOneSonsGeneratorBiQuadratic
663 {
664 public:
665   MinusOneSonsGeneratorBiQuadratic(const INTERP_KERNEL::CellModel& cm):_cm(cm) { }
666   unsigned getNumberOfSons2(const int *conn, int lgth) const { return _cm.getNumberOfSons2(conn,lgth); }
667   unsigned fillSonCellNodalConnectivity2(int sonId, const int *nodalConn, int lgth, int *sonNodalConn, INTERP_KERNEL::NormalizedCellType& typeOfSon) const { return _cm.fillSonCellNodalConnectivity4(sonId,nodalConn,lgth,sonNodalConn,typeOfSon); }
668   static const int DELTA=1;
669 private:
670   const INTERP_KERNEL::CellModel& _cm;
671 };
672
673 class MinusTwoSonsGenerator
674 {
675 public:
676   MinusTwoSonsGenerator(const INTERP_KERNEL::CellModel& cm):_cm(cm) { }
677   unsigned getNumberOfSons2(const int *conn, int lgth) const { return _cm.getNumberOfEdgesIn3D(conn,lgth); }
678   unsigned fillSonCellNodalConnectivity2(int sonId, const int *nodalConn, int lgth, int *sonNodalConn, INTERP_KERNEL::NormalizedCellType& typeOfSon) const { return _cm.fillSonEdgesNodalConnectivity3D(sonId,nodalConn,lgth,sonNodalConn,typeOfSon); }
679   static const int DELTA=2;
680 private:
681   const INTERP_KERNEL::CellModel& _cm;
682 };
683
684 /// @endcond
685
686 /*!
687  * Creates a new MEDCouplingUMesh containing cells, of dimension one less than \a
688  * this->getMeshDimension(), that bound cells of \a this mesh. In addition arrays
689  * describing correspondence between cells of \a this and the result meshes are
690  * returned. The arrays \a desc and \a descIndx describe the descending connectivity,
691  * i.e. enumerate cells of the result mesh bounding each cell of \a this mesh. The
692  * arrays \a revDesc and \a revDescIndx describe the reverse descending connectivity,
693  * i.e. enumerate cells of  \a this mesh bounded by each cell of the result mesh. 
694  * \warning For speed reasons, this method does not check if node ids in the nodal
695  *          connectivity correspond to the size of node coordinates array.
696  * \warning Cells of the result mesh are \b not sorted by geometric type, hence,
697  *          to write this mesh to the MED file, its cells must be sorted using
698  *          sortCellsInMEDFileFrmt().
699  *  \param [in,out] desc - the array containing cell ids of the result mesh bounding
700  *         each cell of \a this mesh.
701  *  \param [in,out] descIndx - the array, of length \a this->getNumberOfCells() + 1,
702  *        dividing cell ids in \a desc into groups each referring to one
703  *        cell of \a this mesh. Its every element (except the last one) is an index
704  *        pointing to the first id of a group of cells. For example cells of the
705  *        result mesh bounding the cell #1 of \a this mesh are described by following
706  *        range of indices:
707  *        [ \a descIndx[1], \a descIndx[2] ) and the cell ids are
708  *        \a desc[ \a descIndx[1] ], \a desc[ \a descIndx[1] + 1], ...
709  *        Number of cells of the result mesh sharing the *i*-th cell of \a this mesh is
710  *        \a descIndx[ *i*+1 ] - \a descIndx[ *i* ].
711  *  \param [in,out] revDesc - the array containing cell ids of \a this mesh bounded
712  *         by each cell of the result mesh.
713  *  \param [in,out] revDescIndx - the array, of length one more than number of cells
714  *        in the result mesh,
715  *        dividing cell ids in \a revDesc into groups each referring to one
716  *        cell of the result mesh the same way as \a descIndx divides \a desc.
717  *  \return MEDCouplingUMesh * - a new instance of MEDCouplingUMesh. The caller is to
718  *        delete this mesh using decrRef() as it is no more needed.
719  *  \throw If the coordinates array is not set.
720  *  \throw If the nodal connectivity of cells is node defined.
721  *  \throw If \a desc == NULL || \a descIndx == NULL || \a revDesc == NULL || \a
722  *         revDescIndx == NULL.
723  * 
724  *  \if ENABLE_EXAMPLES
725  *  \ref cpp_mcumesh_buildDescendingConnectivity "Here is a C++ example".<br>
726  *  \ref  py_mcumesh_buildDescendingConnectivity "Here is a Python example".
727  *  \endif
728  * \sa buildDescendingConnectivity2()
729  */
730 MEDCouplingUMesh *MEDCouplingUMesh::buildDescendingConnectivity(DataArrayInt *desc, DataArrayInt *descIndx, DataArrayInt *revDesc, DataArrayInt *revDescIndx) const
731 {
732   return buildDescendingConnectivityGen<MinusOneSonsGenerator>(desc,descIndx,revDesc,revDescIndx,MEDCouplingFastNbrer);
733 }
734
735 /*!
736  * \a this has to have a mesh dimension equal to 3. If it is not the case an INTERP_KERNEL::Exception will be thrown.
737  * This behaves exactly as MEDCouplingUMesh::buildDescendingConnectivity does except that this method compute directly the transition from mesh dimension 3 to sub edges (dimension 1)
738  * in one shot. That is to say that this method is equivalent to 2 successive calls to MEDCouplingUMesh::buildDescendingConnectivity.
739  * This method returns 4 arrays and a mesh as MEDCouplingUMesh::buildDescendingConnectivity does.
740  * \sa MEDCouplingUMesh::buildDescendingConnectivity
741  */
742 MEDCouplingUMesh *MEDCouplingUMesh::explode3DMeshTo1D(DataArrayInt *desc, DataArrayInt *descIndx, DataArrayInt *revDesc, DataArrayInt *revDescIndx) const
743 {
744   checkFullyDefined();
745   if(getMeshDimension()!=3)
746     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::explode3DMeshTo1D : This has to have a mesh dimension to 3 !");
747   return buildDescendingConnectivityGen<MinusTwoSonsGenerator>(desc,descIndx,revDesc,revDescIndx,MEDCouplingFastNbrer);
748 }
749
750 /*!
751  * Creates a new MEDCouplingUMesh containing cells, of dimension one less than \a
752  * this->getMeshDimension(), that bound cells of \a this mesh. In
753  * addition arrays describing correspondence between cells of \a this and the result
754  * meshes are returned. The arrays \a desc and \a descIndx describe the descending
755  * connectivity, i.e. enumerate cells of the result mesh bounding each cell of \a this
756  *  mesh. This method differs from buildDescendingConnectivity() in that apart
757  * from cell ids, \a desc returns mutual orientation of cells in \a this and the
758  * result meshes. So a positive id means that order of nodes in corresponding cells
759  * of two meshes is same, and a negative id means a reverse order of nodes. Since a
760  * cell with id #0 can't be negative, the array \a desc returns ids in FORTRAN mode,
761  * i.e. cell ids are one-based.
762  * Arrays \a revDesc and \a revDescIndx describe the reverse descending connectivity,
763  * i.e. enumerate cells of  \a this mesh bounded by each cell of the result mesh. 
764  * \warning For speed reasons, this method does not check if node ids in the nodal
765  *          connectivity correspond to the size of node coordinates array.
766  * \warning Cells of the result mesh are \b not sorted by geometric type, hence,
767  *          to write this mesh to the MED file, its cells must be sorted using
768  *          sortCellsInMEDFileFrmt().
769  *  \param [in,out] desc - the array containing cell ids of the result mesh bounding
770  *         each cell of \a this mesh.
771  *  \param [in,out] descIndx - the array, of length \a this->getNumberOfCells() + 1,
772  *        dividing cell ids in \a desc into groups each referring to one
773  *        cell of \a this mesh. Its every element (except the last one) is an index
774  *        pointing to the first id of a group of cells. For example cells of the
775  *        result mesh bounding the cell #1 of \a this mesh are described by following
776  *        range of indices:
777  *        [ \a descIndx[1], \a descIndx[2] ) and the cell ids are
778  *        \a desc[ \a descIndx[1] ], \a desc[ \a descIndx[1] + 1], ...
779  *        Number of cells of the result mesh sharing the *i*-th cell of \a this mesh is
780  *        \a descIndx[ *i*+1 ] - \a descIndx[ *i* ].
781  *  \param [in,out] revDesc - the array containing cell ids of \a this mesh bounded
782  *         by each cell of the result mesh.
783  *  \param [in,out] revDescIndx - the array, of length one more than number of cells
784  *        in the result mesh,
785  *        dividing cell ids in \a revDesc into groups each referring to one
786  *        cell of the result mesh the same way as \a descIndx divides \a desc.
787  *  \return MEDCouplingUMesh * - a new instance of MEDCouplingUMesh. This result mesh
788  *        shares the node coordinates array with \a this mesh. The caller is to
789  *        delete this mesh using decrRef() as it is no more needed.
790  *  \throw If the coordinates array is not set.
791  *  \throw If the nodal connectivity of cells is node defined.
792  *  \throw If \a desc == NULL || \a descIndx == NULL || \a revDesc == NULL || \a
793  *         revDescIndx == NULL.
794  * 
795  *  \if ENABLE_EXAMPLES
796  *  \ref cpp_mcumesh_buildDescendingConnectivity2 "Here is a C++ example".<br>
797  *  \ref  py_mcumesh_buildDescendingConnectivity2 "Here is a Python example".
798  *  \endif
799  * \sa buildDescendingConnectivity()
800  */
801 MEDCouplingUMesh *MEDCouplingUMesh::buildDescendingConnectivity2(DataArrayInt *desc, DataArrayInt *descIndx, DataArrayInt *revDesc, DataArrayInt *revDescIndx) const
802 {
803   return buildDescendingConnectivityGen<MinusOneSonsGenerator>(desc,descIndx,revDesc,revDescIndx,MEDCouplingOrientationSensitiveNbrer);
804 }
805
806 /*!
807  * \b WARNING this method do the assumption that connectivity lies on the coordinates set.
808  * For speed reasons no check of this will be done. This method calls MEDCouplingUMesh::buildDescendingConnectivity to compute the result.
809  * This method lists cell by cell in \b this which are its neighbors. To compute the result only connectivities are considered.
810  * The neighbor cells of cell having id 'cellId' are neighbors[neighborsIndx[cellId]:neighborsIndx[cellId+1]].
811  *
812  * \param [out] neighbors is an array storing all the neighbors of all cells in \b this. This array is newly allocated and should be dealt by the caller. \b neighborsIndx 2nd output
813  *                        parameter allows to select the right part in this array. The number of tuples is equal to the last values in \b neighborsIndx.
814  * \param [out] neighborsIndx is an array of size this->getNumberOfCells()+1 newly allocated and should be dealt by the caller. This arrays allow to use the first output parameter \b neighbors.
815  */
816 void MEDCouplingUMesh::computeNeighborsOfCells(DataArrayInt *&neighbors, DataArrayInt *&neighborsIndx) const
817 {
818   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> desc=DataArrayInt::New();
819   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> descIndx=DataArrayInt::New();
820   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revDesc=DataArrayInt::New();
821   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revDescIndx=DataArrayInt::New();
822   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> meshDM1=buildDescendingConnectivity(desc,descIndx,revDesc,revDescIndx);
823   meshDM1=0;
824   ComputeNeighborsOfCellsAdv(desc,descIndx,revDesc,revDescIndx,neighbors,neighborsIndx);
825 }
826
827 /*!
828  * This method is called by MEDCouplingUMesh::computeNeighborsOfCells. This methods performs the algorithm of MEDCouplingUMesh::computeNeighborsOfCells.
829  * This method is useful for users that want to reduce along a criterion the set of neighbours cell. This is typically the case to extract a set a neighbours,
830  * excluding a set of meshdim-1 cells in input descending connectivity.
831  * Typically \b desc, \b descIndx, \b revDesc and \b revDescIndx input params are the result of MEDCouplingUMesh::buildDescendingConnectivity.
832  * This method lists cell by cell in \b this which are its neighbors. To compute the result only connectivities are considered.
833  * The neighbor cells of cell having id 'cellId' are neighbors[neighborsIndx[cellId]:neighborsIndx[cellId+1]].
834  *
835  * \param [in] desc descending connectivity array.
836  * \param [in] descIndx descending connectivity index array used to walk through \b desc.
837  * \param [in] revDesc reverse descending connectivity array.
838  * \param [in] revDescIndx reverse descending connectivity index array used to walk through \b revDesc.
839  * \param [out] neighbors is an array storing all the neighbors of all cells in \b this. This array is newly allocated and should be dealt by the caller. \b neighborsIndx 2nd output
840  *                        parameter allows to select the right part in this array. The number of tuples is equal to the last values in \b neighborsIndx.
841  * \param [out] neighborsIndx is an array of size this->getNumberOfCells()+1 newly allocated and should be dealt by the caller. This arrays allow to use the first output parameter \b neighbors.
842  */
843 void MEDCouplingUMesh::ComputeNeighborsOfCellsAdv(const DataArrayInt *desc, const DataArrayInt *descIndx, const DataArrayInt *revDesc, const DataArrayInt *revDescIndx,
844                                                   DataArrayInt *&neighbors, DataArrayInt *&neighborsIndx)
845 {
846   if(!desc || !descIndx || !revDesc || !revDescIndx)
847     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ComputeNeighborsOfCellsAdv some input array is empty !");
848   const int *descPtr=desc->getConstPointer();
849   const int *descIPtr=descIndx->getConstPointer();
850   const int *revDescPtr=revDesc->getConstPointer();
851   const int *revDescIPtr=revDescIndx->getConstPointer();
852   //
853   int nbCells=descIndx->getNumberOfTuples()-1;
854   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> out0=DataArrayInt::New();
855   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> out1=DataArrayInt::New(); out1->alloc(nbCells+1,1);
856   int *out1Ptr=out1->getPointer();
857   *out1Ptr++=0;
858   out0->reserve(desc->getNumberOfTuples());
859   for(int i=0;i<nbCells;i++,descIPtr++,out1Ptr++)
860     {
861       for(const int *w1=descPtr+descIPtr[0];w1!=descPtr+descIPtr[1];w1++)
862         {
863           std::set<int> s(revDescPtr+revDescIPtr[*w1],revDescPtr+revDescIPtr[(*w1)+1]);
864           s.erase(i);
865           out0->insertAtTheEnd(s.begin(),s.end());
866         }
867       *out1Ptr=out0->getNumberOfTuples();
868     }
869   neighbors=out0.retn();
870   neighborsIndx=out1.retn();
871 }
872
873 /*!
874  * \b WARNING this method do the assumption that connectivity lies on the coordinates set.
875  * For speed reasons no check of this will be done. This method calls MEDCouplingUMesh::buildDescendingConnectivity to compute the result.
876  * This method lists node by node in \b this which are its neighbors. To compute the result only connectivities are considered.
877  * The neighbor nodes of node having id 'nodeId' are neighbors[neighborsIndx[cellId]:neighborsIndx[cellId+1]].
878  *
879  * \param [out] neighbors is an array storing all the neighbors of all nodes in \b this. This array is newly allocated and should be dealt by the caller. \b neighborsIndx 2nd output
880  *                        parameter allows to select the right part in this array. The number of tuples is equal to the last values in \b neighborsIndx.
881  * \param [out] neighborsIndx is an array of size this->getNumberOfCells()+1 newly allocated and should be dealt by the caller. This arrays allow to use the first output parameter \b neighbors.
882  */
883 void MEDCouplingUMesh::computeNeighborsOfNodes(DataArrayInt *&neighbors, DataArrayInt *&neighborsIdx) const
884 {
885   checkFullyDefined();
886   int mdim(getMeshDimension()),nbNodes(getNumberOfNodes());
887   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> desc(DataArrayInt::New()),descIndx(DataArrayInt::New()),revDesc(DataArrayInt::New()),revDescIndx(DataArrayInt::New());
888   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> mesh1D;
889   switch(mdim)
890   {
891     case 3:
892       {
893         mesh1D=explode3DMeshTo1D(desc,descIndx,revDesc,revDescIndx);
894         break;
895       }
896     case 2:
897       {
898         mesh1D=buildDescendingConnectivity(desc,descIndx,revDesc,revDescIndx);
899         break;
900       }
901     case 1:
902       {
903         mesh1D=const_cast<MEDCouplingUMesh *>(this);
904         mesh1D->incrRef();
905         break;
906       }
907     default:
908       {
909         throw INTERP_KERNEL::Exception("MEDCouplingUMesh::computeNeighborsOfNodes : Mesh dimension supported are [3,2,1] !");
910       }
911   }
912   desc=DataArrayInt::New(); descIndx=DataArrayInt::New(); revDesc=0; revDescIndx=0;
913   mesh1D->getReverseNodalConnectivity(desc,descIndx);
914   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret0(DataArrayInt::New());
915   ret0->alloc(desc->getNumberOfTuples(),1);
916   int *r0Pt(ret0->getPointer());
917   const int *c1DPtr(mesh1D->getNodalConnectivity()->begin()),*rn(desc->begin()),*rni(descIndx->begin());
918   for(int i=0;i<nbNodes;i++,rni++)
919     {
920       for(const int *oneDCellIt=rn+rni[0];oneDCellIt!=rn+rni[1];oneDCellIt++)
921         *r0Pt++=c1DPtr[3*(*oneDCellIt)+1]==i?c1DPtr[3*(*oneDCellIt)+2]:c1DPtr[3*(*oneDCellIt)+1];
922     }
923   neighbors=ret0.retn();
924   neighborsIdx=descIndx.retn();
925 }
926
927 /// @cond INTERNAL
928
929 /*!
930  * \b WARNING this method do the assumption that connectivity lies on the coordinates set.
931  * For speed reasons no check of this will be done.
932  */
933 template<class SonsGenerator>
934 MEDCouplingUMesh *MEDCouplingUMesh::buildDescendingConnectivityGen(DataArrayInt *desc, DataArrayInt *descIndx, DataArrayInt *revDesc, DataArrayInt *revDescIndx, DimM1DescNbrer nbrer) const
935 {
936   if(!desc || !descIndx || !revDesc || !revDescIndx)
937     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildDescendingConnectivityGen : present of a null pointer in input !");
938   checkConnectivityFullyDefined();
939   int nbOfCells=getNumberOfCells();
940   int nbOfNodes=getNumberOfNodes();
941   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revNodalIndx=DataArrayInt::New(); revNodalIndx->alloc(nbOfNodes+1,1); revNodalIndx->fillWithZero();
942   int *revNodalIndxPtr=revNodalIndx->getPointer();
943   const int *conn=_nodal_connec->getConstPointer();
944   const int *connIndex=_nodal_connec_index->getConstPointer();
945   std::string name="Mesh constituent of "; name+=getName();
946   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret=MEDCouplingUMesh::New(name,getMeshDimension()-SonsGenerator::DELTA);
947   ret->setCoords(getCoords());
948   ret->allocateCells(2*nbOfCells);
949   descIndx->alloc(nbOfCells+1,1);
950   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revDesc2(DataArrayInt::New()); revDesc2->reserve(2*nbOfCells);
951   int *descIndxPtr=descIndx->getPointer(); *descIndxPtr++=0;
952   for(int eltId=0;eltId<nbOfCells;eltId++,descIndxPtr++)
953     {
954       int pos=connIndex[eltId];
955       int posP1=connIndex[eltId+1];
956       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[pos]);
957       SonsGenerator sg(cm);
958       unsigned nbOfSons=sg.getNumberOfSons2(conn+pos+1,posP1-pos-1);
959       INTERP_KERNEL::AutoPtr<int> tmp=new int[posP1-pos];
960       for(unsigned i=0;i<nbOfSons;i++)
961         {
962           INTERP_KERNEL::NormalizedCellType cmsId;
963           unsigned nbOfNodesSon=sg.fillSonCellNodalConnectivity2(i,conn+pos+1,posP1-pos-1,tmp,cmsId);
964           for(unsigned k=0;k<nbOfNodesSon;k++)
965             if(tmp[k]>=0)
966               revNodalIndxPtr[tmp[k]+1]++;
967           ret->insertNextCell(cmsId,nbOfNodesSon,tmp);
968           revDesc2->pushBackSilent(eltId);
969         }
970       descIndxPtr[0]=descIndxPtr[-1]+(int)nbOfSons;
971     }
972   int nbOfCellsM1=ret->getNumberOfCells();
973   std::transform(revNodalIndxPtr+1,revNodalIndxPtr+nbOfNodes+1,revNodalIndxPtr,revNodalIndxPtr+1,std::plus<int>());
974   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revNodal=DataArrayInt::New(); revNodal->alloc(revNodalIndx->back(),1);
975   std::fill(revNodal->getPointer(),revNodal->getPointer()+revNodalIndx->back(),-1);
976   int *revNodalPtr=revNodal->getPointer();
977   const int *connM1=ret->getNodalConnectivity()->getConstPointer();
978   const int *connIndexM1=ret->getNodalConnectivityIndex()->getConstPointer();
979   for(int eltId=0;eltId<nbOfCellsM1;eltId++)
980     {
981       const int *strtNdlConnOfCurCell=connM1+connIndexM1[eltId]+1;
982       const int *endNdlConnOfCurCell=connM1+connIndexM1[eltId+1];
983       for(const int *iter=strtNdlConnOfCurCell;iter!=endNdlConnOfCurCell;iter++)
984         if(*iter>=0)//for polyhedrons
985           *std::find_if(revNodalPtr+revNodalIndxPtr[*iter],revNodalPtr+revNodalIndxPtr[*iter+1],std::bind2nd(std::equal_to<int>(),-1))=eltId;
986     }
987   //
988   DataArrayInt *commonCells=0,*commonCellsI=0;
989   FindCommonCellsAlg(3,0,ret->getNodalConnectivity(),ret->getNodalConnectivityIndex(),revNodal,revNodalIndx,commonCells,commonCellsI);
990   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> commonCellsTmp(commonCells),commonCellsITmp(commonCellsI);
991   const int *commonCellsPtr(commonCells->getConstPointer()),*commonCellsIPtr(commonCellsI->getConstPointer());
992   int newNbOfCellsM1=-1;
993   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> o2nM1=DataArrayInt::BuildOld2NewArrayFromSurjectiveFormat2(nbOfCellsM1,commonCells->begin(),
994                                                                                                             commonCellsI->begin(),commonCellsI->end(),newNbOfCellsM1);
995   std::vector<bool> isImpacted(nbOfCellsM1,false);
996   for(const int *work=commonCellsI->begin();work!=commonCellsI->end()-1;work++)
997     for(int work2=work[0];work2!=work[1];work2++)
998       isImpacted[commonCellsPtr[work2]]=true;
999   const int *o2nM1Ptr=o2nM1->getConstPointer();
1000   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> n2oM1=o2nM1->invertArrayO2N2N2OBis(newNbOfCellsM1);
1001   const int *n2oM1Ptr=n2oM1->getConstPointer();
1002   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret2=static_cast<MEDCouplingUMesh *>(ret->buildPartOfMySelf(n2oM1->begin(),n2oM1->end(),true));
1003   ret2->copyTinyInfoFrom(this);
1004   desc->alloc(descIndx->back(),1);
1005   int *descPtr=desc->getPointer();
1006   const INTERP_KERNEL::CellModel& cmsDft=INTERP_KERNEL::CellModel::GetCellModel(INTERP_KERNEL::NORM_POINT1);
1007   for(int i=0;i<nbOfCellsM1;i++,descPtr++)
1008     {
1009       if(!isImpacted[i])
1010         *descPtr=nbrer(o2nM1Ptr[i],0,cmsDft,false,0,0);
1011       else
1012         {
1013           if(i!=n2oM1Ptr[o2nM1Ptr[i]])
1014             {
1015               const INTERP_KERNEL::CellModel& cms=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)connM1[connIndexM1[i]]);
1016               *descPtr=nbrer(o2nM1Ptr[i],connIndexM1[i+1]-connIndexM1[i]-1,cms,true,connM1+connIndexM1[n2oM1Ptr[o2nM1Ptr[i]]]+1,connM1+connIndexM1[i]+1);
1017             }
1018           else
1019             *descPtr=nbrer(o2nM1Ptr[i],0,cmsDft,false,0,0);
1020         }
1021     }
1022   revDesc->reserve(newNbOfCellsM1);
1023   revDescIndx->alloc(newNbOfCellsM1+1,1);
1024   int *revDescIndxPtr=revDescIndx->getPointer(); *revDescIndxPtr++=0;
1025   const int *revDesc2Ptr=revDesc2->getConstPointer();
1026   for(int i=0;i<newNbOfCellsM1;i++,revDescIndxPtr++)
1027     {
1028       int oldCellIdM1=n2oM1Ptr[i];
1029       if(!isImpacted[oldCellIdM1])
1030         {
1031           revDesc->pushBackSilent(revDesc2Ptr[oldCellIdM1]);
1032           revDescIndxPtr[0]=revDescIndxPtr[-1]+1;
1033         }
1034       else
1035         {
1036           for(int j=commonCellsIPtr[0];j<commonCellsIPtr[1];j++)
1037             revDesc->pushBackSilent(revDesc2Ptr[commonCellsPtr[j]]);
1038           revDescIndxPtr[0]=revDescIndxPtr[-1]+commonCellsIPtr[1]-commonCellsIPtr[0];
1039           commonCellsIPtr++;
1040         }
1041     }
1042   //
1043   return ret2.retn();
1044 }
1045
1046 struct MEDCouplingAccVisit
1047 {
1048   MEDCouplingAccVisit():_new_nb_of_nodes(0) { }
1049   int operator()(int val) { if(val!=-1) return _new_nb_of_nodes++; else return -1; }
1050   int _new_nb_of_nodes;
1051 };
1052
1053 /// @endcond
1054
1055 /*!
1056  * Converts specified cells to either polygons (if \a this is a 2D mesh) or
1057  * polyhedrons (if \a this is a 3D mesh). The cells to convert are specified by an
1058  * array of cell ids. Pay attention that after conversion all algorithms work slower
1059  * with \a this mesh than before conversion. <br> If an exception is thrown during the
1060  * conversion due presence of invalid ids in the array of cells to convert, as a
1061  * result \a this mesh contains some already converted elements. In this case the 2D
1062  * mesh remains valid but 3D mesh becomes \b inconsistent!
1063  *  \warning This method can significantly modify the order of geometric types in \a this,
1064  *          hence, to write this mesh to the MED file, its cells must be sorted using
1065  *          sortCellsInMEDFileFrmt().
1066  *  \param [in] cellIdsToConvertBg - the array holding ids of cells to convert.
1067  *  \param [in] cellIdsToConvertEnd - a pointer to the last-plus-one-th element of \a
1068  *         cellIdsToConvertBg.
1069  *  \throw If the coordinates array is not set.
1070  *  \throw If the nodal connectivity of cells is node defined.
1071  *  \throw If dimension of \a this mesh is not either 2 or 3.
1072  *
1073  *  \if ENABLE_EXAMPLES
1074  *  \ref cpp_mcumesh_convertToPolyTypes "Here is a C++ example".<br>
1075  *  \ref  py_mcumesh_convertToPolyTypes "Here is a Python example".
1076  *  \endif
1077  */
1078 void MEDCouplingUMesh::convertToPolyTypes(const int *cellIdsToConvertBg, const int *cellIdsToConvertEnd)
1079 {
1080   checkFullyDefined();
1081   int dim=getMeshDimension();
1082   if(dim<2 || dim>3)
1083     throw INTERP_KERNEL::Exception("Invalid mesh dimension : must be 2 or 3 !");
1084   int nbOfCells(getNumberOfCells());
1085   if(dim==2)
1086     {
1087       const int *connIndex=_nodal_connec_index->getConstPointer();
1088       int *conn=_nodal_connec->getPointer();
1089       for(const int *iter=cellIdsToConvertBg;iter!=cellIdsToConvertEnd;iter++)
1090         {
1091           if(*iter>=0 && *iter<nbOfCells)
1092             {
1093               const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[connIndex[*iter]]);
1094               if(!cm.isQuadratic())
1095                 conn[connIndex[*iter]]=INTERP_KERNEL::NORM_POLYGON;
1096               else
1097                 conn[connIndex[*iter]]=INTERP_KERNEL::NORM_QPOLYG;
1098             }
1099           else
1100             {
1101               std::ostringstream oss; oss << "MEDCouplingUMesh::convertToPolyTypes : On rank #" << std::distance(cellIdsToConvertBg,iter) << " value is " << *iter << " which is not";
1102               oss << " in range [0," << nbOfCells << ") !";
1103               throw INTERP_KERNEL::Exception(oss.str().c_str());
1104             }
1105         }
1106     }
1107   else
1108     {
1109       int *connIndex(_nodal_connec_index->getPointer());
1110       const int *connOld(_nodal_connec->getConstPointer());
1111       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> connNew(DataArrayInt::New()),connNewI(DataArrayInt::New()); connNew->alloc(0,1); connNewI->alloc(1,1); connNewI->setIJ(0,0,0);
1112       std::vector<bool> toBeDone(nbOfCells,false);
1113       for(const int *iter=cellIdsToConvertBg;iter!=cellIdsToConvertEnd;iter++)
1114         {
1115           if(*iter>=0 && *iter<nbOfCells)
1116             toBeDone[*iter]=true;
1117           else
1118             {
1119               std::ostringstream oss; oss << "MEDCouplingUMesh::convertToPolyTypes : On rank #" << std::distance(cellIdsToConvertBg,iter) << " value is " << *iter << " which is not";
1120               oss << " in range [0," << nbOfCells << ") !";
1121               throw INTERP_KERNEL::Exception(oss.str().c_str());
1122             }
1123         }
1124       for(int cellId=0;cellId<nbOfCells;cellId++)
1125         {
1126           int pos(connIndex[cellId]),posP1(connIndex[cellId+1]);
1127           int lgthOld(posP1-pos-1);
1128           if(toBeDone[cellId])
1129             {
1130               const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)connOld[pos]);
1131               unsigned nbOfFaces(cm.getNumberOfSons2(connOld+pos+1,lgthOld));
1132               int *tmp(new int[nbOfFaces*lgthOld+1]);
1133               int *work=tmp; *work++=INTERP_KERNEL::NORM_POLYHED;
1134               for(unsigned j=0;j<nbOfFaces;j++)
1135                 {
1136                   INTERP_KERNEL::NormalizedCellType type;
1137                   unsigned offset=cm.fillSonCellNodalConnectivity2(j,connOld+pos+1,lgthOld,work,type);
1138                   work+=offset;
1139                   *work++=-1;
1140                 }
1141               std::size_t newLgth(std::distance(tmp,work)-1);//-1 for last -1
1142               connNew->pushBackValsSilent(tmp,tmp+newLgth);
1143               connNewI->pushBackSilent(connNewI->back()+(int)newLgth);
1144               delete [] tmp;
1145             }
1146           else
1147             {
1148               connNew->pushBackValsSilent(connOld+pos,connOld+posP1);
1149               connNewI->pushBackSilent(connNewI->back()+posP1-pos);
1150             }
1151         }
1152       setConnectivity(connNew,connNewI,false);//false because computeTypes called just behind.
1153     }
1154   computeTypes();
1155 }
1156
1157 /*!
1158  * Converts all cells to either polygons (if \a this is a 2D mesh) or
1159  * polyhedrons (if \a this is a 3D mesh).
1160  *  \warning As this method is purely for user-friendliness and no optimization is
1161  *          done to avoid construction of a useless vector, this method can be costly
1162  *          in memory.
1163  *  \throw If the coordinates array is not set.
1164  *  \throw If the nodal connectivity of cells is node defined.
1165  *  \throw If dimension of \a this mesh is not either 2 or 3.
1166  */
1167 void MEDCouplingUMesh::convertAllToPoly()
1168 {
1169   int nbOfCells=getNumberOfCells();
1170   std::vector<int> cellIds(nbOfCells);
1171   for(int i=0;i<nbOfCells;i++)
1172     cellIds[i]=i;
1173   convertToPolyTypes(&cellIds[0],&cellIds[0]+cellIds.size());
1174 }
1175
1176 /*!
1177  * Fixes nodal connectivity of invalid cells of type NORM_POLYHED. This method
1178  * expects that all NORM_POLYHED cells have connectivity similar to that of prismatic
1179  * volumes like NORM_HEXA8, NORM_PENTA6 etc., i.e. the first half of nodes describes a
1180  * base facet of the volume and the second half of nodes describes an opposite facet
1181  * having the same number of nodes as the base one. This method converts such
1182  * connectivity to a valid polyhedral format where connectivity of each facet is
1183  * explicitly described and connectivity of facets are separated by -1. If \a this mesh
1184  * contains a NORM_POLYHED cell with a valid connectivity, or an invalid connectivity is
1185  * not as expected, an exception is thrown and the mesh remains unchanged. Care of
1186  * a correct orientation of the first facet of a polyhedron, else orientation of a
1187  * corrected cell is reverse.<br>
1188  * This method is useful to build an extruded unstructured mesh with polyhedrons as
1189  * it releases the user from boring description of polyhedra connectivity in the valid
1190  * format.
1191  *  \throw If \a this->getMeshDimension() != 3.
1192  *  \throw If \a this->getSpaceDimension() != 3.
1193  *  \throw If the nodal connectivity of cells is not defined.
1194  *  \throw If the coordinates array is not set.
1195  *  \throw If \a this mesh contains polyhedrons with the valid connectivity.
1196  *  \throw If \a this mesh contains polyhedrons with odd number of nodes.
1197  *
1198  *  \if ENABLE_EXAMPLES
1199  *  \ref cpp_mcumesh_arePolyhedronsNotCorrectlyOriented "Here is a C++ example".<br>
1200  *  \ref  py_mcumesh_arePolyhedronsNotCorrectlyOriented "Here is a Python example".
1201  *  \endif
1202  */
1203 void MEDCouplingUMesh::convertExtrudedPolyhedra()
1204 {
1205   checkFullyDefined();
1206   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
1207     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertExtrudedPolyhedra works on umeshes with meshdim equal to 3 and spaceDim equal to 3 too!");
1208   int nbOfCells=getNumberOfCells();
1209   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newCi=DataArrayInt::New();
1210   newCi->alloc(nbOfCells+1,1);
1211   int *newci=newCi->getPointer();
1212   const int *ci=_nodal_connec_index->getConstPointer();
1213   const int *c=_nodal_connec->getConstPointer();
1214   newci[0]=0;
1215   for(int i=0;i<nbOfCells;i++)
1216     {
1217       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)c[ci[i]];
1218       if(type==INTERP_KERNEL::NORM_POLYHED)
1219         {
1220           if(std::count(c+ci[i]+1,c+ci[i+1],-1)!=0)
1221             {
1222               std::ostringstream oss; oss << "MEDCouplingUMesh::convertExtrudedPolyhedra : cell # " << i << " is a polhedron BUT it has NOT exactly 1 face !";
1223               throw INTERP_KERNEL::Exception(oss.str().c_str());
1224             }
1225           std::size_t n2=std::distance(c+ci[i]+1,c+ci[i+1]);
1226           if(n2%2!=0)
1227             {
1228               std::ostringstream oss; oss << "MEDCouplingUMesh::convertExtrudedPolyhedra : cell # " << i << " is a polhedron with 1 face but there is a mismatch of number of nodes in face should be even !";
1229               throw INTERP_KERNEL::Exception(oss.str().c_str());
1230             }
1231           int n1=(int)(n2/2);
1232           newci[i+1]=7*n1+2+newci[i];//6*n1 (nodal length) + n1+2 (number of faces) - 1 (number of '-1' separator is equal to number of faces -1) + 1 (for cell type)
1233         }
1234       else
1235         newci[i+1]=(ci[i+1]-ci[i])+newci[i];
1236     }
1237   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newC=DataArrayInt::New();
1238   newC->alloc(newci[nbOfCells],1);
1239   int *newc=newC->getPointer();
1240   for(int i=0;i<nbOfCells;i++)
1241     {
1242       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)c[ci[i]];
1243       if(type==INTERP_KERNEL::NORM_POLYHED)
1244         {
1245           std::size_t n1=std::distance(c+ci[i]+1,c+ci[i+1])/2;
1246           newc=std::copy(c+ci[i],c+ci[i]+n1+1,newc);
1247           *newc++=-1;
1248           for(std::size_t j=0;j<n1;j++)
1249             {
1250               newc[j]=c[ci[i]+1+n1+(n1-j)%n1];
1251               newc[n1+5*j]=-1;
1252               newc[n1+5*j+1]=c[ci[i]+1+j];
1253               newc[n1+5*j+2]=c[ci[i]+1+j+n1];
1254               newc[n1+5*j+3]=c[ci[i]+1+(j+1)%n1+n1];
1255               newc[n1+5*j+4]=c[ci[i]+1+(j+1)%n1];
1256             }
1257           newc+=n1*6;
1258         }
1259       else
1260         newc=std::copy(c+ci[i],c+ci[i+1],newc);
1261     }
1262   _nodal_connec_index->decrRef(); _nodal_connec_index=newCi.retn();
1263   _nodal_connec->decrRef(); _nodal_connec=newC.retn();
1264 }
1265
1266
1267 /*!
1268  * Converts all polygons (if \a this is a 2D mesh) or polyhedrons (if \a this is a 3D
1269  * mesh) to cells of classical types. This method is opposite to convertToPolyTypes().
1270  * \warning Cells of the result mesh are \b not sorted by geometric type, hence,
1271  *          to write this mesh to the MED file, its cells must be sorted using
1272  *          sortCellsInMEDFileFrmt().
1273  * \return \c true if at least one cell has been converted, \c false else. In the
1274  *         last case the nodal connectivity remains unchanged.
1275  * \throw If the coordinates array is not set.
1276  * \throw If the nodal connectivity of cells is not defined.
1277  * \throw If \a this->getMeshDimension() < 0.
1278  */
1279 bool MEDCouplingUMesh::unPolyze()
1280 {
1281   checkFullyDefined();
1282   int mdim=getMeshDimension();
1283   if(mdim<0)
1284     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::unPolyze works on umeshes with meshdim equals to 0, 1 2 or 3 !");
1285   if(mdim<=1)
1286     return false;
1287   int nbOfCells=getNumberOfCells();
1288   if(nbOfCells<1)
1289     return false;
1290   int initMeshLgth=getMeshLength();
1291   int *conn=_nodal_connec->getPointer();
1292   int *index=_nodal_connec_index->getPointer();
1293   int posOfCurCell=0;
1294   int newPos=0;
1295   int lgthOfCurCell;
1296   bool ret=false;
1297   for(int i=0;i<nbOfCells;i++)
1298     {
1299       lgthOfCurCell=index[i+1]-posOfCurCell;
1300       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)conn[posOfCurCell];
1301       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(type);
1302       INTERP_KERNEL::NormalizedCellType newType=INTERP_KERNEL::NORM_ERROR;
1303       int newLgth;
1304       if(cm.isDynamic())
1305         {
1306           switch(cm.getDimension())
1307           {
1308             case 2:
1309               {
1310                 INTERP_KERNEL::AutoPtr<int> tmp=new int[lgthOfCurCell-1];
1311                 std::copy(conn+posOfCurCell+1,conn+posOfCurCell+lgthOfCurCell,(int *)tmp);
1312                 newType=INTERP_KERNEL::CellSimplify::tryToUnPoly2D(cm.isQuadratic(),tmp,lgthOfCurCell-1,conn+newPos+1,newLgth);
1313                 break;
1314               }
1315             case 3:
1316               {
1317                 int nbOfFaces,lgthOfPolyhConn;
1318                 INTERP_KERNEL::AutoPtr<int> zipFullReprOfPolyh=INTERP_KERNEL::CellSimplify::getFullPolyh3DCell(type,conn+posOfCurCell+1,lgthOfCurCell-1,nbOfFaces,lgthOfPolyhConn);
1319                 newType=INTERP_KERNEL::CellSimplify::tryToUnPoly3D(zipFullReprOfPolyh,nbOfFaces,lgthOfPolyhConn,conn+newPos+1,newLgth);
1320                 break;
1321               }
1322             case 1:
1323               {
1324                 newType=(lgthOfCurCell==3)?INTERP_KERNEL::NORM_SEG2:INTERP_KERNEL::NORM_POLYL;
1325                 break;
1326               }
1327           }
1328           ret=ret || (newType!=type);
1329           conn[newPos]=newType;
1330           newPos+=newLgth+1;
1331           posOfCurCell=index[i+1];
1332           index[i+1]=newPos;
1333         }
1334       else
1335         {
1336           std::copy(conn+posOfCurCell,conn+posOfCurCell+lgthOfCurCell,conn+newPos);
1337           newPos+=lgthOfCurCell;
1338           posOfCurCell+=lgthOfCurCell;
1339           index[i+1]=newPos;
1340         }
1341     }
1342   if(newPos!=initMeshLgth)
1343     _nodal_connec->reAlloc(newPos);
1344   if(ret)
1345     computeTypes();
1346   return ret;
1347 }
1348
1349 /*!
1350  * This method expects that spaceDimension is equal to 3 and meshDimension equal to 3.
1351  * This method performs operation only on polyhedrons in \b this. If no polyhedrons exists in \b this, \b this remains unchanged.
1352  * This method allows to merge if any coplanar 3DSurf cells that may appear in some polyhedrons cells. 
1353  *
1354  * \param [in] eps is a relative precision that allows to establish if some 3D plane are coplanar or not. This epsilon is used to recenter around origin to have maximal 
1355  *             precision.
1356  */
1357 void MEDCouplingUMesh::simplifyPolyhedra(double eps)
1358 {
1359   checkFullyDefined();
1360   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
1361     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::simplifyPolyhedra : works on meshdimension 3 and spaceDimension 3 !");
1362   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> coords=getCoords()->deepCpy();
1363   coords->recenterForMaxPrecision(eps);
1364   //
1365   int nbOfCells=getNumberOfCells();
1366   const int *conn=_nodal_connec->getConstPointer();
1367   const int *index=_nodal_connec_index->getConstPointer();
1368   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> connINew=DataArrayInt::New();
1369   connINew->alloc(nbOfCells+1,1);
1370   int *connINewPtr=connINew->getPointer(); *connINewPtr++=0;
1371   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> connNew=DataArrayInt::New(); connNew->alloc(0,1);
1372   bool changed=false;
1373   for(int i=0;i<nbOfCells;i++,connINewPtr++)
1374     {
1375       if(conn[index[i]]==(int)INTERP_KERNEL::NORM_POLYHED)
1376         {
1377           SimplifyPolyhedronCell(eps,coords,conn+index[i],conn+index[i+1],connNew);
1378           changed=true;
1379         }
1380       else
1381         connNew->insertAtTheEnd(conn+index[i],conn+index[i+1]);
1382       *connINewPtr=connNew->getNumberOfTuples();
1383     }
1384   if(changed)
1385     setConnectivity(connNew,connINew,false);
1386 }
1387
1388 /*!
1389  * This method returns all node ids used in \b this. The data array returned has to be dealt by the caller.
1390  * The returned node ids are sortes ascendingly. This method is closed to MEDCouplingUMesh::getNodeIdsInUse except
1391  * the format of returned DataArrayInt instance.
1392  * 
1393  * \return a newly allocated DataArrayInt sorted ascendingly of fetched node ids.
1394  * \sa MEDCouplingUMesh::getNodeIdsInUse, areAllNodesFetched
1395  */
1396 DataArrayInt *MEDCouplingUMesh::computeFetchedNodeIds() const
1397 {
1398   checkConnectivityFullyDefined();
1399   int nbOfCells=getNumberOfCells();
1400   const int *connIndex=_nodal_connec_index->getConstPointer();
1401   const int *conn=_nodal_connec->getConstPointer();
1402   const int *maxEltPt=std::max_element(_nodal_connec->begin(),_nodal_connec->end());
1403   int maxElt=maxEltPt==_nodal_connec->end()?0:std::abs(*maxEltPt)+1;
1404   std::vector<bool> retS(maxElt,false);
1405   for(int i=0;i<nbOfCells;i++)
1406     for(int j=connIndex[i]+1;j<connIndex[i+1];j++)
1407       if(conn[j]>=0)
1408         retS[conn[j]]=true;
1409   int sz=0;
1410   for(int i=0;i<maxElt;i++)
1411     if(retS[i])
1412       sz++;
1413   DataArrayInt *ret=DataArrayInt::New();
1414   ret->alloc(sz,1);
1415   int *retPtr=ret->getPointer();
1416   for(int i=0;i<maxElt;i++)
1417     if(retS[i])
1418       *retPtr++=i;
1419   return ret;
1420 }
1421
1422 /*!
1423  * \param [in,out] nodeIdsInUse an array of size typically equal to nbOfNodes.
1424  * \sa MEDCouplingUMesh::getNodeIdsInUse, areAllNodesFetched
1425  */
1426 void MEDCouplingUMesh::computeNodeIdsAlg(std::vector<bool>& nodeIdsInUse) const
1427 {
1428   int nbOfNodes((int)nodeIdsInUse.size()),nbOfCells(getNumberOfCells());
1429   const int *connIndex(_nodal_connec_index->getConstPointer()),*conn(_nodal_connec->getConstPointer());
1430   for(int i=0;i<nbOfCells;i++)
1431     for(int j=connIndex[i]+1;j<connIndex[i+1];j++)
1432       if(conn[j]>=0)
1433         {
1434           if(conn[j]<nbOfNodes)
1435             nodeIdsInUse[conn[j]]=true;
1436           else
1437             {
1438               std::ostringstream oss; oss << "MEDCouplingUMesh::computeNodeIdsAlg : In cell #" << i  << " presence of node id " <<  conn[j] << " not in [0," << nbOfNodes << ") !";
1439               throw INTERP_KERNEL::Exception(oss.str().c_str());
1440             }
1441         }
1442 }
1443
1444 /*!
1445  * Finds nodes not used in any cell and returns an array giving a new id to every node
1446  * by excluding the unused nodes, for which the array holds -1. The result array is
1447  * a mapping in "Old to New" mode. 
1448  *  \param [out] nbrOfNodesInUse - number of node ids present in the nodal connectivity.
1449  *  \return DataArrayInt * - a new instance of DataArrayInt. Its length is \a
1450  *          this->getNumberOfNodes(). It holds for each node of \a this mesh either -1
1451  *          if the node is unused or a new id else. The caller is to delete this
1452  *          array using decrRef() as it is no more needed.  
1453  *  \throw If the coordinates array is not set.
1454  *  \throw If the nodal connectivity of cells is not defined.
1455  *  \throw If the nodal connectivity includes an invalid id.
1456  *
1457  *  \if ENABLE_EXAMPLES
1458  *  \ref cpp_mcumesh_getNodeIdsInUse "Here is a C++ example".<br>
1459  *  \ref  py_mcumesh_getNodeIdsInUse "Here is a Python example".
1460  *  \endif
1461  * \sa computeFetchedNodeIds, computeNodeIdsAlg()
1462  */
1463 DataArrayInt *MEDCouplingUMesh::getNodeIdsInUse(int& nbrOfNodesInUse) const
1464 {
1465   nbrOfNodesInUse=-1;
1466   int nbOfNodes(getNumberOfNodes());
1467   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New();
1468   ret->alloc(nbOfNodes,1);
1469   int *traducer=ret->getPointer();
1470   std::fill(traducer,traducer+nbOfNodes,-1);
1471   int nbOfCells=getNumberOfCells();
1472   const int *connIndex=_nodal_connec_index->getConstPointer();
1473   const int *conn=_nodal_connec->getConstPointer();
1474   for(int i=0;i<nbOfCells;i++)
1475     for(int j=connIndex[i]+1;j<connIndex[i+1];j++)
1476       if(conn[j]>=0)
1477         {
1478           if(conn[j]<nbOfNodes)
1479             traducer[conn[j]]=1;
1480           else
1481             {
1482               std::ostringstream oss; oss << "MEDCouplingUMesh::getNodeIdsInUse : In cell #" << i  << " presence of node id " <<  conn[j] << " not in [0," << nbOfNodes << ") !";
1483               throw INTERP_KERNEL::Exception(oss.str().c_str());
1484             }
1485         }
1486   nbrOfNodesInUse=(int)std::count(traducer,traducer+nbOfNodes,1);
1487   std::transform(traducer,traducer+nbOfNodes,traducer,MEDCouplingAccVisit());
1488   return ret.retn();
1489 }
1490
1491 /*!
1492  * This method returns a newly allocated array containing this->getNumberOfCells() tuples and 1 component.
1493  * For each cell in \b this the number of nodes constituting cell is computed.
1494  * For each polyhedron cell, the sum of the number of nodes of each face constituting polyhedron cell is returned.
1495  * So for pohyhedrons some nodes can be counted several times in the returned result.
1496  * 
1497  * \return a newly allocated array
1498  * \sa MEDCouplingUMesh::computeEffectiveNbOfNodesPerCell
1499  */
1500 DataArrayInt *MEDCouplingUMesh::computeNbOfNodesPerCell() const
1501 {
1502   checkConnectivityFullyDefined();
1503   int nbOfCells=getNumberOfCells();
1504   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New();
1505   ret->alloc(nbOfCells,1);
1506   int *retPtr=ret->getPointer();
1507   const int *conn=getNodalConnectivity()->getConstPointer();
1508   const int *connI=getNodalConnectivityIndex()->getConstPointer();
1509   for(int i=0;i<nbOfCells;i++,retPtr++)
1510     {
1511       if(conn[connI[i]]!=(int)INTERP_KERNEL::NORM_POLYHED)
1512         *retPtr=connI[i+1]-connI[i]-1;
1513       else
1514         *retPtr=connI[i+1]-connI[i]-1-std::count(conn+connI[i]+1,conn+connI[i+1],-1);
1515     }
1516   return ret.retn();
1517 }
1518
1519 /*!
1520  * This method computes effective number of nodes per cell. That is to say nodes appearing several times in nodal connectivity of a cell,
1521  * will be counted only once here whereas it will be counted several times in MEDCouplingUMesh::computeNbOfNodesPerCell method.
1522  *
1523  * \return DataArrayInt * - new object to be deallocated by the caller.
1524  * \sa MEDCouplingUMesh::computeNbOfNodesPerCell
1525  */
1526 DataArrayInt *MEDCouplingUMesh::computeEffectiveNbOfNodesPerCell() const
1527 {
1528   checkConnectivityFullyDefined();
1529   int nbOfCells=getNumberOfCells();
1530   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New();
1531   ret->alloc(nbOfCells,1);
1532   int *retPtr=ret->getPointer();
1533   const int *conn=getNodalConnectivity()->getConstPointer();
1534   const int *connI=getNodalConnectivityIndex()->getConstPointer();
1535   for(int i=0;i<nbOfCells;i++,retPtr++)
1536     {
1537       std::set<int> s(conn+connI[i]+1,conn+connI[i+1]);
1538       if(conn[connI[i]]!=(int)INTERP_KERNEL::NORM_POLYHED)
1539         *retPtr=(int)s.size();
1540       else
1541         {
1542           s.erase(-1);
1543           *retPtr=(int)s.size();
1544         }
1545     }
1546   return ret.retn();
1547 }
1548
1549 /*!
1550  * This method returns a newly allocated array containing this->getNumberOfCells() tuples and 1 component.
1551  * For each cell in \b this the number of faces constituting (entity of dimension this->getMeshDimension()-1) cell is computed.
1552  * 
1553  * \return a newly allocated array
1554  */
1555 DataArrayInt *MEDCouplingUMesh::computeNbOfFacesPerCell() const
1556 {
1557   checkConnectivityFullyDefined();
1558   int nbOfCells=getNumberOfCells();
1559   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New();
1560   ret->alloc(nbOfCells,1);
1561   int *retPtr=ret->getPointer();
1562   const int *conn=getNodalConnectivity()->getConstPointer();
1563   const int *connI=getNodalConnectivityIndex()->getConstPointer();
1564   for(int i=0;i<nbOfCells;i++,retPtr++,connI++)
1565     {
1566       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[*connI]);
1567       *retPtr=cm.getNumberOfSons2(conn+connI[0]+1,connI[1]-connI[0]-1);
1568     }
1569   return ret.retn();
1570 }
1571
1572 /*!
1573  * Removes unused nodes (the node coordinates array is shorten) and returns an array
1574  * mapping between new and old node ids in "Old to New" mode. -1 values in the returned
1575  * array mean that the corresponding old node is no more used. 
1576  *  \return DataArrayInt * - a new instance of DataArrayInt of length \a
1577  *           this->getNumberOfNodes() before call of this method. The caller is to
1578  *           delete this array using decrRef() as it is no more needed. 
1579  *  \throw If the coordinates array is not set.
1580  *  \throw If the nodal connectivity of cells is not defined.
1581  *  \throw If the nodal connectivity includes an invalid id.
1582  *  \sa areAllNodesFetched
1583  *
1584  *  \if ENABLE_EXAMPLES
1585  *  \ref cpp_mcumesh_zipCoordsTraducer "Here is a C++ example".<br>
1586  *  \ref  py_mcumesh_zipCoordsTraducer "Here is a Python example".
1587  *  \endif
1588  */
1589 DataArrayInt *MEDCouplingUMesh::zipCoordsTraducer()
1590 {
1591   return MEDCouplingPointSet::zipCoordsTraducer();
1592 }
1593
1594 /*!
1595  * This method stands if 'cell1' and 'cell2' are equals regarding 'compType' policy.
1596  * The semantic of 'compType' is specified in MEDCouplingPointSet::zipConnectivityTraducer method.
1597  */
1598 int MEDCouplingUMesh::AreCellsEqual(const int *conn, const int *connI, int cell1, int cell2, int compType)
1599 {
1600   switch(compType)
1601   {
1602     case 0:
1603       return AreCellsEqual0(conn,connI,cell1,cell2);
1604     case 1:
1605       return AreCellsEqual1(conn,connI,cell1,cell2);
1606     case 2:
1607       return AreCellsEqual2(conn,connI,cell1,cell2);
1608     case 3:
1609       return AreCellsEqual3(conn,connI,cell1,cell2);
1610     case 7:
1611       return AreCellsEqual7(conn,connI,cell1,cell2);
1612   }
1613   throw INTERP_KERNEL::Exception("Unknown comparison asked ! Must be in 0,1,2,3 or 7.");
1614 }
1615
1616 /*!
1617  * This method is the last step of the MEDCouplingPointSet::zipConnectivityTraducer with policy 0.
1618  */
1619 int MEDCouplingUMesh::AreCellsEqual0(const int *conn, const int *connI, int cell1, int cell2)
1620 {
1621   if(connI[cell1+1]-connI[cell1]==connI[cell2+1]-connI[cell2])
1622     return std::equal(conn+connI[cell1]+1,conn+connI[cell1+1],conn+connI[cell2]+1)?1:0;
1623   return 0;
1624 }
1625
1626 /*!
1627  * This method is the last step of the MEDCouplingPointSet::zipConnectivityTraducer with policy 1.
1628  */
1629 int MEDCouplingUMesh::AreCellsEqual1(const int *conn, const int *connI, int cell1, int cell2)
1630 {
1631   int sz=connI[cell1+1]-connI[cell1];
1632   if(sz==connI[cell2+1]-connI[cell2])
1633     {
1634       if(conn[connI[cell1]]==conn[connI[cell2]])
1635         {
1636           const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[connI[cell1]]);
1637           unsigned dim=cm.getDimension();
1638           if(dim!=3)
1639             {
1640               if(dim!=1)
1641                 {
1642                   int sz1=2*(sz-1);
1643                   INTERP_KERNEL::AutoPtr<int> tmp=new int[sz1];
1644                   int *work=std::copy(conn+connI[cell1]+1,conn+connI[cell1+1],(int *)tmp);
1645                   std::copy(conn+connI[cell1]+1,conn+connI[cell1+1],work);
1646                   work=std::search((int *)tmp,(int *)tmp+sz1,conn+connI[cell2]+1,conn+connI[cell2+1]);
1647                   return work!=tmp+sz1?1:0;
1648                 }
1649               else
1650                 return std::equal(conn+connI[cell1]+1,conn+connI[cell1+1],conn+connI[cell2]+1)?1:0;//case of SEG2 and SEG3
1651             }
1652           else
1653             throw INTERP_KERNEL::Exception("MEDCouplingUMesh::AreCellsEqual1 : not implemented yet for meshdim == 3 !");
1654         }
1655     }
1656   return 0;
1657 }
1658
1659 /*!
1660  * This method is the last step of the MEDCouplingPointSet::zipConnectivityTraducer with policy 2.
1661  */
1662 int MEDCouplingUMesh::AreCellsEqual2(const int *conn, const int *connI, int cell1, int cell2)
1663 {
1664   if(connI[cell1+1]-connI[cell1]==connI[cell2+1]-connI[cell2])
1665     {
1666       if(conn[connI[cell1]]==conn[connI[cell2]])
1667         {
1668           std::set<int> s1(conn+connI[cell1]+1,conn+connI[cell1+1]);
1669           std::set<int> s2(conn+connI[cell2]+1,conn+connI[cell2+1]);
1670           return s1==s2?1:0;
1671         }
1672     }
1673   return 0;
1674 }
1675
1676 /*!
1677  * This method is less restrictive than AreCellsEqual2. Here the geometric type is absolutely not taken into account !
1678  */
1679 int MEDCouplingUMesh::AreCellsEqual3(const int *conn, const int *connI, int cell1, int cell2)
1680 {
1681   if(connI[cell1+1]-connI[cell1]==connI[cell2+1]-connI[cell2])
1682     {
1683       std::set<int> s1(conn+connI[cell1]+1,conn+connI[cell1+1]);
1684       std::set<int> s2(conn+connI[cell2]+1,conn+connI[cell2+1]);
1685       return s1==s2?1:0;
1686     }
1687   return 0;
1688 }
1689
1690 /*!
1691  * This method is the last step of the MEDCouplingPointSet::zipConnectivityTraducer with policy 7.
1692  */
1693 int MEDCouplingUMesh::AreCellsEqual7(const int *conn, const int *connI, int cell1, int cell2)
1694 {
1695   int sz=connI[cell1+1]-connI[cell1];
1696   if(sz==connI[cell2+1]-connI[cell2])
1697     {
1698       if(conn[connI[cell1]]==conn[connI[cell2]])
1699         {
1700           const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[connI[cell1]]);
1701           unsigned dim=cm.getDimension();
1702           if(dim!=3)
1703             {
1704               if(dim!=1)
1705                 {
1706                   int sz1=2*(sz-1);
1707                   INTERP_KERNEL::AutoPtr<int> tmp=new int[sz1];
1708                   int *work=std::copy(conn+connI[cell1]+1,conn+connI[cell1+1],(int *)tmp);
1709                   std::copy(conn+connI[cell1]+1,conn+connI[cell1+1],work);
1710                   work=std::search((int *)tmp,(int *)tmp+sz1,conn+connI[cell2]+1,conn+connI[cell2+1]);
1711                   if(work!=tmp+sz1)
1712                     return 1;
1713                   else
1714                     {
1715                       std::reverse_iterator<int *> it1((int *)tmp+sz1);
1716                       std::reverse_iterator<int *> it2((int *)tmp);
1717                       if(std::search(it1,it2,conn+connI[cell2]+1,conn+connI[cell2+1])!=it2)
1718                         return 2;
1719                       else
1720                         return 0;
1721                     }
1722
1723                   return work!=tmp+sz1?1:0;
1724                 }
1725               else
1726                 {//case of SEG2 and SEG3
1727                   if(std::equal(conn+connI[cell1]+1,conn+connI[cell1+1],conn+connI[cell2]+1))
1728                     return 1;
1729                   if(!cm.isQuadratic())
1730                     {
1731                       std::reverse_iterator<const int *> it1(conn+connI[cell1+1]);
1732                       std::reverse_iterator<const int *> it2(conn+connI[cell1]+1);
1733                       if(std::equal(it1,it2,conn+connI[cell2]+1))
1734                         return 2;
1735                       return 0;
1736                     }
1737                   else
1738                     {
1739                       if(conn[connI[cell1]+1]==conn[connI[cell2]+2] && conn[connI[cell1]+2]==conn[connI[cell2]+1] && conn[connI[cell1]+3]==conn[connI[cell2]+3])
1740                         return 2;
1741                       return 0;
1742                     }
1743                 }
1744             }
1745           else
1746             throw INTERP_KERNEL::Exception("MEDCouplingUMesh::AreCellsEqual7 : not implemented yet for meshdim == 3 !");
1747         }
1748     }
1749   return 0;
1750 }
1751
1752 /*!
1753  * This method find in candidate pool defined by 'candidates' the cells equal following the polycy 'compType'.
1754  * If any true is returned and the results will be put at the end of 'result' output parameter. If not false is returned
1755  * and result remains unchanged.
1756  * The semantic of 'compType' is specified in MEDCouplingPointSet::zipConnectivityTraducer method.
1757  * If in 'candidates' pool -1 value is considered as an empty value.
1758  * WARNING this method returns only ONE set of result !
1759  */
1760 bool MEDCouplingUMesh::AreCellsEqualInPool(const std::vector<int>& candidates, int compType, const int *conn, const int *connI, DataArrayInt *result)
1761 {
1762   if(candidates.size()<1)
1763     return false;
1764   bool ret=false;
1765   std::vector<int>::const_iterator iter=candidates.begin();
1766   int start=(*iter++);
1767   for(;iter!=candidates.end();iter++)
1768     {
1769       int status=AreCellsEqual(conn,connI,start,*iter,compType);
1770       if(status!=0)
1771         {
1772           if(!ret)
1773             {
1774               result->pushBackSilent(start);
1775               ret=true;
1776             }
1777           if(status==1)
1778             result->pushBackSilent(*iter);
1779           else
1780             result->pushBackSilent(status==2?(*iter+1):-(*iter+1));
1781         }
1782     }
1783   return ret;
1784 }
1785
1786 /*!
1787  * This method find cells that are cells equal (regarding \a compType) in \a this. The comparison is specified by \a compType.
1788  * This method keeps the coordiantes of \a this. This method is time consuming and is called 
1789  *
1790  * \param [in] compType input specifying the technique used to compare cells each other.
1791  *   - 0 : exactly. A cell is detected to be the same if and only if the connectivity is exactly the same without permutation and types same too. This is the strongest policy.
1792  *   - 1 : permutation same orientation. cell1 and cell2 are considered equal if the connectivity of cell2 can be deduced by those of cell1 by direct permutation (with exactly the same orientation)
1793  * and their type equal. For 1D mesh the policy 1 is equivalent to 0.
1794  *   - 2 : nodal. cell1 and cell2 are equal if and only if cell1 and cell2 have same type and have the same nodes constituting connectivity. This is the laziest policy. This policy
1795  * can be used for users not sensitive to orientation of cell
1796  * \param [in] startCellId specifies the cellId starting from which the equality computation will be carried out. By default it is 0, which it means that all cells in \a this will be scanned.
1797  * \param [out] commonCells
1798  * \param [out] commonCellsI
1799  * \return the correspondance array old to new in a newly allocated array.
1800  * 
1801  */
1802 void MEDCouplingUMesh::findCommonCells(int compType, int startCellId, DataArrayInt *& commonCellsArr, DataArrayInt *& commonCellsIArr) const
1803 {
1804   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revNodal=DataArrayInt::New(),revNodalI=DataArrayInt::New();
1805   getReverseNodalConnectivity(revNodal,revNodalI);
1806   FindCommonCellsAlg(compType,startCellId,_nodal_connec,_nodal_connec_index,revNodal,revNodalI,commonCellsArr,commonCellsIArr);
1807 }
1808
1809 void MEDCouplingUMesh::FindCommonCellsAlg(int compType, int startCellId, const DataArrayInt *nodal, const DataArrayInt *nodalI, const DataArrayInt *revNodal, const DataArrayInt *revNodalI,
1810                                           DataArrayInt *& commonCellsArr, DataArrayInt *& commonCellsIArr)
1811 {
1812   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> commonCells=DataArrayInt::New(),commonCellsI=DataArrayInt::New(); commonCells->alloc(0,1);
1813   int nbOfCells=nodalI->getNumberOfTuples()-1;
1814   commonCellsI->reserve(1); commonCellsI->pushBackSilent(0);
1815   const int *revNodalPtr=revNodal->getConstPointer(),*revNodalIPtr=revNodalI->getConstPointer();
1816   const int *connPtr=nodal->getConstPointer(),*connIPtr=nodalI->getConstPointer();
1817   std::vector<bool> isFetched(nbOfCells,false);
1818   if(startCellId==0)
1819     {
1820       for(int i=0;i<nbOfCells;i++)
1821         {
1822           if(!isFetched[i])
1823             {
1824               const int *connOfNode=std::find_if(connPtr+connIPtr[i]+1,connPtr+connIPtr[i+1],std::bind2nd(std::not_equal_to<int>(),-1));
1825               std::vector<int> v,v2;
1826               if(connOfNode!=connPtr+connIPtr[i+1])
1827                 {
1828                   const int *locRevNodal=std::find(revNodalPtr+revNodalIPtr[*connOfNode],revNodalPtr+revNodalIPtr[*connOfNode+1],i);
1829                   v2.insert(v2.end(),locRevNodal,revNodalPtr+revNodalIPtr[*connOfNode+1]);
1830                   connOfNode++;
1831                 }
1832               for(;connOfNode!=connPtr+connIPtr[i+1] && v2.size()>1;connOfNode++)
1833                 if(*connOfNode>=0)
1834                   {
1835                     v=v2;
1836                     const int *locRevNodal=std::find(revNodalPtr+revNodalIPtr[*connOfNode],revNodalPtr+revNodalIPtr[*connOfNode+1],i);
1837                     std::vector<int>::iterator it=std::set_intersection(v.begin(),v.end(),locRevNodal,revNodalPtr+revNodalIPtr[*connOfNode+1],v2.begin());
1838                     v2.resize(std::distance(v2.begin(),it));
1839                   }
1840               if(v2.size()>1)
1841                 {
1842                   if(AreCellsEqualInPool(v2,compType,connPtr,connIPtr,commonCells))
1843                     {
1844                       int pos=commonCellsI->back();
1845                       commonCellsI->pushBackSilent(commonCells->getNumberOfTuples());
1846                       for(const int *it=commonCells->begin()+pos;it!=commonCells->end();it++)
1847                         isFetched[*it]=true;
1848                     }
1849                 }
1850             }
1851         }
1852     }
1853   else
1854     {
1855       for(int i=startCellId;i<nbOfCells;i++)
1856         {
1857           if(!isFetched[i])
1858             {
1859               const int *connOfNode=std::find_if(connPtr+connIPtr[i]+1,connPtr+connIPtr[i+1],std::bind2nd(std::not_equal_to<int>(),-1));
1860               std::vector<int> v,v2;
1861               if(connOfNode!=connPtr+connIPtr[i+1])
1862                 {
1863                   v2.insert(v2.end(),revNodalPtr+revNodalIPtr[*connOfNode],revNodalPtr+revNodalIPtr[*connOfNode+1]);
1864                   connOfNode++;
1865                 }
1866               for(;connOfNode!=connPtr+connIPtr[i+1] && v2.size()>1;connOfNode++)
1867                 if(*connOfNode>=0)
1868                   {
1869                     v=v2;
1870                     std::vector<int>::iterator it=std::set_intersection(v.begin(),v.end(),revNodalPtr+revNodalIPtr[*connOfNode],revNodalPtr+revNodalIPtr[*connOfNode+1],v2.begin());
1871                     v2.resize(std::distance(v2.begin(),it));
1872                   }
1873               if(v2.size()>1)
1874                 {
1875                   if(AreCellsEqualInPool(v2,compType,connPtr,connIPtr,commonCells))
1876                     {
1877                       int pos=commonCellsI->back();
1878                       commonCellsI->pushBackSilent(commonCells->getNumberOfTuples());
1879                       for(const int *it=commonCells->begin()+pos;it!=commonCells->end();it++)
1880                         isFetched[*it]=true;
1881                     }
1882                 }
1883             }
1884         }
1885     }
1886   commonCellsArr=commonCells.retn();
1887   commonCellsIArr=commonCellsI.retn();
1888 }
1889
1890 /*!
1891  * Checks if \a this mesh includes all cells of an \a other mesh, and returns an array
1892  * giving for each cell of the \a other an id of a cell in \a this mesh. A value larger
1893  * than \a other->getNumberOfCells() in the returned array means that there is no
1894  * corresponding cell in \a this mesh.
1895  * It is expected that \a this and \a other meshes share the same node coordinates
1896  * array, if it is not so an exception is thrown. 
1897  *  \param [in] other - the mesh to compare with.
1898  *  \param [in] compType - specifies a cell comparison technique. For meaning of its
1899  *         valid values [0,1,2], see zipConnectivityTraducer().
1900  *  \param [out] arr - a new instance of DataArrayInt returning correspondence
1901  *         between cells of the two meshes. It contains \a other->getNumberOfCells()
1902  *         values. The caller is to delete this array using
1903  *         decrRef() as it is no more needed.
1904  *  \return bool - \c true if all cells of \a other mesh are present in the \a this
1905  *         mesh.
1906  *
1907  *  \if ENABLE_EXAMPLES
1908  *  \ref cpp_mcumesh_areCellsIncludedIn "Here is a C++ example".<br>
1909  *  \ref  py_mcumesh_areCellsIncludedIn "Here is a Python example".
1910  *  \endif
1911  *  \sa checkDeepEquivalOnSameNodesWith()
1912  *  \sa checkGeoEquivalWith()
1913  */
1914 bool MEDCouplingUMesh::areCellsIncludedIn(const MEDCouplingUMesh *other, int compType, DataArrayInt *& arr) const
1915 {
1916   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> mesh=MergeUMeshesOnSameCoords(this,other);
1917   int nbOfCells=getNumberOfCells();
1918   static const int possibleCompType[]={0,1,2};
1919   if(std::find(possibleCompType,possibleCompType+sizeof(possibleCompType)/sizeof(int),compType)==possibleCompType+sizeof(possibleCompType)/sizeof(int))
1920     {
1921       std::ostringstream oss; oss << "MEDCouplingUMesh::areCellsIncludedIn : only following policies are possible : ";
1922       std::copy(possibleCompType,possibleCompType+sizeof(possibleCompType)/sizeof(int),std::ostream_iterator<int>(oss," "));
1923       oss << " !";
1924       throw INTERP_KERNEL::Exception(oss.str().c_str());
1925     }
1926   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> o2n=mesh->zipConnectivityTraducer(compType,nbOfCells);
1927   arr=o2n->substr(nbOfCells);
1928   arr->setName(other->getName());
1929   int tmp;
1930   if(other->getNumberOfCells()==0)
1931     return true;
1932   return arr->getMaxValue(tmp)<nbOfCells;
1933 }
1934
1935 /*!
1936  * This method makes the assumption that \a this and \a other share the same coords. If not an exception will be thrown !
1937  * This method tries to determine if \b other is fully included in \b this.
1938  * The main difference is that this method is not expected to throw exception.
1939  * This method has two outputs :
1940  *
1941  * \param arr is an output parameter that returns a \b newly created instance. This array is of size 'other->getNumberOfCells()'.
1942  * \return If \a other is fully included in 'this 'true is returned. If not false is returned.
1943  */
1944 bool MEDCouplingUMesh::areCellsIncludedIn2(const MEDCouplingUMesh *other, DataArrayInt *& arr) const
1945 {
1946   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> mesh=MergeUMeshesOnSameCoords(this,other);
1947   DataArrayInt *commonCells=0,*commonCellsI=0;
1948   int thisNbCells=getNumberOfCells();
1949   mesh->findCommonCells(7,thisNbCells,commonCells,commonCellsI);
1950   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> commonCellsTmp(commonCells),commonCellsITmp(commonCellsI);
1951   const int *commonCellsPtr=commonCells->getConstPointer(),*commonCellsIPtr=commonCellsI->getConstPointer();
1952   int otherNbCells=other->getNumberOfCells();
1953   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> arr2=DataArrayInt::New();
1954   arr2->alloc(otherNbCells,1);
1955   arr2->fillWithZero();
1956   int *arr2Ptr=arr2->getPointer();
1957   int nbOfCommon=commonCellsI->getNumberOfTuples()-1;
1958   for(int i=0;i<nbOfCommon;i++)
1959     {
1960       int start=commonCellsPtr[commonCellsIPtr[i]];
1961       if(start<thisNbCells)
1962         {
1963           for(int j=commonCellsIPtr[i]+1;j!=commonCellsIPtr[i+1];j++)
1964             {
1965               int sig=commonCellsPtr[j]>0?1:-1;
1966               int val=std::abs(commonCellsPtr[j])-1;
1967               if(val>=thisNbCells)
1968                 arr2Ptr[val-thisNbCells]=sig*(start+1);
1969             }
1970         }
1971     }
1972   arr2->setName(other->getName());
1973   if(arr2->presenceOfValue(0))
1974     return false;
1975   arr=arr2.retn();
1976   return true;
1977 }
1978
1979 MEDCouplingPointSet *MEDCouplingUMesh::mergeMyselfWithOnSameCoords(const MEDCouplingPointSet *other) const
1980 {
1981   if(!other)
1982     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::mergeMyselfWithOnSameCoords : input other is null !");
1983   const MEDCouplingUMesh *otherC=dynamic_cast<const MEDCouplingUMesh *>(other);
1984   if(!otherC)
1985     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::mergeMyselfWithOnSameCoords : the input other mesh is not of type unstructured !");
1986   std::vector<const MEDCouplingUMesh *> ms(2);
1987   ms[0]=this;
1988   ms[1]=otherC;
1989   return MergeUMeshesOnSameCoords(ms);
1990 }
1991
1992 /*!
1993  * Build a sub part of \b this lying or not on the same coordinates than \b this (regarding value of \b keepCoords).
1994  * By default coordinates are kept. This method is close to MEDCouplingUMesh::buildPartOfMySelf except that here input
1995  * cellIds is not given explicitely but by a range python like.
1996  * 
1997  * \param keepCoords that specifies if you want or not to keep coords as this or zip it (see ParaMEDMEM::MEDCouplingUMesh::zipCoords). If true zipCoords is \b NOT called, if false, zipCoords is called.
1998  * \return a newly allocated
1999  * 
2000  * \warning This method modifies can generate an unstructured mesh whose cells are not sorted by geometric type order.
2001  * In view of the MED file writing, a renumbering of cells of returned unstructured mesh (using MEDCouplingUMesh::sortCellsInMEDFileFrmt) should be necessary.
2002  */
2003 MEDCouplingPointSet *MEDCouplingUMesh::buildPartOfMySelf2(int start, int end, int step, bool keepCoords) const
2004 {
2005   if(getMeshDimension()!=-1)
2006     return MEDCouplingPointSet::buildPartOfMySelf2(start,end,step,keepCoords);
2007   else
2008     {
2009       int newNbOfCells=DataArray::GetNumberOfItemGivenBESRelative(start,end,step,"MEDCouplingUMesh::buildPartOfMySelf2 for -1 dimension mesh ");
2010       if(newNbOfCells!=1)
2011         throw INTERP_KERNEL::Exception("-1D mesh has only one cell !");
2012       if(start!=0)
2013         throw INTERP_KERNEL::Exception("-1D mesh has only one cell : 0 !");
2014       incrRef();
2015       return const_cast<MEDCouplingUMesh *>(this);
2016     }
2017 }
2018
2019 /*!
2020  * Creates a new MEDCouplingUMesh containing specified cells of \a this mesh.
2021  * The result mesh shares or not the node coordinates array with \a this mesh depending
2022  * on \a keepCoords parameter.
2023  *  \warning Cells of the result mesh can be \b not sorted by geometric type, hence,
2024  *           to write this mesh to the MED file, its cells must be sorted using
2025  *           sortCellsInMEDFileFrmt().
2026  *  \param [in] begin - an array of cell ids to include to the new mesh.
2027  *  \param [in] end - a pointer to last-plus-one-th element of \a begin.
2028  *  \param [in] keepCoords - if \c true, the result mesh shares the node coordinates
2029  *         array of \a this mesh, else "free" nodes are removed from the result mesh
2030  *         by calling zipCoords().
2031  *  \return MEDCouplingPointSet * - a new instance of MEDCouplingUMesh. The caller is
2032  *         to delete this mesh using decrRef() as it is no more needed. 
2033  *  \throw If the coordinates array is not set.
2034  *  \throw If the nodal connectivity of cells is not defined.
2035  *  \throw If any cell id in the array \a begin is not valid.
2036  *
2037  *  \if ENABLE_EXAMPLES
2038  *  \ref cpp_mcumesh_buildPartOfMySelf "Here is a C++ example".<br>
2039  *  \ref  py_mcumesh_buildPartOfMySelf "Here is a Python example".
2040  *  \endif
2041  */
2042 MEDCouplingPointSet *MEDCouplingUMesh::buildPartOfMySelf(const int *begin, const int *end, bool keepCoords) const
2043 {
2044   if(getMeshDimension()!=-1)
2045     return MEDCouplingPointSet::buildPartOfMySelf(begin,end,keepCoords);
2046   else
2047     {
2048       if(end-begin!=1)
2049         throw INTERP_KERNEL::Exception("-1D mesh has only one cell !");
2050       if(begin[0]!=0)
2051         throw INTERP_KERNEL::Exception("-1D mesh has only one cell : 0 !");
2052       incrRef();
2053       return const_cast<MEDCouplingUMesh *>(this);
2054     }
2055 }
2056
2057 /*!
2058  * This method operates only on nodal connectivity on \b this. Coordinates of \b this is completely ignored here.
2059  *
2060  * This method allows to partially modify some cells in \b this (whose list is specified by [ \b cellIdsBg, \b cellIdsEnd ) ) with cells coming in \b otherOnSameCoordsThanThis.
2061  * Size of [ \b cellIdsBg, \b cellIdsEnd ) ) must be equal to the number of cells of otherOnSameCoordsThanThis.
2062  * The number of cells of \b this will remain the same with this method.
2063  *
2064  * \param [in] begin begin of cell ids (included) of cells in this to assign
2065  * \param [in] end end of cell ids (excluded) of cells in this to assign
2066  * \param [in] otherOnSameCoordsThanThis an another mesh with same meshdimension than \b this with exactly the same number of cells than cell ids list in [\b cellIdsBg, \b cellIdsEnd ).
2067  *             Coordinate pointer of \b this and those of \b otherOnSameCoordsThanThis must be the same
2068  */
2069 void MEDCouplingUMesh::setPartOfMySelf(const int *cellIdsBg, const int *cellIdsEnd, const MEDCouplingUMesh& otherOnSameCoordsThanThis)
2070 {
2071   checkConnectivityFullyDefined();
2072   otherOnSameCoordsThanThis.checkConnectivityFullyDefined();
2073   if(getCoords()!=otherOnSameCoordsThanThis.getCoords())
2074     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::setPartOfMySelf : coordinates pointer are not the same ! Invoke setCoords or call tryToShareSameCoords method !");
2075   if(getMeshDimension()!=otherOnSameCoordsThanThis.getMeshDimension())
2076     {
2077       std::ostringstream oss; oss << "MEDCouplingUMesh::setPartOfMySelf : Mismatch of meshdimensions ! this is equal to " << getMeshDimension();
2078       oss << ", whereas other mesh dimension is set equal to " << otherOnSameCoordsThanThis.getMeshDimension() << " !";
2079       throw INTERP_KERNEL::Exception(oss.str().c_str());
2080     }
2081   int nbOfCellsToModify=(int)std::distance(cellIdsBg,cellIdsEnd);
2082   if(nbOfCellsToModify!=otherOnSameCoordsThanThis.getNumberOfCells())
2083     {
2084       std::ostringstream oss; oss << "MEDCouplingUMesh::setPartOfMySelf : cells ids length (" <<  nbOfCellsToModify << ") do not match the number of cells of other mesh (" << otherOnSameCoordsThanThis.getNumberOfCells() << ") !";
2085       throw INTERP_KERNEL::Exception(oss.str().c_str());
2086     }
2087   int nbOfCells=getNumberOfCells();
2088   bool easyAssign=true;
2089   const int *connI=_nodal_connec_index->getConstPointer();
2090   const int *connIOther=otherOnSameCoordsThanThis._nodal_connec_index->getConstPointer();
2091   for(const int *it=cellIdsBg;it!=cellIdsEnd && easyAssign;it++,connIOther++)
2092     {
2093       if(*it>=0 && *it<nbOfCells)
2094         {
2095           easyAssign=(connIOther[1]-connIOther[0])==(connI[*it+1]-connI[*it]);
2096         }
2097       else
2098         {
2099           std::ostringstream oss; oss << "MEDCouplingUMesh::setPartOfMySelf : On pos #" << std::distance(cellIdsBg,it) << " id is equal to " << *it << " which is not in [0," << nbOfCells << ") !";
2100           throw INTERP_KERNEL::Exception(oss.str().c_str());
2101         }
2102     }
2103   if(easyAssign)
2104     {
2105       MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx(cellIdsBg,cellIdsEnd,_nodal_connec,_nodal_connec_index,otherOnSameCoordsThanThis._nodal_connec,otherOnSameCoordsThanThis._nodal_connec_index);
2106       computeTypes();
2107     }
2108   else
2109     {
2110       DataArrayInt *arrOut=0,*arrIOut=0;
2111       MEDCouplingUMesh::SetPartOfIndexedArrays(cellIdsBg,cellIdsEnd,_nodal_connec,_nodal_connec_index,otherOnSameCoordsThanThis._nodal_connec,otherOnSameCoordsThanThis._nodal_connec_index,
2112                                                arrOut,arrIOut);
2113       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> arrOutAuto(arrOut),arrIOutAuto(arrIOut);
2114       setConnectivity(arrOut,arrIOut,true);
2115     }
2116 }
2117
2118 void MEDCouplingUMesh::setPartOfMySelf2(int start, int end, int step, const MEDCouplingUMesh& otherOnSameCoordsThanThis)
2119 {
2120   checkConnectivityFullyDefined();
2121   otherOnSameCoordsThanThis.checkConnectivityFullyDefined();
2122   if(getCoords()!=otherOnSameCoordsThanThis.getCoords())
2123     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::setPartOfMySelf2 : coordinates pointer are not the same ! Invoke setCoords or call tryToShareSameCoords method !");
2124   if(getMeshDimension()!=otherOnSameCoordsThanThis.getMeshDimension())
2125     {
2126       std::ostringstream oss; oss << "MEDCouplingUMesh::setPartOfMySelf2 : Mismatch of meshdimensions ! this is equal to " << getMeshDimension();
2127       oss << ", whereas other mesh dimension is set equal to " << otherOnSameCoordsThanThis.getMeshDimension() << " !";
2128       throw INTERP_KERNEL::Exception(oss.str().c_str());
2129     }
2130   int nbOfCellsToModify=DataArray::GetNumberOfItemGivenBESRelative(start,end,step,"MEDCouplingUMesh::setPartOfMySelf2 : ");
2131   if(nbOfCellsToModify!=otherOnSameCoordsThanThis.getNumberOfCells())
2132     {
2133       std::ostringstream oss; oss << "MEDCouplingUMesh::setPartOfMySelf2 : cells ids length (" <<  nbOfCellsToModify << ") do not match the number of cells of other mesh (" << otherOnSameCoordsThanThis.getNumberOfCells() << ") !";
2134       throw INTERP_KERNEL::Exception(oss.str().c_str());
2135     }
2136   int nbOfCells=getNumberOfCells();
2137   bool easyAssign=true;
2138   const int *connI=_nodal_connec_index->getConstPointer();
2139   const int *connIOther=otherOnSameCoordsThanThis._nodal_connec_index->getConstPointer();
2140   int it=start;
2141   for(int i=0;i<nbOfCellsToModify && easyAssign;i++,it+=step,connIOther++)
2142     {
2143       if(it>=0 && it<nbOfCells)
2144         {
2145           easyAssign=(connIOther[1]-connIOther[0])==(connI[it+1]-connI[it]);
2146         }
2147       else
2148         {
2149           std::ostringstream oss; oss << "MEDCouplingUMesh::setPartOfMySelf2 : On pos #" << i << " id is equal to " << it << " which is not in [0," << nbOfCells << ") !";
2150           throw INTERP_KERNEL::Exception(oss.str().c_str());
2151         }
2152     }
2153   if(easyAssign)
2154     {
2155       MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx2(start,end,step,_nodal_connec,_nodal_connec_index,otherOnSameCoordsThanThis._nodal_connec,otherOnSameCoordsThanThis._nodal_connec_index);
2156       computeTypes();
2157     }
2158   else
2159     {
2160       DataArrayInt *arrOut=0,*arrIOut=0;
2161       MEDCouplingUMesh::SetPartOfIndexedArrays2(start,end,step,_nodal_connec,_nodal_connec_index,otherOnSameCoordsThanThis._nodal_connec,otherOnSameCoordsThanThis._nodal_connec_index,
2162                                                 arrOut,arrIOut);
2163       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> arrOutAuto(arrOut),arrIOutAuto(arrIOut);
2164       setConnectivity(arrOut,arrIOut,true);
2165     }
2166 }                      
2167
2168 /*!
2169  * Keeps from \a this only cells which constituing point id are in the ids specified by [ \a begin,\a end ).
2170  * The resulting cell ids are stored at the end of the 'cellIdsKept' parameter.
2171  * Parameter \a fullyIn specifies if a cell that has part of its nodes in ids array is kept or not.
2172  * If \a fullyIn is true only cells whose ids are \b fully contained in [ \a begin,\a end ) tab will be kept.
2173  *
2174  * \param [in] begin input start of array of node ids.
2175  * \param [in] end input end of array of node ids.
2176  * \param [in] fullyIn input that specifies if all node ids must be in [ \a begin,\a end ) array to consider cell to be in.
2177  * \param [in,out] cellIdsKeptArr array where all candidate cell ids are put at the end.
2178  */
2179 void MEDCouplingUMesh::fillCellIdsToKeepFromNodeIds(const int *begin, const int *end, bool fullyIn, DataArrayInt *&cellIdsKeptArr) const
2180 {
2181   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> cellIdsKept=DataArrayInt::New(); cellIdsKept->alloc(0,1);
2182   checkConnectivityFullyDefined();
2183   int tmp=-1;
2184   int sz=getNodalConnectivity()->getMaxValue(tmp); sz=std::max(sz,0)+1;
2185   std::vector<bool> fastFinder(sz,false);
2186   for(const int *work=begin;work!=end;work++)
2187     if(*work>=0 && *work<sz)
2188       fastFinder[*work]=true;
2189   int nbOfCells=getNumberOfCells();
2190   const int *conn=getNodalConnectivity()->getConstPointer();
2191   const int *connIndex=getNodalConnectivityIndex()->getConstPointer();
2192   for(int i=0;i<nbOfCells;i++)
2193     {
2194       int ref=0,nbOfHit=0;
2195       for(const int *work2=conn+connIndex[i]+1;work2!=conn+connIndex[i+1];work2++)
2196         if(*work2>=0)
2197           {
2198             ref++;
2199             if(fastFinder[*work2])
2200               nbOfHit++;
2201           }
2202       if((ref==nbOfHit && fullyIn) || (nbOfHit!=0 && !fullyIn))
2203         cellIdsKept->pushBackSilent(i);
2204     }
2205   cellIdsKeptArr=cellIdsKept.retn();
2206 }
2207
2208 /*!
2209  * Creates a new MEDCouplingUMesh containing cells, of dimension one less than \a
2210  * this->getMeshDimension(), that bound some cells of \a this mesh.
2211  * The cells of lower dimension to include to the result mesh are selected basing on
2212  * specified node ids and the value of \a fullyIn parameter. If \a fullyIn ==\c true, a
2213  * cell is copied if its all nodes are in the array \a begin of node ids. If \a fullyIn
2214  * ==\c false, a cell is copied if any its node is in the array of node ids. The
2215  * created mesh shares the node coordinates array with \a this mesh. 
2216  *  \param [in] begin - the array of node ids.
2217  *  \param [in] end - a pointer to the (last+1)-th element of \a begin.
2218  *  \param [in] fullyIn - if \c true, then cells whose all nodes are in the
2219  *         array \a begin are added, else cells whose any node is in the
2220  *         array \a begin are added.
2221  *  \return MEDCouplingPointSet * - new instance of MEDCouplingUMesh. The caller is
2222  *         to delete this mesh using decrRef() as it is no more needed. 
2223  *  \throw If the coordinates array is not set.
2224  *  \throw If the nodal connectivity of cells is not defined.
2225  *  \throw If any node id in \a begin is not valid.
2226  *
2227  *  \if ENABLE_EXAMPLES
2228  *  \ref cpp_mcumesh_buildFacePartOfMySelfNode "Here is a C++ example".<br>
2229  *  \ref  py_mcumesh_buildFacePartOfMySelfNode "Here is a Python example".
2230  *  \endif
2231  */
2232 MEDCouplingPointSet *MEDCouplingUMesh::buildFacePartOfMySelfNode(const int *begin, const int *end, bool fullyIn) const
2233 {
2234   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> desc,descIndx,revDesc,revDescIndx;
2235   desc=DataArrayInt::New(); descIndx=DataArrayInt::New(); revDesc=DataArrayInt::New(); revDescIndx=DataArrayInt::New();
2236   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> subMesh=buildDescendingConnectivity(desc,descIndx,revDesc,revDescIndx);
2237   desc=0; descIndx=0; revDesc=0; revDescIndx=0;
2238   return subMesh->buildPartOfMySelfNode(begin,end,fullyIn);
2239 }
2240
2241 /*!
2242  * Creates a new MEDCouplingUMesh containing cells, of dimension one less than \a
2243  * this->getMeshDimension(), which bound only one cell of \a this mesh.
2244  *  \param [in] keepCoords - if \c true, the result mesh shares the node coordinates
2245  *         array of \a this mesh, else "free" nodes are removed from the result mesh
2246  *         by calling zipCoords().
2247  *  \return MEDCouplingPointSet * - a new instance of MEDCouplingUMesh. The caller is
2248  *         to delete this mesh using decrRef() as it is no more needed. 
2249  *  \throw If the coordinates array is not set.
2250  *  \throw If the nodal connectivity of cells is not defined.
2251  *
2252  *  \if ENABLE_EXAMPLES
2253  *  \ref cpp_mcumesh_buildBoundaryMesh "Here is a C++ example".<br>
2254  *  \ref  py_mcumesh_buildBoundaryMesh "Here is a Python example".
2255  *  \endif
2256  */
2257 MEDCouplingPointSet *MEDCouplingUMesh::buildBoundaryMesh(bool keepCoords) const
2258 {
2259   DataArrayInt *desc=DataArrayInt::New();
2260   DataArrayInt *descIndx=DataArrayInt::New();
2261   DataArrayInt *revDesc=DataArrayInt::New();
2262   DataArrayInt *revDescIndx=DataArrayInt::New();
2263   //
2264   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> meshDM1=buildDescendingConnectivity(desc,descIndx,revDesc,revDescIndx);
2265   revDesc->decrRef();
2266   desc->decrRef();
2267   descIndx->decrRef();
2268   int nbOfCells=meshDM1->getNumberOfCells();
2269   const int *revDescIndxC=revDescIndx->getConstPointer();
2270   std::vector<int> boundaryCells;
2271   for(int i=0;i<nbOfCells;i++)
2272     if(revDescIndxC[i+1]-revDescIndxC[i]==1)
2273       boundaryCells.push_back(i);
2274   revDescIndx->decrRef();
2275   MEDCouplingPointSet *ret=meshDM1->buildPartOfMySelf(&boundaryCells[0],&boundaryCells[0]+boundaryCells.size(),keepCoords);
2276   return ret;
2277 }
2278
2279 /*!
2280  * This method returns a newly created DataArrayInt instance containing ids of cells located in boundary.
2281  * A cell is detected to be on boundary if it contains one or more than one face having only one father.
2282  * This method makes the assumption that \a this is fully defined (coords,connectivity). If not an exception will be thrown. 
2283  */
2284 DataArrayInt *MEDCouplingUMesh::findCellIdsOnBoundary() const
2285 {
2286   checkFullyDefined();
2287   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> desc=DataArrayInt::New();
2288   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> descIndx=DataArrayInt::New();
2289   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revDesc=DataArrayInt::New();
2290   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revDescIndx=DataArrayInt::New();
2291   //
2292   buildDescendingConnectivity(desc,descIndx,revDesc,revDescIndx)->decrRef();
2293   desc=(DataArrayInt*)0; descIndx=(DataArrayInt*)0;
2294   //
2295   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp=revDescIndx->deltaShiftIndex();
2296   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> faceIds=tmp->getIdsEqual(1); tmp=(DataArrayInt*)0;
2297   const int *revDescPtr=revDesc->getConstPointer();
2298   const int *revDescIndxPtr=revDescIndx->getConstPointer();
2299   int nbOfCells=getNumberOfCells();
2300   std::vector<bool> ret1(nbOfCells,false);
2301   int sz=0;
2302   for(const int *pt=faceIds->begin();pt!=faceIds->end();pt++)
2303     if(!ret1[revDescPtr[revDescIndxPtr[*pt]]])
2304       { ret1[revDescPtr[revDescIndxPtr[*pt]]]=true; sz++; }
2305   //
2306   DataArrayInt *ret2=DataArrayInt::New();
2307   ret2->alloc(sz,1);
2308   int *ret2Ptr=ret2->getPointer();
2309   sz=0;
2310   for(std::vector<bool>::const_iterator it=ret1.begin();it!=ret1.end();it++,sz++)
2311     if(*it)
2312       *ret2Ptr++=sz;
2313   ret2->setName("BoundaryCells");
2314   return ret2;
2315 }
2316
2317 /*!
2318  * This method find in \b this cells ids that lie on mesh \b otherDimM1OnSameCoords.
2319  * \b this and \b otherDimM1OnSameCoords have to lie on the same coordinate array pointer. The coherency of that coords array with connectivity
2320  * of \b this and \b otherDimM1OnSameCoords is not important here because this method works only on connectivity.
2321  * this->getMeshDimension() - 1 must be equal to otherDimM1OnSameCoords.getMeshDimension()
2322  *
2323  * s0 is the cells ids set in \b this lying on at least one node in fetched nodes in \b otherDimM1OnSameCoords.
2324  * This method method returns cells ids set s = s1 + s2 where :
2325  * 
2326  *  - s1 are cells ids in \b this whose dim-1 constituent equals a cell in \b otherDimM1OnSameCoords.
2327  *  - s2 are cells ids in \b s0 - \b s1 whose at least two neighbors are in s1.
2328  *
2329  * \throw if \b otherDimM1OnSameCoords is not part of constituent of \b this, or if coordinate pointer of \b this and \b otherDimM1OnSameCoords
2330  *        are not same, or if this->getMeshDimension()-1!=otherDimM1OnSameCoords.getMeshDimension()
2331  *
2332  * \param [out] cellIdsRk0 a newly allocated array containing cells ids in \b this containg s0 in above algorithm.
2333  * \param [out] cellIdsRk1 a newly allocated array containing cells ids of s1+s2 \b into \b cellIdsRk0 subset. To get absolute ids of s1+s2 simply invoke
2334  *              cellIdsRk1->transformWithIndArr(cellIdsRk0->begin(),cellIdsRk0->end());
2335  */
2336 void MEDCouplingUMesh::findCellIdsLyingOn(const MEDCouplingUMesh& otherDimM1OnSameCoords, DataArrayInt *&cellIdsRk0, DataArrayInt *&cellIdsRk1) const
2337 {
2338   if(getCoords()!=otherDimM1OnSameCoords.getCoords())
2339     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::findCellIdsLyingOn : coordinates pointer are not the same ! Use tryToShareSameCoords method !");
2340   checkConnectivityFullyDefined();
2341   otherDimM1OnSameCoords.checkConnectivityFullyDefined();
2342   if(getMeshDimension()-1!=otherDimM1OnSameCoords.getMeshDimension())
2343     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::findCellIdsLyingOn : invalid mesh dimension of input mesh regarding meshdimesion of this !");
2344   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> fetchedNodeIds1=otherDimM1OnSameCoords.computeFetchedNodeIds();
2345   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> s0arr=getCellIdsLyingOnNodes(fetchedNodeIds1->begin(),fetchedNodeIds1->end(),false);
2346   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> thisPart=static_cast<MEDCouplingUMesh *>(buildPartOfMySelf(s0arr->begin(),s0arr->end(),true));
2347   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> descThisPart=DataArrayInt::New(),descIThisPart=DataArrayInt::New(),revDescThisPart=DataArrayInt::New(),revDescIThisPart=DataArrayInt::New();
2348   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> thisPartConsti=thisPart->buildDescendingConnectivity(descThisPart,descIThisPart,revDescThisPart,revDescIThisPart);
2349   const int *revDescThisPartPtr=revDescThisPart->getConstPointer(),*revDescIThisPartPtr=revDescIThisPart->getConstPointer();
2350   DataArrayInt *idsOtherInConsti=0;
2351   bool b=thisPartConsti->areCellsIncludedIn(&otherDimM1OnSameCoords,2,idsOtherInConsti);
2352   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> idsOtherInConstiAuto(idsOtherInConsti);
2353   if(!b)
2354     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::findCellIdsLyingOn : the given mdim-1 mesh in other is not a constituent of this !");
2355   std::set<int> s1;
2356   for(const int *idOther=idsOtherInConsti->begin();idOther!=idsOtherInConsti->end();idOther++)
2357     s1.insert(revDescThisPartPtr+revDescIThisPartPtr[*idOther],revDescThisPartPtr+revDescIThisPartPtr[*idOther+1]);
2358   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> s1arr_renum1=DataArrayInt::New(); s1arr_renum1->alloc((int)s1.size(),1); std::copy(s1.begin(),s1.end(),s1arr_renum1->getPointer());
2359   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> s1Comparr_renum1=s1arr_renum1->buildComplement(s0arr->getNumberOfTuples());
2360   DataArrayInt *neighThisPart=0,*neighIThisPart=0;
2361   ComputeNeighborsOfCellsAdv(descThisPart,descIThisPart,revDescThisPart,revDescIThisPart,neighThisPart,neighIThisPart);
2362   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> neighThisPartAuto(neighThisPart),neighIThisPartAuto(neighIThisPart);
2363   ExtractFromIndexedArrays(s1Comparr_renum1->begin(),s1Comparr_renum1->end(),neighThisPart,neighIThisPart,neighThisPart,neighIThisPart);// reuse of neighThisPart and neighIThisPart
2364   neighThisPartAuto=neighThisPart; neighIThisPartAuto=neighIThisPart;
2365   RemoveIdsFromIndexedArrays(s1Comparr_renum1->begin(),s1Comparr_renum1->end(),neighThisPart,neighIThisPart);
2366   neighThisPartAuto=0;
2367   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> s2_tmp=neighIThisPart->deltaShiftIndex();
2368   const int li[2]={0,1};
2369   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> s2_renum2=s2_tmp->getIdsNotEqualList(li,li+2);
2370   s2_renum2->transformWithIndArr(s1Comparr_renum1->begin(),s1Comparr_renum1->end());//s2_renum2==s2_renum1
2371   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> s_renum1=DataArrayInt::Aggregate(s2_renum2,s1arr_renum1,0);
2372   s_renum1->sort();
2373   //
2374   cellIdsRk0=s0arr.retn();
2375   cellIdsRk1=s_renum1.retn();
2376 }
2377
2378 /*!
2379  * This method computes the skin of \b this. That is to say the consituting meshdim-1 mesh is built and only the boundary subpart is
2380  * returned. This subpart of meshdim-1 mesh is built using meshdim-1 cells in it shared only one cell in \b this.
2381  * 
2382  * \return a newly allocated mesh lying on the same coordinates than \b this. The caller has to deal with returned mesh.
2383  */
2384 MEDCouplingUMesh *MEDCouplingUMesh::computeSkin() const
2385 {
2386   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> desc=DataArrayInt::New();
2387   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> descIndx=DataArrayInt::New();
2388   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revDesc=DataArrayInt::New();
2389   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revDescIndx=DataArrayInt::New();
2390   //
2391   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> meshDM1=buildDescendingConnectivity(desc,descIndx,revDesc,revDescIndx);
2392   revDesc=0; desc=0; descIndx=0;
2393   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revDescIndx2=revDescIndx->deltaShiftIndex();
2394   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> part=revDescIndx2->getIdsEqual(1);
2395   return static_cast<MEDCouplingUMesh *>(meshDM1->buildPartOfMySelf(part->begin(),part->end(),true));
2396 }
2397
2398 /*!
2399  * Finds nodes lying on the boundary of \a this mesh.
2400  *  \return DataArrayInt * - a new instance of DataArrayInt holding ids of found
2401  *          nodes. The caller is to delete this array using decrRef() as it is no
2402  *          more needed.
2403  *  \throw If the coordinates array is not set.
2404  *  \throw If the nodal connectivity of cells is node defined.
2405  *
2406  *  \if ENABLE_EXAMPLES
2407  *  \ref cpp_mcumesh_findBoundaryNodes "Here is a C++ example".<br>
2408  *  \ref  py_mcumesh_findBoundaryNodes "Here is a Python example".
2409  *  \endif
2410  */
2411 DataArrayInt *MEDCouplingUMesh::findBoundaryNodes() const
2412 {
2413   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> skin=computeSkin();
2414   return skin->computeFetchedNodeIds();
2415 }
2416
2417 MEDCouplingUMesh *MEDCouplingUMesh::buildUnstructured() const
2418 {
2419   incrRef();
2420   return const_cast<MEDCouplingUMesh *>(this);
2421 }
2422
2423 /*!
2424  * This method expects that \b this and \b otherDimM1OnSameCoords share the same coordinates array.
2425  * otherDimM1OnSameCoords->getMeshDimension() is expected to be equal to this->getMeshDimension()-1.
2426  * This method searches for nodes needed to be duplicated. These nodes are nodes fetched by \b otherDimM1OnSameCoords which are not part of the boundary of \b otherDimM1OnSameCoords.
2427  * If a node is in the boundary of \b this \b and in the boundary of \b otherDimM1OnSameCoords this node is considerd as needed to be duplicated.
2428  * When the set of node ids \b nodeIdsToDuplicate is computed, cell ids in \b this is searched so that their connectivity includes at least 1 node in \b nodeIdsToDuplicate.
2429  *
2430  * \param [in] otherDimM1OnSameCoords a mesh lying on the same coords than \b this and with a mesh dimension equal to those of \b this minus 1. WARNING this input
2431  *             parameter is altered during the call.
2432  * \param [out] nodeIdsToDuplicate node ids needed to be duplicated following the algorithm explain above.
2433  * \param [out] cellIdsNeededToBeRenum cell ids in \b this in which the renumber of nodes should be performed.
2434  * \param [out] cellIdsNotModified cell ids int \b this that lies on \b otherDimM1OnSameCoords mesh whose connectivity do \b not need to be modified as it is the case for \b cellIdsNeededToBeRenum.
2435  *
2436  * \warning This method modifies param \b otherDimM1OnSameCoords (for speed reasons).
2437  */
2438 void MEDCouplingUMesh::findNodesToDuplicate(const MEDCouplingUMesh& otherDimM1OnSameCoords, DataArrayInt *& nodeIdsToDuplicate,
2439                                             DataArrayInt *& cellIdsNeededToBeRenum, DataArrayInt *& cellIdsNotModified) const
2440 {
2441   checkFullyDefined();
2442   otherDimM1OnSameCoords.checkFullyDefined();
2443   if(getCoords()!=otherDimM1OnSameCoords.getCoords())
2444     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::findNodesToDuplicate : meshes do not share the same coords array !");
2445   if(otherDimM1OnSameCoords.getMeshDimension()!=getMeshDimension()-1)
2446     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::findNodesToDuplicate : the mesh given in other parameter must have this->getMeshDimension()-1 !");
2447   DataArrayInt *cellIdsRk0=0,*cellIdsRk1=0;
2448   findCellIdsLyingOn(otherDimM1OnSameCoords,cellIdsRk0,cellIdsRk1);
2449   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> cellIdsRk0Auto(cellIdsRk0),cellIdsRk1Auto(cellIdsRk1);
2450   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> s0=cellIdsRk1->buildComplement(cellIdsRk0->getNumberOfTuples());
2451   s0->transformWithIndArr(cellIdsRk0Auto->begin(),cellIdsRk0Auto->end());
2452   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m0Part=static_cast<MEDCouplingUMesh *>(buildPartOfMySelf(s0->begin(),s0->end(),true));
2453   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> s1=m0Part->computeFetchedNodeIds();
2454   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> s2=otherDimM1OnSameCoords.computeFetchedNodeIds();
2455   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> s3=s2->buildSubstraction(s1);
2456   cellIdsRk1->transformWithIndArr(cellIdsRk0Auto->begin(),cellIdsRk0Auto->end());
2457   //
2458   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m0Part2=static_cast<MEDCouplingUMesh *>(buildPartOfMySelf(cellIdsRk1->begin(),cellIdsRk1->end(),true));
2459   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> desc00=DataArrayInt::New(),descI00=DataArrayInt::New(),revDesc00=DataArrayInt::New(),revDescI00=DataArrayInt::New();
2460   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m01=m0Part2->buildDescendingConnectivity(desc00,descI00,revDesc00,revDescI00);
2461   DataArrayInt *idsTmp=0;
2462   bool b=m01->areCellsIncludedIn(&otherDimM1OnSameCoords,2,idsTmp);
2463   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ids(idsTmp);
2464   if(!b)
2465     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::findNodesToDuplicate : the given mdim-1 mesh in other is not a constituent of this !");
2466   MEDCouplingUMesh::RemoveIdsFromIndexedArrays(ids->begin(),ids->end(),desc00,descI00);
2467   DataArrayInt *tmp0=0,*tmp1=0;
2468   ComputeNeighborsOfCellsAdv(desc00,descI00,revDesc00,revDescI00,tmp0,tmp1);
2469   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> neigh00(tmp0);
2470   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> neighI00(tmp1);
2471   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> cellsToModifyConn0_torenum=MEDCouplingUMesh::ComputeSpreadZoneGradually(neigh00,neighI00);
2472   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> cellsToModifyConn1_torenum=cellsToModifyConn0_torenum->buildComplement(neighI00->getNumberOfTuples()-1);
2473   cellsToModifyConn0_torenum->transformWithIndArr(cellIdsRk1->begin(),cellIdsRk1->end());
2474   cellsToModifyConn1_torenum->transformWithIndArr(cellIdsRk1->begin(),cellIdsRk1->end());
2475   //
2476   cellIdsNeededToBeRenum=cellsToModifyConn0_torenum.retn();
2477   cellIdsNotModified=cellsToModifyConn1_torenum.retn();
2478   nodeIdsToDuplicate=s3.retn();
2479 }
2480
2481 /*!
2482  * This method operates a modification of the connectivity and coords in \b this.
2483  * Every time that a node id in [ \b nodeIdsToDuplicateBg, \b nodeIdsToDuplicateEnd ) will append in nodal connectivity of \b this 
2484  * its ids will be modified to id this->getNumberOfNodes()+std::distance(nodeIdsToDuplicateBg,std::find(nodeIdsToDuplicateBg,nodeIdsToDuplicateEnd,id)).
2485  * More explicitely the renumber array in nodes is not explicitely given in old2new to avoid to build a big array of renumbering whereas typically few node ids needs to be
2486  * renumbered. The node id nodeIdsToDuplicateBg[0] will have id this->getNumberOfNodes()+0, node id nodeIdsToDuplicateBg[1] will have id this->getNumberOfNodes()+1,
2487  * node id nodeIdsToDuplicateBg[2] will have id this->getNumberOfNodes()+2...
2488  * 
2489  * As a consequence nodal connectivity array length will remain unchanged by this method, and nodal connectivity index array will remain unchanged by this method.
2490  * 
2491  * \param [in] nodeIdsToDuplicateBg begin of node ids (included) to be duplicated in connectivity only
2492  * \param [in] nodeIdsToDuplicateEnd end of node ids (excluded) to be duplicated in connectivity only
2493  */
2494 void MEDCouplingUMesh::duplicateNodes(const int *nodeIdsToDuplicateBg, const int *nodeIdsToDuplicateEnd)
2495 {
2496   int nbOfNodes=getNumberOfNodes();
2497   duplicateNodesInCoords(nodeIdsToDuplicateBg,nodeIdsToDuplicateEnd);
2498   duplicateNodesInConn(nodeIdsToDuplicateBg,nodeIdsToDuplicateEnd,nbOfNodes);
2499 }
2500
2501 /*!
2502  * This method renumbers only nodal connectivity in \a this. The renumbering is only an offset applied. So this method is a specialization of
2503  * \a renumberNodesInConn. \b WARNING, this method does not check that the resulting node ids in the nodal connectivity is in a valid range !
2504  *
2505  * \param [in] offset - specifies the offset to be applied on each element of connectivity.
2506  *
2507  * \sa renumberNodesInConn
2508  */
2509 void MEDCouplingUMesh::renumberNodesWithOffsetInConn(int offset)
2510 {
2511   checkConnectivityFullyDefined();
2512   int *conn(getNodalConnectivity()->getPointer());
2513   const int *connIndex(getNodalConnectivityIndex()->getConstPointer());
2514   int nbOfCells(getNumberOfCells());
2515   for(int i=0;i<nbOfCells;i++)
2516     for(int iconn=connIndex[i]+1;iconn!=connIndex[i+1];iconn++)
2517       {
2518         int& node=conn[iconn];
2519         if(node>=0)//avoid polyhedron separator
2520           {
2521             node+=offset;
2522           }
2523       }
2524   _nodal_connec->declareAsNew();
2525   updateTime();
2526 }
2527
2528 /*!
2529  *  Same than renumberNodesInConn(const int *) except that here the format of old-to-new traducer is using map instead
2530  *  of array. This method is dedicated for renumbering from a big set of nodes the a tiny set of nodes which is the case during extraction
2531  *  of a big mesh.
2532  */
2533 void MEDCouplingUMesh::renumberNodesInConn(const INTERP_KERNEL::HashMap<int,int>& newNodeNumbersO2N)
2534 {
2535   checkConnectivityFullyDefined();
2536   int *conn(getNodalConnectivity()->getPointer());
2537   const int *connIndex(getNodalConnectivityIndex()->getConstPointer());
2538   int nbOfCells(getNumberOfCells());
2539   for(int i=0;i<nbOfCells;i++)
2540     for(int iconn=connIndex[i]+1;iconn!=connIndex[i+1];iconn++)
2541       {
2542         int& node=conn[iconn];
2543         if(node>=0)//avoid polyhedron separator
2544           {
2545             INTERP_KERNEL::HashMap<int,int>::const_iterator it(newNodeNumbersO2N.find(node));
2546             if(it!=newNodeNumbersO2N.end())
2547               {
2548                 node=(*it).second;
2549               }
2550             else
2551               {
2552                 std::ostringstream oss; oss << "MEDCouplingUMesh::renumberNodesInConn(map) : presence in connectivity for cell #" << i << " of node #" << node << " : Not in map !";
2553                 throw INTERP_KERNEL::Exception(oss.str().c_str());
2554               }
2555           }
2556       }
2557   _nodal_connec->declareAsNew();
2558   updateTime();
2559 }
2560
2561 /*!
2562  * Changes ids of nodes within the nodal connectivity arrays according to a permutation
2563  * array in "Old to New" mode. The node coordinates array is \b not changed by this method.
2564  * This method is a generalization of shiftNodeNumbersInConn().
2565  *  \warning This method performs no check of validity of new ids. **Use it with care !**
2566  *  \param [in] newNodeNumbersO2N - a permutation array, of length \a
2567  *         this->getNumberOfNodes(), in "Old to New" mode. 
2568  *         See \ref MEDCouplingArrayRenumbering for more info on renumbering modes.
2569  *  \throw If the nodal connectivity of cells is not defined.
2570  *
2571  *  \if ENABLE_EXAMPLES
2572  *  \ref cpp_mcumesh_renumberNodesInConn "Here is a C++ example".<br>
2573  *  \ref  py_mcumesh_renumberNodesInConn "Here is a Python example".
2574  *  \endif
2575  */
2576 void MEDCouplingUMesh::renumberNodesInConn(const int *newNodeNumbersO2N)
2577 {
2578   checkConnectivityFullyDefined();
2579   int *conn=getNodalConnectivity()->getPointer();
2580   const int *connIndex=getNodalConnectivityIndex()->getConstPointer();
2581   int nbOfCells(getNumberOfCells());
2582   for(int i=0;i<nbOfCells;i++)
2583     for(int iconn=connIndex[i]+1;iconn!=connIndex[i+1];iconn++)
2584       {
2585         int& node=conn[iconn];
2586         if(node>=0)//avoid polyhedron separator
2587           {
2588             node=newNodeNumbersO2N[node];
2589           }
2590       }
2591   _nodal_connec->declareAsNew();
2592   updateTime();
2593 }
2594
2595 /*!
2596  * This method renumbers nodes \b in \b connectivity \b only \b without \b any \b reference \b to \b coords.
2597  * This method performs no check on the fact that new coordinate ids are valid. \b Use \b it \b with \b care !
2598  * This method is an specialization of \ref ParaMEDMEM::MEDCouplingUMesh::renumberNodesInConn "renumberNodesInConn method".
2599  * 
2600  * \param [in] delta specifies the shift size applied to nodeId in nodal connectivity in \b this.
2601  */
2602 void MEDCouplingUMesh::shiftNodeNumbersInConn(int delta)
2603 {
2604   checkConnectivityFullyDefined();
2605   int *conn=getNodalConnectivity()->getPointer();
2606   const int *connIndex=getNodalConnectivityIndex()->getConstPointer();
2607   int nbOfCells=getNumberOfCells();
2608   for(int i=0;i<nbOfCells;i++)
2609     for(int iconn=connIndex[i]+1;iconn!=connIndex[i+1];iconn++)
2610       {
2611         int& node=conn[iconn];
2612         if(node>=0)//avoid polyhedron separator
2613           {
2614             node+=delta;
2615           }
2616       }
2617   _nodal_connec->declareAsNew();
2618   updateTime();
2619 }
2620
2621 /*!
2622  * This method operates a modification of the connectivity in \b this.
2623  * Coordinates are \b NOT considered here and will remain unchanged by this method. this->_coords can ever been null for the needs of this method.
2624  * Every time that a node id in [ \b nodeIdsToDuplicateBg, \b nodeIdsToDuplicateEnd ) will append in nodal connectivity of \b this 
2625  * its ids will be modified to id offset+std::distance(nodeIdsToDuplicateBg,std::find(nodeIdsToDuplicateBg,nodeIdsToDuplicateEnd,id)).
2626  * More explicitely the renumber array in nodes is not explicitely given in old2new to avoid to build a big array of renumbering whereas typically few node ids needs to be
2627  * renumbered. The node id nodeIdsToDuplicateBg[0] will have id offset+0, node id nodeIdsToDuplicateBg[1] will have id offset+1,
2628  * node id nodeIdsToDuplicateBg[2] will have id offset+2...
2629  * 
2630  * As a consequence nodal connectivity array length will remain unchanged by this method, and nodal connectivity index array will remain unchanged by this method.
2631  * As an another consequense after the call of this method \b this can be transiently non cohrent.
2632  * 
2633  * \param [in] nodeIdsToDuplicateBg begin of node ids (included) to be duplicated in connectivity only
2634  * \param [in] nodeIdsToDuplicateEnd end of node ids (excluded) to be duplicated in connectivity only
2635  * \param [in] offset the offset applied to all node ids in connectivity that are in [ \a nodeIdsToDuplicateBg, \a nodeIdsToDuplicateEnd ). 
2636  */
2637 void MEDCouplingUMesh::duplicateNodesInConn(const int *nodeIdsToDuplicateBg, const int *nodeIdsToDuplicateEnd, int offset)
2638 {
2639   checkConnectivityFullyDefined();
2640   std::map<int,int> m;
2641   int val=offset;
2642   for(const int *work=nodeIdsToDuplicateBg;work!=nodeIdsToDuplicateEnd;work++,val++)
2643     m[*work]=val;
2644   int *conn=getNodalConnectivity()->getPointer();
2645   const int *connIndex=getNodalConnectivityIndex()->getConstPointer();
2646   int nbOfCells=getNumberOfCells();
2647   for(int i=0;i<nbOfCells;i++)
2648     for(int iconn=connIndex[i]+1;iconn!=connIndex[i+1];iconn++)
2649       {
2650         int& node=conn[iconn];
2651         if(node>=0)//avoid polyhedron separator
2652           {
2653             std::map<int,int>::iterator it=m.find(node);
2654             if(it!=m.end())
2655               node=(*it).second;
2656           }
2657       }
2658   updateTime();
2659 }
2660
2661 /*!
2662  * This method renumbers cells of \a this using the array specified by [old2NewBg;old2NewBg+getNumberOfCells())
2663  *
2664  * Contrary to MEDCouplingPointSet::renumberNodes, this method makes a permutation without any fuse of cell.
2665  * After the call of this method the number of cells remains the same as before.
2666  *
2667  * If 'check' equals true the method will check that any elements in [ \a old2NewBg; \a old2NewEnd ) is unique ; if not
2668  * an INTERP_KERNEL::Exception will be thrown. When 'check' equals true [ \a old2NewBg ; \a old2NewEnd ) is not expected to
2669  * be strictly in [0;this->getNumberOfCells()).
2670  *
2671  * If 'check' equals false the method will not check the content of [ \a old2NewBg ; \a old2NewEnd ).
2672  * To avoid any throw of SIGSEGV when 'check' equals false, the elements in [ \a old2NewBg ; \a old2NewEnd ) should be unique and
2673  * should be contained in[0;this->getNumberOfCells()).
2674  * 
2675  * \param [in] old2NewBg is expected to be a dynamically allocated pointer of size at least equal to this->getNumberOfCells()
2676  */
2677 void MEDCouplingUMesh::renumberCells(const int *old2NewBg, bool check)
2678 {
2679   checkConnectivityFullyDefined();
2680   int nbCells=getNumberOfCells();
2681   const int *array=old2NewBg;
2682   if(check)
2683     array=DataArrayInt::CheckAndPreparePermutation(old2NewBg,old2NewBg+nbCells);
2684   //
2685   const int *conn=_nodal_connec->getConstPointer();
2686   const int *connI=_nodal_connec_index->getConstPointer();
2687   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> o2n=DataArrayInt::New(); o2n->useArray(array,false,C_DEALLOC,nbCells,1);
2688   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> n2o=o2n->invertArrayO2N2N2O(nbCells);
2689   const int *n2oPtr=n2o->begin();
2690   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConn=DataArrayInt::New();
2691   newConn->alloc(_nodal_connec->getNumberOfTuples(),_nodal_connec->getNumberOfComponents());
2692   newConn->copyStringInfoFrom(*_nodal_connec);
2693   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConnI=DataArrayInt::New();
2694   newConnI->alloc(_nodal_connec_index->getNumberOfTuples(),_nodal_connec_index->getNumberOfComponents());
2695   newConnI->copyStringInfoFrom(*_nodal_connec_index);
2696   //
2697   int *newC=newConn->getPointer();
2698   int *newCI=newConnI->getPointer();
2699   int loc=0;
2700   newCI[0]=loc;
2701   for(int i=0;i<nbCells;i++)
2702     {
2703       int pos=n2oPtr[i];
2704       int nbOfElts=connI[pos+1]-connI[pos];
2705       newC=std::copy(conn+connI[pos],conn+connI[pos+1],newC);
2706       loc+=nbOfElts;
2707       newCI[i+1]=loc;
2708     }
2709   //
2710   setConnectivity(newConn,newConnI);
2711   if(check)
2712     free(const_cast<int *>(array));
2713 }
2714
2715 /*!
2716  * Finds cells whose bounding boxes intersect a given bounding box.
2717  *  \param [in] bbox - an array defining the bounding box via coordinates of its
2718  *         extremum points in "no interlace" mode, i.e. xMin, xMax, yMin, yMax, zMin,
2719  *         zMax (if in 3D). 
2720  *  \param [in] eps - a factor used to increase size of the bounding box of cell
2721  *         before comparing it with \a bbox. This factor is multiplied by the maximal
2722  *         extent of the bounding box of cell to produce an addition to this bounding box.
2723  *  \return DataArrayInt * - a new instance of DataArrayInt holding ids for found
2724  *         cells. The caller is to delete this array using decrRef() as it is no more
2725  *         needed. 
2726  *  \throw If the coordinates array is not set.
2727  *  \throw If the nodal connectivity of cells is not defined.
2728  *
2729  *  \if ENABLE_EXAMPLES
2730  *  \ref cpp_mcumesh_getCellsInBoundingBox "Here is a C++ example".<br>
2731  *  \ref  py_mcumesh_getCellsInBoundingBox "Here is a Python example".
2732  *  \endif
2733  */
2734 DataArrayInt *MEDCouplingUMesh::getCellsInBoundingBox(const double *bbox, double eps) const
2735 {
2736   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> elems=DataArrayInt::New(); elems->alloc(0,1);
2737   if(getMeshDimension()==-1)
2738     {
2739       elems->pushBackSilent(0);
2740       return elems.retn();
2741     }
2742   int dim=getSpaceDimension();
2743   INTERP_KERNEL::AutoPtr<double> elem_bb=new double[2*dim];
2744   const int* conn      = getNodalConnectivity()->getConstPointer();
2745   const int* conn_index= getNodalConnectivityIndex()->getConstPointer();
2746   const double* coords = getCoords()->getConstPointer();
2747   int nbOfCells=getNumberOfCells();
2748   for ( int ielem=0; ielem<nbOfCells;ielem++ )
2749     {
2750       for (int i=0; i<dim; i++)
2751         {
2752           elem_bb[i*2]=std::numeric_limits<double>::max();
2753           elem_bb[i*2+1]=-std::numeric_limits<double>::max();
2754         }
2755
2756       for (int inode=conn_index[ielem]+1; inode<conn_index[ielem+1]; inode++)//+1 due to offset of cell type.
2757         {
2758           int node= conn[inode];
2759           if(node>=0)//avoid polyhedron separator
2760             {
2761               for (int idim=0; idim<dim; idim++)
2762                 {
2763                   if ( coords[node*dim+idim] < elem_bb[idim*2] )
2764                     {
2765                       elem_bb[idim*2] = coords[node*dim+idim] ;
2766                     }
2767                   if ( coords[node*dim+idim] > elem_bb[idim*2+1] )
2768                     {
2769                       elem_bb[idim*2+1] = coords[node*dim+idim] ;
2770                     }
2771                 }
2772             }
2773         }
2774       if (intersectsBoundingBox(elem_bb, bbox, dim, eps))
2775         elems->pushBackSilent(ielem);
2776     }
2777   return elems.retn();
2778 }
2779
2780 /*!
2781  * Given a boundary box 'bbox' returns elements 'elems' contained in this 'bbox' or touching 'bbox' (within 'eps' distance).
2782  * Warning 'elems' is incremented during the call so if elems is not empty before call returned elements will be
2783  * added in 'elems' parameter.
2784  */
2785 DataArrayInt *MEDCouplingUMesh::getCellsInBoundingBox(const INTERP_KERNEL::DirectedBoundingBox& bbox, double eps)
2786 {
2787   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> elems=DataArrayInt::New(); elems->alloc(0,1);
2788   if(getMeshDimension()==-1)
2789     {
2790       elems->pushBackSilent(0);
2791       return elems.retn();
2792     }
2793   int dim=getSpaceDimension();
2794   INTERP_KERNEL::AutoPtr<double> elem_bb=new double[2*dim];
2795   const int* conn      = getNodalConnectivity()->getConstPointer();
2796   const int* conn_index= getNodalConnectivityIndex()->getConstPointer();
2797   const double* coords = getCoords()->getConstPointer();
2798   int nbOfCells=getNumberOfCells();
2799   for ( int ielem=0; ielem<nbOfCells;ielem++ )
2800     {
2801       for (int i=0; i<dim; i++)
2802         {
2803           elem_bb[i*2]=std::numeric_limits<double>::max();
2804           elem_bb[i*2+1]=-std::numeric_limits<double>::max();
2805         }
2806
2807       for (int inode=conn_index[ielem]+1; inode<conn_index[ielem+1]; inode++)//+1 due to offset of cell type.
2808         {
2809           int node= conn[inode];
2810           if(node>=0)//avoid polyhedron separator
2811             {
2812               for (int idim=0; idim<dim; idim++)
2813                 {
2814                   if ( coords[node*dim+idim] < elem_bb[idim*2] )
2815                     {
2816                       elem_bb[idim*2] = coords[node*dim+idim] ;
2817                     }
2818                   if ( coords[node*dim+idim] > elem_bb[idim*2+1] )
2819                     {
2820                       elem_bb[idim*2+1] = coords[node*dim+idim] ;
2821                     }
2822                 }
2823             }
2824         }
2825       if(intersectsBoundingBox(bbox, elem_bb, dim, eps))
2826         elems->pushBackSilent(ielem);
2827     }
2828   return elems.retn();
2829 }
2830
2831 /*!
2832  * Returns a type of a cell by its id.
2833  *  \param [in] cellId - the id of the cell of interest.
2834  *  \return INTERP_KERNEL::NormalizedCellType - enumeration item describing the cell type.
2835  *  \throw If \a cellId is invalid. Valid range is [0, \a this->getNumberOfCells() ).
2836  */
2837 INTERP_KERNEL::NormalizedCellType MEDCouplingUMesh::getTypeOfCell(int cellId) const
2838 {
2839   const int *ptI=_nodal_connec_index->getConstPointer();
2840   const int *pt=_nodal_connec->getConstPointer();
2841   if(cellId>=0 && cellId<(int)_nodal_connec_index->getNbOfElems()-1)
2842     return (INTERP_KERNEL::NormalizedCellType) pt[ptI[cellId]];
2843   else
2844     {
2845       std::ostringstream oss; oss << "MEDCouplingUMesh::getTypeOfCell : Requesting type of cell #" << cellId << " but it should be in [0," << _nodal_connec_index->getNbOfElems()-1 << ") !";
2846       throw INTERP_KERNEL::Exception(oss.str().c_str());
2847     }
2848 }
2849
2850 /*!
2851  * This method returns a newly allocated array containing cell ids (ascendingly sorted) whose geometric type are equal to type.
2852  * This method does not throw exception if geometric type \a type is not in \a this.
2853  * This method throws an INTERP_KERNEL::Exception if meshdimension of \b this is not equal to those of \b type.
2854  * The coordinates array is not considered here.
2855  *
2856  * \param [in] type the geometric type
2857  * \return cell ids in this having geometric type \a type.
2858  */
2859 DataArrayInt *MEDCouplingUMesh::giveCellsWithType(INTERP_KERNEL::NormalizedCellType type) const
2860 {
2861
2862   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New();
2863   ret->alloc(0,1);
2864   checkConnectivityFullyDefined();
2865   int nbCells=getNumberOfCells();
2866   int mdim=getMeshDimension();
2867   const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(type);
2868   if(mdim!=(int)cm.getDimension())
2869     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::giveCellsWithType : Mismatch between mesh dimension and dimension of the cell !");
2870   const int *ptI=_nodal_connec_index->getConstPointer();
2871   const int *pt=_nodal_connec->getConstPointer();
2872   for(int i=0;i<nbCells;i++)
2873     {
2874       if((INTERP_KERNEL::NormalizedCellType)pt[ptI[i]]==type)
2875         ret->pushBackSilent(i);
2876     }
2877   return ret.retn();
2878 }
2879
2880 /*!
2881  * Returns nb of cells having the geometric type \a type. No throw if no cells in \a this has the geometric type \a type.
2882  */
2883 int MEDCouplingUMesh::getNumberOfCellsWithType(INTERP_KERNEL::NormalizedCellType type) const
2884 {
2885   const int *ptI=_nodal_connec_index->getConstPointer();
2886   const int *pt=_nodal_connec->getConstPointer();
2887   int nbOfCells=getNumberOfCells();
2888   int ret=0;
2889   for(int i=0;i<nbOfCells;i++)
2890     if((INTERP_KERNEL::NormalizedCellType) pt[ptI[i]]==type)
2891       ret++;
2892   return ret;
2893 }
2894
2895 /*!
2896  * Returns the nodal connectivity of a given cell.
2897  * The separator of faces within polyhedron connectivity (-1) is not returned, thus
2898  * all returned node ids can be used in getCoordinatesOfNode().
2899  *  \param [in] cellId - an id of the cell of interest.
2900  *  \param [in,out] conn - a vector where the node ids are appended. It is not
2901  *         cleared before the appending.
2902  *  \throw If \a cellId is invalid. Valid range is [0, \a this->getNumberOfCells() ).
2903  */
2904 void MEDCouplingUMesh::getNodeIdsOfCell(int cellId, std::vector<int>& conn) const
2905 {
2906   const int *ptI=_nodal_connec_index->getConstPointer();
2907   const int *pt=_nodal_connec->getConstPointer();
2908   for(const int *w=pt+ptI[cellId]+1;w!=pt+ptI[cellId+1];w++)
2909     if(*w>=0)
2910       conn.push_back(*w);
2911 }
2912
2913 std::string MEDCouplingUMesh::simpleRepr() const
2914 {
2915   static const char msg0[]="No coordinates specified !";
2916   std::ostringstream ret;
2917   ret << "Unstructured mesh with name : \"" << getName() << "\"\n";
2918   ret << "Description of mesh : \"" << getDescription() << "\"\n";
2919   int tmpp1,tmpp2;
2920   double tt=getTime(tmpp1,tmpp2);
2921   ret << "Time attached to the mesh [unit] : " << tt << " [" << getTimeUnit() << "]\n";
2922   ret << "Iteration : " << tmpp1  << " Order : " << tmpp2 << "\n";
2923   if(_mesh_dim>=-1)
2924     { ret << "Mesh dimension : " << _mesh_dim << "\nSpace dimension : "; }
2925   else
2926     { ret << " Mesh dimension has not been set or is invalid !"; }
2927   if(_coords!=0)
2928     {
2929       const int spaceDim=getSpaceDimension();
2930       ret << spaceDim << "\nInfo attached on space dimension : ";
2931       for(int i=0;i<spaceDim;i++)
2932         ret << "\"" << _coords->getInfoOnComponent(i) << "\" ";
2933       ret << "\n";
2934     }
2935   else
2936     ret << msg0 << "\n";
2937   ret << "Number of nodes : ";
2938   if(_coords!=0)
2939     ret << getNumberOfNodes() << "\n";
2940   else
2941     ret << msg0 << "\n";
2942   ret << "Number of cells : ";
2943   if(_nodal_connec!=0 && _nodal_connec_index!=0)
2944     ret << getNumberOfCells() << "\n";
2945   else
2946     ret << "No connectivity specified !" << "\n";
2947   ret << "Cell types present : ";
2948   for(std::set<INTERP_KERNEL::NormalizedCellType>::const_iterator iter=_types.begin();iter!=_types.end();iter++)
2949     {
2950       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(*iter);
2951       ret << cm.getRepr() << " ";
2952     }
2953   ret << "\n";
2954   return ret.str();
2955 }
2956
2957 std::string MEDCouplingUMesh::advancedRepr() const
2958 {
2959   std::ostringstream ret;
2960   ret << simpleRepr();
2961   ret << "\nCoordinates array : \n___________________\n\n";
2962   if(_coords)
2963     _coords->reprWithoutNameStream(ret);
2964   else
2965     ret << "No array set !\n";
2966   ret << "\n\nConnectivity arrays : \n_____________________\n\n";
2967   reprConnectivityOfThisLL(ret);
2968   return ret.str();
2969 }
2970
2971 /*!
2972  * This method returns a C++ code that is a dump of \a this.
2973  * This method will throw if this is not fully defined.
2974  */
2975 std::string MEDCouplingUMesh::cppRepr() const
2976 {
2977   static const char coordsName[]="coords";
2978   static const char connName[]="conn";
2979   static const char connIName[]="connI";
2980   checkFullyDefined();
2981   std::ostringstream ret; ret << "// coordinates" << std::endl;
2982   _coords->reprCppStream(coordsName,ret); ret << std::endl << "// connectivity" << std::endl;
2983   _nodal_connec->reprCppStream(connName,ret); ret << std::endl;
2984   _nodal_connec_index->reprCppStream(connIName,ret); ret << std::endl;
2985   ret << "MEDCouplingUMesh *mesh=MEDCouplingUMesh::New(\"" << getName() << "\"," << getMeshDimension() << ");" << std::endl;
2986   ret << "mesh->setCoords(" << coordsName << ");" << std::endl;
2987   ret << "mesh->setConnectivity(" << connName << "," << connIName << ",true);" << std::endl;
2988   ret << coordsName << "->decrRef(); " << connName << "->decrRef(); " << connIName << "->decrRef();" << std::endl;
2989   return ret.str();
2990 }
2991
2992 std::string MEDCouplingUMesh::reprConnectivityOfThis() const
2993 {
2994   std::ostringstream ret;
2995   reprConnectivityOfThisLL(ret);
2996   return ret.str();
2997 }
2998
2999 /*!
3000  * This method builds a newly allocated instance (with the same name than \a this) that the caller has the responsability to deal with.
3001  * This method returns an instance with all arrays allocated (connectivity, connectivity index, coordinates)
3002  * but with length of these arrays set to 0. It allows to define an "empty" mesh (with nor cells nor nodes but compliant with
3003  * some algos).
3004  * 
3005  * This method expects that \a this has a mesh dimension set and higher or equal to 0. If not an exception will be thrown.
3006  * This method analyzes the 3 arrays of \a this. For each the following behaviour is done : if the array is null a newly one is created
3007  * with number of tuples set to 0, if not the array is taken as this in the returned instance.
3008  */
3009 MEDCouplingUMesh *MEDCouplingUMesh::buildSetInstanceFromThis(int spaceDim) const
3010 {
3011   int mdim=getMeshDimension();
3012   if(mdim<0)
3013     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSetInstanceFromThis : invalid mesh dimension ! Should be >= 0 !");
3014   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret=MEDCouplingUMesh::New(getName(),mdim);
3015   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp1,tmp2;
3016   bool needToCpyCT=true;
3017   if(!_nodal_connec)
3018     {
3019       tmp1=DataArrayInt::New(); tmp1->alloc(0,1);
3020       needToCpyCT=false;
3021     }
3022   else
3023     {
3024       tmp1=_nodal_connec;
3025       tmp1->incrRef();
3026     }
3027   if(!_nodal_connec_index)
3028     {
3029       tmp2=DataArrayInt::New(); tmp2->alloc(1,1); tmp2->setIJ(0,0,0);
3030       needToCpyCT=false;
3031     }
3032   else
3033     {
3034       tmp2=_nodal_connec_index;
3035       tmp2->incrRef();
3036     }
3037   ret->setConnectivity(tmp1,tmp2,false);
3038   if(needToCpyCT)
3039     ret->_types=_types;
3040   if(!_coords)
3041     {
3042       MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> coords=DataArrayDouble::New(); coords->alloc(0,spaceDim);
3043       ret->setCoords(coords);
3044     }
3045   else
3046     ret->setCoords(_coords);
3047   return ret.retn();
3048 }
3049
3050 void MEDCouplingUMesh::reprConnectivityOfThisLL(std::ostringstream& stream) const
3051 {
3052   if(_nodal_connec!=0 && _nodal_connec_index!=0)
3053     {
3054       int nbOfCells=getNumberOfCells();
3055       const int *c=_nodal_connec->getConstPointer();
3056       const int *ci=_nodal_connec_index->getConstPointer();
3057       for(int i=0;i<nbOfCells;i++)
3058         {
3059           const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)c[ci[i]]);
3060           stream << "Cell #" << i << " " << cm.getRepr() << " : ";
3061           std::copy(c+ci[i]+1,c+ci[i+1],std::ostream_iterator<int>(stream," "));
3062           stream << "\n";
3063         }
3064     }
3065   else
3066     stream << "Connectivity not defined !\n";
3067 }
3068
3069 int MEDCouplingUMesh::getNumberOfNodesInCell(int cellId) const
3070 {
3071   const int *ptI=_nodal_connec_index->getConstPointer();
3072   const int *pt=_nodal_connec->getConstPointer();
3073   if(pt[ptI[cellId]]!=INTERP_KERNEL::NORM_POLYHED)
3074     return ptI[cellId+1]-ptI[cellId]-1;
3075   else
3076     return (int)std::count_if(pt+ptI[cellId]+1,pt+ptI[cellId+1],std::bind2nd(std::not_equal_to<int>(),-1));
3077 }
3078
3079 /*!
3080  * Returns types of cells of the specified part of \a this mesh.
3081  * This method avoids computing sub-mesh explicitely to get its types.
3082  *  \param [in] begin - an array of cell ids of interest.
3083  *  \param [in] end - the end of \a begin, i.e. a pointer to its (last+1)-th element.
3084  *  \return std::set<INTERP_KERNEL::NormalizedCellType> - a set of enumeration items
3085  *         describing the cell types. 
3086  *  \throw If the coordinates array is not set.
3087  *  \throw If the nodal connectivity of cells is not defined.
3088  *  \sa getAllGeoTypes()
3089  */
3090 std::set<INTERP_KERNEL::NormalizedCellType> MEDCouplingUMesh::getTypesOfPart(const int *begin, const int *end) const
3091 {
3092   checkFullyDefined();
3093   std::set<INTERP_KERNEL::NormalizedCellType> ret;
3094   const int *conn=_nodal_connec->getConstPointer();
3095   const int *connIndex=_nodal_connec_index->getConstPointer();
3096   for(const int *w=begin;w!=end;w++)
3097     ret.insert((INTERP_KERNEL::NormalizedCellType)conn[connIndex[*w]]);
3098   return ret;
3099 }
3100
3101 /*!
3102  * Defines the nodal connectivity using given connectivity arrays. Optionally updates
3103  * a set of types of cells constituting \a this mesh. 
3104  * This method is for advanced users having prepared their connectivity before. For
3105  * more info on using this method see \ref MEDCouplingUMeshAdvBuild.
3106  *  \param [in] conn - the nodal connectivity array. 
3107  *  \param [in] connIndex - the nodal connectivity index array.
3108  *  \param [in] isComputingTypes - if \c true, the set of types constituting \a this
3109  *         mesh is updated.
3110  */
3111 void MEDCouplingUMesh::setConnectivity(DataArrayInt *conn, DataArrayInt *connIndex, bool isComputingTypes)
3112 {
3113   DataArrayInt::SetArrayIn(conn,_nodal_connec);
3114   DataArrayInt::SetArrayIn(connIndex,_nodal_connec_index);
3115   if(isComputingTypes)
3116     computeTypes();
3117   declareAsNew();
3118 }
3119
3120 /*!
3121  * Copy constructor. If 'deepCpy' is false \a this is a shallow copy of other.
3122  * If 'deeCpy' is true all arrays (coordinates and connectivities) are deeply copied.
3123  */
3124 MEDCouplingUMesh::MEDCouplingUMesh(const MEDCouplingUMesh& other, bool deepCopy):MEDCouplingPointSet(other,deepCopy),_mesh_dim(other._mesh_dim),
3125     _nodal_connec(0),_nodal_connec_index(0),
3126     _types(other._types)
3127 {
3128   if(other._nodal_connec)
3129     _nodal_connec=other._nodal_connec->performCpy(deepCopy);
3130   if(other._nodal_connec_index)
3131     _nodal_connec_index=other._nodal_connec_index->performCpy(deepCopy);
3132 }
3133
3134 MEDCouplingUMesh::~MEDCouplingUMesh()
3135 {
3136   if(_nodal_connec)
3137     _nodal_connec->decrRef();
3138   if(_nodal_connec_index)
3139     _nodal_connec_index->decrRef();
3140 }
3141
3142 /*!
3143  * Recomputes a set of cell types of \a this mesh. For more info see
3144  * \ref MEDCouplingUMeshNodalConnectivity.
3145  */
3146 void MEDCouplingUMesh::computeTypes()
3147 {
3148   if(_nodal_connec && _nodal_connec_index)
3149     {
3150       _types.clear();
3151       const int *conn=_nodal_connec->getConstPointer();
3152       const int *connIndex=_nodal_connec_index->getConstPointer();
3153       int nbOfElem=_nodal_connec_index->getNbOfElems()-1;
3154       if (nbOfElem > 0)
3155         for(const int *pt=connIndex;pt !=connIndex+nbOfElem;pt++)
3156           _types.insert((INTERP_KERNEL::NormalizedCellType)conn[*pt]);
3157     }
3158 }
3159
3160 /*!
3161  * This method checks that all arrays are set. If yes nothing done if no an exception is thrown.
3162  */
3163 void MEDCouplingUMesh::checkFullyDefined() const
3164 {
3165   if(!_nodal_connec_index || !_nodal_connec || !_coords)
3166     throw INTERP_KERNEL::Exception("Reverse nodal connectivity computation requires full connectivity and coordinates set in unstructured mesh.");
3167 }
3168
3169 /*!
3170  * This method checks that all connectivity arrays are set. If yes nothing done if no an exception is thrown.
3171  */
3172 void MEDCouplingUMesh::checkConnectivityFullyDefined() const
3173 {
3174   if(!_nodal_connec_index || !_nodal_connec)
3175     throw INTERP_KERNEL::Exception("Reverse nodal connectivity computation requires full connectivity set in unstructured mesh.");
3176 }
3177
3178 /*!
3179  * Returns a number of cells constituting \a this mesh. 
3180  *  \return int - the number of cells in \a this mesh.
3181  *  \throw If the nodal connectivity of cells is not defined.
3182  */
3183 int MEDCouplingUMesh::getNumberOfCells() const
3184
3185   if(_nodal_connec_index)
3186     return _nodal_connec_index->getNumberOfTuples()-1;
3187   else
3188     if(_mesh_dim==-1)
3189       return 1;
3190     else
3191       throw INTERP_KERNEL::Exception("Unable to get number of cells because no connectivity specified !");
3192 }
3193
3194 /*!
3195  * Returns a dimension of \a this mesh, i.e. a dimension of cells constituting \a this
3196  * mesh. For more info see \ref MEDCouplingMeshesPage.
3197  *  \return int - the dimension of \a this mesh.
3198  *  \throw If the mesh dimension is not defined using setMeshDimension().
3199  */
3200 int MEDCouplingUMesh::getMeshDimension() const
3201 {
3202   if(_mesh_dim<-1)
3203     throw INTERP_KERNEL::Exception("No mesh dimension specified !");
3204   return _mesh_dim;
3205 }
3206
3207 /*!
3208  * Returns a length of the nodal connectivity array.
3209  * This method is for test reason. Normally the integer returned is not useable by
3210  * user.  For more info see \ref MEDCouplingUMeshNodalConnectivity.
3211  *  \return int - the length of the nodal connectivity array.
3212  */
3213 int MEDCouplingUMesh::getMeshLength() const
3214 {
3215   return _nodal_connec->getNbOfElems();
3216 }
3217
3218 /*!
3219  * First step of serialization process. Used by ParaMEDMEM and MEDCouplingCorba to transfert data between process.
3220  */
3221 void MEDCouplingUMesh::getTinySerializationInformation(std::vector<double>& tinyInfoD, std::vector<int>& tinyInfo, std::vector<std::string>& littleStrings) const
3222 {
3223   MEDCouplingPointSet::getTinySerializationInformation(tinyInfoD,tinyInfo,littleStrings);
3224   tinyInfo.push_back(getMeshDimension());
3225   tinyInfo.push_back(getNumberOfCells());
3226   if(_nodal_connec)
3227     tinyInfo.push_back(getMeshLength());
3228   else
3229     tinyInfo.push_back(-1);
3230 }
3231
3232 /*!
3233  * First step of unserialization process.
3234  */
3235 bool MEDCouplingUMesh::isEmptyMesh(const std::vector<int>& tinyInfo) const
3236 {
3237   return tinyInfo[6]<=0;
3238 }
3239
3240 /*!
3241  * Second step of serialization process.
3242  * \param tinyInfo must be equal to the result given by getTinySerializationInformation method.
3243  */
3244 void MEDCouplingUMesh::resizeForUnserialization(const std::vector<int>& tinyInfo, DataArrayInt *a1, DataArrayDouble *a2, std::vector<std::string>& littleStrings) const
3245 {
3246   MEDCouplingPointSet::resizeForUnserialization(tinyInfo,a1,a2,littleStrings);
3247   if(tinyInfo[5]!=-1)
3248     a1->alloc(tinyInfo[7]+tinyInfo[6]+1,1);
3249 }
3250
3251 /*!
3252  * Third and final step of serialization process.
3253  */
3254 void MEDCouplingUMesh::serialize(DataArrayInt *&a1, DataArrayDouble *&a2) const
3255 {
3256   MEDCouplingPointSet::serialize(a1,a2);
3257   if(getMeshDimension()>-1)
3258     {
3259       a1=DataArrayInt::New();
3260       a1->alloc(getMeshLength()+getNumberOfCells()+1,1);
3261       int *ptA1=a1->getPointer();
3262       const int *conn=getNodalConnectivity()->getConstPointer();
3263       const int *index=getNodalConnectivityIndex()->getConstPointer();
3264       ptA1=std::copy(index,index+getNumberOfCells()+1,ptA1);
3265       std::copy(conn,conn+getMeshLength(),ptA1);
3266     }
3267   else
3268     a1=0;
3269 }
3270
3271 /*!
3272  * Second and final unserialization process.
3273  * \param tinyInfo must be equal to the result given by getTinySerializationInformation method.
3274  */
3275 void MEDCouplingUMesh::unserialization(const std::vector<double>& tinyInfoD, const std::vector<int>& tinyInfo, const DataArrayInt *a1, DataArrayDouble *a2, const std::vector<std::string>& littleStrings)
3276 {
3277   MEDCouplingPointSet::unserialization(tinyInfoD,tinyInfo,a1,a2,littleStrings);
3278   setMeshDimension(tinyInfo[5]);
3279   if(tinyInfo[7]!=-1)
3280     {
3281       // Connectivity
3282       const int *recvBuffer=a1->getConstPointer();
3283       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> myConnecIndex=DataArrayInt::New();
3284       myConnecIndex->alloc(tinyInfo[6]+1,1);
3285       std::copy(recvBuffer,recvBuffer+tinyInfo[6]+1,myConnecIndex->getPointer());
3286       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> myConnec=DataArrayInt::New();
3287       myConnec->alloc(tinyInfo[7],1);
3288       std::copy(recvBuffer+tinyInfo[6]+1,recvBuffer+tinyInfo[6]+1+tinyInfo[7],myConnec->getPointer());
3289       setConnectivity(myConnec, myConnecIndex);
3290     }
3291 }
3292
3293 /*!
3294  * This is the low algorithm of MEDCouplingUMesh::buildPartOfMySelf2.
3295  * CellIds are given using range specified by a start an end and step.
3296  */
3297 MEDCouplingPointSet *MEDCouplingUMesh::buildPartOfMySelfKeepCoords2(int start, int end, int step) const
3298 {
3299   checkFullyDefined();
3300   int ncell=getNumberOfCells();
3301   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret=MEDCouplingUMesh::New();
3302   ret->_mesh_dim=_mesh_dim;
3303   ret->setCoords(_coords);
3304   int newNbOfCells=DataArray::GetNumberOfItemGivenBESRelative(start,end,step,"MEDCouplingUMesh::buildPartOfMySelfKeepCoords2 : ");
3305   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConnI=DataArrayInt::New(); newConnI->alloc(newNbOfCells+1,1);
3306   int *newConnIPtr=newConnI->getPointer(); *newConnIPtr=0;
3307   int work=start;
3308   const int *conn=_nodal_connec->getConstPointer();
3309   const int *connIndex=_nodal_connec_index->getConstPointer();
3310   for(int i=0;i<newNbOfCells;i++,newConnIPtr++,work+=step)
3311     {
3312       if(work>=0 && work<ncell)
3313         {
3314           newConnIPtr[1]=newConnIPtr[0]+connIndex[work+1]-connIndex[work];
3315         }
3316       else
3317         {
3318           std::ostringstream oss; oss << "MEDCouplingUMesh::buildPartOfMySelfKeepCoords2 : On pos #" << i << " input cell id =" << work << " should be in [0," << ncell << ") !";
3319           throw INTERP_KERNEL::Exception(oss.str().c_str());
3320         }
3321     }
3322   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConn=DataArrayInt::New(); newConn->alloc(newConnIPtr[0],1);
3323   int *newConnPtr=newConn->getPointer();
3324   std::set<INTERP_KERNEL::NormalizedCellType> types;
3325   work=start;
3326   for(int i=0;i<newNbOfCells;i++,newConnIPtr++,work+=step)
3327     {
3328       types.insert((INTERP_KERNEL::NormalizedCellType)conn[connIndex[work]]);
3329       newConnPtr=std::copy(conn+connIndex[work],conn+connIndex[work+1],newConnPtr);
3330     }
3331   ret->setConnectivity(newConn,newConnI,false);
3332   ret->_types=types;
3333   ret->copyTinyInfoFrom(this);
3334   return ret.retn();
3335 }
3336
3337 /*!
3338  * This is the low algorithm of MEDCouplingUMesh::buildPartOfMySelf.
3339  * Keeps from \a this only cells which constituing point id are in the ids specified by [ \a begin,\a end ).
3340  * The return newly allocated mesh will share the same coordinates as \a this.
3341  */
3342 MEDCouplingPointSet *MEDCouplingUMesh::buildPartOfMySelfKeepCoords(const int *begin, const int *end) const
3343 {
3344   checkConnectivityFullyDefined();
3345   int ncell=getNumberOfCells();
3346   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret=MEDCouplingUMesh::New();
3347   ret->_mesh_dim=_mesh_dim;
3348   ret->setCoords(_coords);
3349   std::size_t nbOfElemsRet=std::distance(begin,end);
3350   int *connIndexRet=(int *)malloc((nbOfElemsRet+1)*sizeof(int));
3351   connIndexRet[0]=0;
3352   const int *conn=_nodal_connec->getConstPointer();
3353   const int *connIndex=_nodal_connec_index->getConstPointer();
3354   int newNbring=0;
3355   for(const int *work=begin;work!=end;work++,newNbring++)
3356     {
3357       if(*work>=0 && *work<ncell)
3358         connIndexRet[newNbring+1]=connIndexRet[newNbring]+connIndex[*work+1]-connIndex[*work];
3359       else
3360         {
3361           free(connIndexRet);
3362           std::ostringstream oss; oss << "MEDCouplingUMesh::buildPartOfMySelfKeepCoords : On pos #" << std::distance(begin,work) << " input cell id =" << *work << " should be in [0," << ncell << ") !";
3363           throw INTERP_KERNEL::Exception(oss.str().c_str());
3364         }
3365     }
3366   int *connRet=(int *)malloc(connIndexRet[nbOfElemsRet]*sizeof(int));
3367   int *connRetWork=connRet;
3368   std::set<INTERP_KERNEL::NormalizedCellType> types;
3369   for(const int *work=begin;work!=end;work++)
3370     {
3371       types.insert((INTERP_KERNEL::NormalizedCellType)conn[connIndex[*work]]);
3372       connRetWork=std::copy(conn+connIndex[*work],conn+connIndex[*work+1],connRetWork);
3373     }
3374   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> connRetArr=DataArrayInt::New();
3375   connRetArr->useArray(connRet,true,C_DEALLOC,connIndexRet[nbOfElemsRet],1);
3376   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> connIndexRetArr=DataArrayInt::New();
3377   connIndexRetArr->useArray(connIndexRet,true,C_DEALLOC,(int)nbOfElemsRet+1,1);
3378   ret->setConnectivity(connRetArr,connIndexRetArr,false);
3379   ret->_types=types;
3380   ret->copyTinyInfoFrom(this);
3381   return ret.retn();
3382 }
3383
3384 /*!
3385  * Returns a new MEDCouplingFieldDouble containing volumes of cells constituting \a this
3386  * mesh.<br>
3387  * For 1D cells, the returned field contains lengths.<br>
3388  * For 2D cells, the returned field contains areas.<br>
3389  * For 3D cells, the returned field contains volumes.
3390  *  \param [in] isAbs - if \c true, the computed cell volume does not reflect cell
3391  *         orientation, i.e. the volume is always positive.
3392  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on cells
3393  *         and one time . The caller is to delete this field using decrRef() as it is no
3394  *         more needed.
3395  */
3396 MEDCouplingFieldDouble *MEDCouplingUMesh::getMeasureField(bool isAbs) const
3397 {
3398   std::string name="MeasureOfMesh_";
3399   name+=getName();
3400   int nbelem=getNumberOfCells();
3401   MEDCouplingAutoRefCountObjectPtr<MEDCouplingFieldDouble> field=MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME);
3402   field->setName(name);
3403   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> array=DataArrayDouble::New();
3404   array->alloc(nbelem,1);
3405   double *area_vol=array->getPointer();
3406   field->setArray(array) ; array=0;
3407   field->setMesh(const_cast<MEDCouplingUMesh *>(this));
3408   field->synchronizeTimeWithMesh();
3409   if(getMeshDimension()!=-1)
3410     {
3411       int ipt;
3412       INTERP_KERNEL::NormalizedCellType type;
3413       int dim_space=getSpaceDimension();
3414       const double *coords=getCoords()->getConstPointer();
3415       const int *connec=getNodalConnectivity()->getConstPointer();
3416       const int *connec_index=getNodalConnectivityIndex()->getConstPointer();
3417       for(int iel=0;iel<nbelem;iel++)
3418         {
3419           ipt=connec_index[iel];
3420           type=(INTERP_KERNEL::NormalizedCellType)connec[ipt];
3421           area_vol[iel]=INTERP_KERNEL::computeVolSurfOfCell2<int,INTERP_KERNEL::ALL_C_MODE>(type,connec+ipt+1,connec_index[iel+1]-ipt-1,coords,dim_space);
3422         }
3423       if(isAbs)
3424         std::transform(area_vol,area_vol+nbelem,area_vol,std::ptr_fun<double,double>(fabs));
3425     }
3426   else
3427     {
3428       area_vol[0]=std::numeric_limits<double>::max();
3429     }
3430   return field.retn();
3431 }
3432
3433 /*!
3434  * Returns a new DataArrayDouble containing volumes of specified cells of \a this
3435  * mesh.<br>
3436  * For 1D cells, the returned array contains lengths.<br>
3437  * For 2D cells, the returned array contains areas.<br>
3438  * For 3D cells, the returned array contains volumes.
3439  * This method avoids building explicitly a part of \a this mesh to perform the work.
3440  *  \param [in] isAbs - if \c true, the computed cell volume does not reflect cell
3441  *         orientation, i.e. the volume is always positive.
3442  *  \param [in] begin - an array of cell ids of interest.
3443  *  \param [in] end - the end of \a begin, i.e. a pointer to its (last+1)-th element.
3444  *  \return DataArrayDouble * - a new instance of DataArrayDouble. The caller is to
3445  *          delete this array using decrRef() as it is no more needed.
3446  * 
3447  *  \if ENABLE_EXAMPLES
3448  *  \ref cpp_mcumesh_getPartMeasureField "Here is a C++ example".<br>
3449  *  \ref  py_mcumesh_getPartMeasureField "Here is a Python example".
3450  *  \endif
3451  *  \sa getMeasureField()
3452  */
3453 DataArrayDouble *MEDCouplingUMesh::getPartMeasureField(bool isAbs, const int *begin, const int *end) const
3454 {
3455   std::string name="PartMeasureOfMesh_";
3456   name+=getName();
3457   int nbelem=(int)std::distance(begin,end);
3458   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> array=DataArrayDouble::New();
3459   array->setName(name);
3460   array->alloc(nbelem,1);
3461   double *area_vol=array->getPointer();
3462   if(getMeshDimension()!=-1)
3463     {
3464       int ipt;
3465       INTERP_KERNEL::NormalizedCellType type;
3466       int dim_space=getSpaceDimension();
3467       const double *coords=getCoords()->getConstPointer();
3468       const int *connec=getNodalConnectivity()->getConstPointer();
3469       const int *connec_index=getNodalConnectivityIndex()->getConstPointer();
3470       for(const int *iel=begin;iel!=end;iel++)
3471         {
3472           ipt=connec_index[*iel];
3473           type=(INTERP_KERNEL::NormalizedCellType)connec[ipt];
3474           *area_vol++=INTERP_KERNEL::computeVolSurfOfCell2<int,INTERP_KERNEL::ALL_C_MODE>(type,connec+ipt+1,connec_index[*iel+1]-ipt-1,coords,dim_space);
3475         }
3476       if(isAbs)
3477         std::transform(array->getPointer(),area_vol,array->getPointer(),std::ptr_fun<double,double>(fabs));
3478     }
3479   else
3480     {
3481       area_vol[0]=std::numeric_limits<double>::max();
3482     }
3483   return array.retn();
3484 }
3485
3486 /*!
3487  * Returns a new MEDCouplingFieldDouble containing volumes of cells of a dual mesh of
3488  * \a this one. The returned field contains the dual cell volume for each corresponding
3489  * node in \a this mesh. In other words, the field returns the getMeasureField() of
3490  *  the dual mesh in P1 sens of \a this.<br>
3491  * For 1D cells, the returned field contains lengths.<br>
3492  * For 2D cells, the returned field contains areas.<br>
3493  * For 3D cells, the returned field contains volumes.
3494  * This method is useful to check "P1*" conservative interpolators.
3495  *  \param [in] isAbs - if \c true, the computed cell volume does not reflect cell
3496  *         orientation, i.e. the volume is always positive.
3497  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
3498  *          nodes and one time. The caller is to delete this array using decrRef() as
3499  *          it is no more needed.
3500  */
3501 MEDCouplingFieldDouble *MEDCouplingUMesh::getMeasureFieldOnNode(bool isAbs) const
3502 {
3503   MEDCouplingAutoRefCountObjectPtr<MEDCouplingFieldDouble> tmp=getMeasureField(isAbs);
3504   std::string name="MeasureOnNodeOfMesh_";
3505   name+=getName();
3506   int nbNodes=getNumberOfNodes();
3507   MEDCouplingAutoRefCountObjectPtr<MEDCouplingFieldDouble> ret=MEDCouplingFieldDouble::New(ON_NODES);
3508   double cst=1./((double)getMeshDimension()+1.);
3509   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> array=DataArrayDouble::New();
3510   array->alloc(nbNodes,1);
3511   double *valsToFill=array->getPointer();
3512   std::fill(valsToFill,valsToFill+nbNodes,0.);
3513   const double *values=tmp->getArray()->getConstPointer();
3514   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> da=DataArrayInt::New();
3515   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> daInd=DataArrayInt::New();
3516   getReverseNodalConnectivity(da,daInd);
3517   const int *daPtr=da->getConstPointer();
3518   const int *daIPtr=daInd->getConstPointer();
3519   for(int i=0;i<nbNodes;i++)
3520     for(const int *cell=daPtr+daIPtr[i];cell!=daPtr+daIPtr[i+1];cell++)
3521       valsToFill[i]+=cst*values[*cell];
3522   ret->setMesh(this);
3523   ret->setArray(array);
3524   return ret.retn();
3525 }
3526
3527 /*!
3528  * Returns a new MEDCouplingFieldDouble holding normal vectors to cells of \a this
3529  * mesh. The returned normal vectors to each cell have a norm2 equal to 1.
3530  * The computed vectors have <em> this->getMeshDimension()+1 </em> components
3531  * and are normalized.
3532  * <br> \a this can be either 
3533  * - a  2D mesh in 2D or 3D space or 
3534  * - an 1D mesh in 2D space.
3535  * 
3536  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
3537  *          cells and one time. The caller is to delete this field using decrRef() as
3538  *          it is no more needed.
3539  *  \throw If the nodal connectivity of cells is not defined.
3540  *  \throw If the coordinates array is not set.
3541  *  \throw If the mesh dimension is not set.
3542  *  \throw If the mesh and space dimension is not as specified above.
3543  */
3544 MEDCouplingFieldDouble *MEDCouplingUMesh::buildOrthogonalField() const
3545 {
3546   if((getMeshDimension()!=2) && (getMeshDimension()!=1 || getSpaceDimension()!=2))
3547     throw INTERP_KERNEL::Exception("Expected a umesh with ( meshDim == 2 spaceDim == 2 or 3 ) or ( meshDim == 1 spaceDim == 2 ) !");
3548   MEDCouplingAutoRefCountObjectPtr<MEDCouplingFieldDouble> ret=MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME);
3549   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> array=DataArrayDouble::New();
3550   int nbOfCells=getNumberOfCells();
3551   int nbComp=getMeshDimension()+1;
3552   array->alloc(nbOfCells,nbComp);
3553   double *vals=array->getPointer();
3554   const int *connI=_nodal_connec_index->getConstPointer();
3555   const int *conn=_nodal_connec->getConstPointer();
3556   const double *coords=_coords->getConstPointer();
3557   if(getMeshDimension()==2)
3558     {
3559       if(getSpaceDimension()==3)
3560         {
3561           MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> loc=getBarycenterAndOwner();
3562           const double *locPtr=loc->getConstPointer();
3563           for(int i=0;i<nbOfCells;i++,vals+=3)
3564             {
3565               int offset=connI[i];
3566               INTERP_KERNEL::crossprod<3>(locPtr+3*i,coords+3*conn[offset+1],coords+3*conn[offset+2],vals);
3567               double n=INTERP_KERNEL::norm<3>(vals);
3568               std::transform(vals,vals+3,vals,std::bind2nd(std::multiplies<double>(),1./n));
3569             }
3570         }
3571       else
3572         {
3573           MEDCouplingAutoRefCountObjectPtr<MEDCouplingFieldDouble> isAbs=getMeasureField(false);
3574           const double *isAbsPtr=isAbs->getArray()->begin();
3575           for(int i=0;i<nbOfCells;i++,isAbsPtr++)
3576             { vals[3*i]=0.; vals[3*i+1]=0.; vals[3*i+2]=*isAbsPtr>0.?1.:-1.; }
3577         }
3578     }
3579   else//meshdimension==1
3580     {
3581       double tmp[2];
3582       for(int i=0;i<nbOfCells;i++)
3583         {
3584           int offset=connI[i];
3585           std::transform(coords+2*conn[offset+2],coords+2*conn[offset+2]+2,coords+2*conn[offset+1],tmp,std::minus<double>());
3586           double n=INTERP_KERNEL::norm<2>(tmp);
3587           std::transform(tmp,tmp+2,tmp,std::bind2nd(std::multiplies<double>(),1./n));
3588           *vals++=-tmp[1];
3589           *vals++=tmp[0];
3590         }
3591     }
3592   ret->setArray(array);
3593   ret->setMesh(this);
3594   ret->synchronizeTimeWithSupport();
3595   return ret.retn();
3596 }
3597
3598 /*!
3599  * Returns a new MEDCouplingFieldDouble holding normal vectors to specified cells of
3600  * \a this mesh. The computed vectors have <em> this->getMeshDimension()+1 </em> components
3601  * and are normalized.
3602  * <br> \a this can be either 
3603  * - a  2D mesh in 2D or 3D space or 
3604  * - an 1D mesh in 2D space.
3605  * 
3606  * This method avoids building explicitly a part of \a this mesh to perform the work.
3607  *  \param [in] begin - an array of cell ids of interest.
3608  *  \param [in] end - the end of \a begin, i.e. a pointer to its (last+1)-th element.
3609  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
3610  *          cells and one time. The caller is to delete this field using decrRef() as
3611  *          it is no more needed.
3612  *  \throw If the nodal connectivity of cells is not defined.
3613  *  \throw If the coordinates array is not set.
3614  *  \throw If the mesh dimension is not set.
3615  *  \throw If the mesh and space dimension is not as specified above.
3616  *  \sa buildOrthogonalField()
3617  *
3618  *  \if ENABLE_EXAMPLES
3619  *  \ref cpp_mcumesh_buildPartOrthogonalField "Here is a C++ example".<br>
3620  *  \ref  py_mcumesh_buildPartOrthogonalField "Here is a Python example".
3621  *  \endif
3622  */
3623 MEDCouplingFieldDouble *MEDCouplingUMesh::buildPartOrthogonalField(const int *begin, const int *end) const
3624 {
3625   if((getMeshDimension()!=2) && (getMeshDimension()!=1 || getSpaceDimension()!=2))
3626     throw INTERP_KERNEL::Exception("Expected a umesh with ( meshDim == 2 spaceDim == 2 or 3 ) or ( meshDim == 1 spaceDim == 2 ) !");
3627   MEDCouplingAutoRefCountObjectPtr<MEDCouplingFieldDouble> ret=MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME);
3628   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> array=DataArrayDouble::New();
3629   std::size_t nbelems=std::distance(begin,end);
3630   int nbComp=getMeshDimension()+1;
3631   array->alloc((int)nbelems,nbComp);
3632   double *vals=array->getPointer();
3633   const int *connI=_nodal_connec_index->getConstPointer();
3634   const int *conn=_nodal_connec->getConstPointer();
3635   const double *coords=_coords->getConstPointer();
3636   if(getMeshDimension()==2)
3637     {
3638       if(getSpaceDimension()==3)
3639         {
3640           MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> loc=getPartBarycenterAndOwner(begin,end);
3641           const double *locPtr=loc->getConstPointer();
3642           for(const int *i=begin;i!=end;i++,vals+=3,locPtr+=3)
3643             {
3644               int offset=connI[*i];
3645               INTERP_KERNEL::crossprod<3>(locPtr,coords+3*conn[offset+1],coords+3*conn[offset+2],vals);
3646               double n=INTERP_KERNEL::norm<3>(vals);
3647               std::transform(vals,vals+3,vals,std::bind2nd(std::multiplies<double>(),1./n));
3648             }
3649         }
3650       else
3651         {
3652           for(std::size_t i=0;i<nbelems;i++)
3653             { vals[3*i]=0.; vals[3*i+1]=0.; vals[3*i+2]=1.; }
3654         }
3655     }
3656   else//meshdimension==1
3657     {
3658       double tmp[2];
3659       for(const int *i=begin;i!=end;i++)
3660         {
3661           int offset=connI[*i];
3662           std::transform(coords+2*conn[offset+2],coords+2*conn[offset+2]+2,coords+2*conn[offset+1],tmp,std::minus<double>());
3663           double n=INTERP_KERNEL::norm<2>(tmp);
3664           std::transform(tmp,tmp+2,tmp,std::bind2nd(std::multiplies<double>(),1./n));
3665           *vals++=-tmp[1];
3666           *vals++=tmp[0];
3667         }
3668     }
3669   ret->setArray(array);
3670   ret->setMesh(this);
3671   ret->synchronizeTimeWithSupport();
3672   return ret.retn();
3673 }
3674
3675 /*!
3676  * Returns a new MEDCouplingFieldDouble holding a direction vector for each SEG2 in \a
3677  * this 1D mesh. The computed vectors have <em> this->getSpaceDimension() </em> components
3678  * and are \b not normalized.
3679  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
3680  *          cells and one time. The caller is to delete this field using decrRef() as
3681  *          it is no more needed.
3682  *  \throw If the nodal connectivity of cells is not defined.
3683  *  \throw If the coordinates array is not set.
3684  *  \throw If \a this->getMeshDimension() != 1.
3685  *  \throw If \a this mesh includes cells of type other than SEG2.
3686  */
3687 MEDCouplingFieldDouble *MEDCouplingUMesh::buildDirectionVectorField() const
3688 {
3689   if(getMeshDimension()!=1)
3690     throw INTERP_KERNEL::Exception("Expected a umesh with meshDim == 1 for buildDirectionVectorField !");
3691   if(_types.size()!=1 || *(_types.begin())!=INTERP_KERNEL::NORM_SEG2)
3692     throw INTERP_KERNEL::Exception("Expected a umesh with only NORM_SEG2 type of elements for buildDirectionVectorField !");
3693   MEDCouplingAutoRefCountObjectPtr<MEDCouplingFieldDouble> ret=MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME);
3694   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> array=DataArrayDouble::New();
3695   int nbOfCells=getNumberOfCells();
3696   int spaceDim=getSpaceDimension();
3697   array->alloc(nbOfCells,spaceDim);
3698   double *pt=array->getPointer();
3699   const double *coo=getCoords()->getConstPointer();
3700   std::vector<int> conn;
3701   conn.reserve(2);
3702   for(int i=0;i<nbOfCells;i++)
3703     {
3704       conn.resize(0);
3705       getNodeIdsOfCell(i,conn);
3706       pt=std::transform(coo+conn[1]*spaceDim,coo+(conn[1]+1)*spaceDim,coo+conn[0]*spaceDim,pt,std::minus<double>());
3707     }
3708   ret->setArray(array);
3709   ret->setMesh(this);
3710   ret->synchronizeTimeWithSupport();
3711   return ret.retn();
3712 }
3713
3714 /*!
3715  * Creates a 2D mesh by cutting \a this 3D mesh with a plane. In addition to the mesh,
3716  * returns a new DataArrayInt, of length equal to the number of 2D cells in the result
3717  * mesh, holding, for each cell in the result mesh, an id of a 3D cell it comes
3718  * from. If a result face is shared by two 3D cells, then the face in included twice in
3719  * the result mesh.
3720  *  \param [in] origin - 3 components of a point defining location of the plane.
3721  *  \param [in] vec - 3 components of a vector normal to the plane. Vector magnitude
3722  *         must be greater than 1e-6.
3723  *  \param [in] eps - half-thickness of the plane.
3724  *  \param [out] cellIds - a new instance of DataArrayInt holding ids of 3D cells
3725  *         producing correspondent 2D cells. The caller is to delete this array
3726  *         using decrRef() as it is no more needed.
3727  *  \return MEDCouplingUMesh * - a new instance of MEDCouplingUMesh. This mesh does
3728  *         not share the node coordinates array with \a this mesh. The caller is to
3729  *         delete this mesh using decrRef() as it is no more needed.  
3730  *  \throw If the coordinates array is not set.
3731  *  \throw If the nodal connectivity of cells is not defined.
3732  *  \throw If \a this->getMeshDimension() != 3 or \a this->getSpaceDimension() != 3.
3733  *  \throw If magnitude of \a vec is less than 1e-6.
3734  *  \throw If the plane does not intersect any 3D cell of \a this mesh.
3735  *  \throw If \a this includes quadratic cells.
3736  */
3737 MEDCouplingUMesh *MEDCouplingUMesh::buildSlice3D(const double *origin, const double *vec, double eps, DataArrayInt *&cellIds) const
3738 {
3739   checkFullyDefined();
3740   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
3741     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSlice3D works on umeshes with meshdim equal to 3 and spaceDim equal to 3 too!");
3742   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> candidates=getCellIdsCrossingPlane(origin,vec,eps);
3743   if(candidates->empty())
3744     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSlice3D : No 3D cells in this intercepts the specified plane considering bounding boxes !");
3745   std::vector<int> nodes;
3746   DataArrayInt *cellIds1D=0;
3747   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> subMesh=static_cast<MEDCouplingUMesh*>(buildPartOfMySelf(candidates->begin(),candidates->end(),false));
3748   subMesh->findNodesOnPlane(origin,vec,eps,nodes);
3749   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> desc1=DataArrayInt::New(),desc2=DataArrayInt::New();
3750   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> descIndx1=DataArrayInt::New(),descIndx2=DataArrayInt::New();
3751   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revDesc1=DataArrayInt::New(),revDesc2=DataArrayInt::New();
3752   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revDescIndx1=DataArrayInt::New(),revDescIndx2=DataArrayInt::New();
3753   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> mDesc2=subMesh->buildDescendingConnectivity(desc2,descIndx2,revDesc2,revDescIndx2);//meshDim==2 spaceDim==3
3754   revDesc2=0; revDescIndx2=0;
3755   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> mDesc1=mDesc2->buildDescendingConnectivity(desc1,descIndx1,revDesc1,revDescIndx1);//meshDim==1 spaceDim==3
3756   revDesc1=0; revDescIndx1=0;
3757   mDesc1->fillCellIdsToKeepFromNodeIds(&nodes[0],&nodes[0]+nodes.size(),true,cellIds1D);
3758   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> cellIds1DTmp(cellIds1D);
3759   //
3760   std::vector<int> cut3DCurve(mDesc1->getNumberOfCells(),-2);
3761   for(const int *it=cellIds1D->begin();it!=cellIds1D->end();it++)
3762     cut3DCurve[*it]=-1;
3763   mDesc1->split3DCurveWithPlane(origin,vec,eps,cut3DCurve);
3764   std::vector< std::pair<int,int> > cut3DSurf(mDesc2->getNumberOfCells());
3765   AssemblyForSplitFrom3DCurve(cut3DCurve,nodes,mDesc2->getNodalConnectivity()->getConstPointer(),mDesc2->getNodalConnectivityIndex()->getConstPointer(),
3766                               mDesc1->getNodalConnectivity()->getConstPointer(),mDesc1->getNodalConnectivityIndex()->getConstPointer(),
3767                               desc1->getConstPointer(),descIndx1->getConstPointer(),cut3DSurf);
3768   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn(DataArrayInt::New()),connI(DataArrayInt::New()),cellIds2(DataArrayInt::New());
3769   connI->pushBackSilent(0); conn->alloc(0,1); cellIds2->alloc(0,1);
3770   subMesh->assemblyForSplitFrom3DSurf(cut3DSurf,desc2->getConstPointer(),descIndx2->getConstPointer(),conn,connI,cellIds2);
3771   if(cellIds2->empty())
3772     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSlice3D : No 3D cells in this intercepts the specified plane !");
3773   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret=MEDCouplingUMesh::New("Slice3D",2);
3774   ret->setCoords(mDesc1->getCoords());
3775   ret->setConnectivity(conn,connI,true);
3776   cellIds=candidates->selectByTupleId(cellIds2->begin(),cellIds2->end());
3777   return ret.retn();
3778 }
3779
3780 /*!
3781  * Creates an 1D mesh by cutting \a this 2D mesh in 3D space with a plane. In
3782 addition to the mesh, returns a new DataArrayInt, of length equal to the number of 1D cells in the result mesh, holding, for each cell in the result mesh, an id of a 2D cell it comes
3783 from. If a result segment is shared by two 2D cells, then the segment in included twice in
3784 the result mesh.
3785  *  \param [in] origin - 3 components of a point defining location of the plane.
3786  *  \param [in] vec - 3 components of a vector normal to the plane. Vector magnitude
3787  *         must be greater than 1e-6.
3788  *  \param [in] eps - half-thickness of the plane.
3789  *  \param [out] cellIds - a new instance of DataArrayInt holding ids of faces
3790  *         producing correspondent segments. The caller is to delete this array
3791  *         using decrRef() as it is no more needed.
3792  *  \return MEDCouplingUMesh * - a new instance of MEDCouplingUMesh. This is an 1D
3793  *         mesh in 3D space. This mesh does not share the node coordinates array with
3794  *         \a this mesh. The caller is to delete this mesh using decrRef() as it is
3795  *         no more needed. 
3796  *  \throw If the coordinates array is not set.
3797  *  \throw If the nodal connectivity of cells is not defined.
3798  *  \throw If \a this->getMeshDimension() != 2 or \a this->getSpaceDimension() != 3.
3799  *  \throw If magnitude of \a vec is less than 1e-6.
3800  *  \throw If the plane does not intersect any 2D cell of \a this mesh.
3801  *  \throw If \a this includes quadratic cells.
3802  */
3803 MEDCouplingUMesh *MEDCouplingUMesh::buildSlice3DSurf(const double *origin, const double *vec, double eps, DataArrayInt *&cellIds) const
3804 {
3805   checkFullyDefined();
3806   if(getMeshDimension()!=2 || getSpaceDimension()!=3)
3807     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSlice3DSurf works on umeshes with meshdim equal to 2 and spaceDim equal to 3 !");
3808   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> candidates=getCellIdsCrossingPlane(origin,vec,eps);
3809   if(candidates->empty())
3810     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSlice3DSurf : No 3D surf cells in this intercepts the specified plane considering bounding boxes !");
3811   std::vector<int> nodes;
3812   DataArrayInt *cellIds1D=0;
3813   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> subMesh=static_cast<MEDCouplingUMesh*>(buildPartOfMySelf(candidates->begin(),candidates->end(),false));
3814   subMesh->findNodesOnPlane(origin,vec,eps,nodes);
3815   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> desc1=DataArrayInt::New();
3816   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> descIndx1=DataArrayInt::New();
3817   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revDesc1=DataArrayInt::New();
3818   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revDescIndx1=DataArrayInt::New();
3819   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> mDesc1=subMesh->buildDescendingConnectivity(desc1,descIndx1,revDesc1,revDescIndx1);//meshDim==1 spaceDim==3
3820   mDesc1->fillCellIdsToKeepFromNodeIds(&nodes[0],&nodes[0]+nodes.size(),true,cellIds1D);
3821   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> cellIds1DTmp(cellIds1D);
3822   //
3823   std::vector<int> cut3DCurve(mDesc1->getNumberOfCells(),-2);
3824   for(const int *it=cellIds1D->begin();it!=cellIds1D->end();it++)
3825     cut3DCurve[*it]=-1;
3826   mDesc1->split3DCurveWithPlane(origin,vec,eps,cut3DCurve);
3827   int ncellsSub=subMesh->getNumberOfCells();
3828   std::vector< std::pair<int,int> > cut3DSurf(ncellsSub);
3829   AssemblyForSplitFrom3DCurve(cut3DCurve,nodes,subMesh->getNodalConnectivity()->getConstPointer(),subMesh->getNodalConnectivityIndex()->getConstPointer(),
3830                               mDesc1->getNodalConnectivity()->getConstPointer(),mDesc1->getNodalConnectivityIndex()->getConstPointer(),
3831                               desc1->getConstPointer(),descIndx1->getConstPointer(),cut3DSurf);
3832   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn(DataArrayInt::New()),connI(DataArrayInt::New()),cellIds2(DataArrayInt::New()); connI->pushBackSilent(0);
3833   conn->alloc(0,1);
3834   const int *nodal=subMesh->getNodalConnectivity()->getConstPointer();
3835   const int *nodalI=subMesh->getNodalConnectivityIndex()->getConstPointer();
3836   for(int i=0;i<ncellsSub;i++)
3837     {
3838       if(cut3DSurf[i].first!=-1 && cut3DSurf[i].second!=-1)
3839         {
3840           if(cut3DSurf[i].first!=-2)
3841             {
3842               conn->pushBackSilent((int)INTERP_KERNEL::NORM_SEG2); conn->pushBackSilent(cut3DSurf[i].first); conn->pushBackSilent(cut3DSurf[i].second);
3843               connI->pushBackSilent(conn->getNumberOfTuples());
3844               cellIds2->pushBackSilent(i);
3845             }
3846           else
3847             {
3848               int cellId3DSurf=cut3DSurf[i].second;
3849               int offset=nodalI[cellId3DSurf]+1;
3850               int nbOfEdges=nodalI[cellId3DSurf+1]-offset;
3851               for(int j=0;j<nbOfEdges;j++)
3852                 {
3853                   conn->pushBackSilent((int)INTERP_KERNEL::NORM_SEG2); conn->pushBackSilent(nodal[offset+j]); conn->pushBackSilent(nodal[offset+(j+1)%nbOfEdges]);
3854                   connI->pushBackSilent(conn->getNumberOfTuples());
3855                   cellIds2->pushBackSilent(cellId3DSurf);
3856                 }
3857             }
3858         }
3859     }
3860   if(cellIds2->empty())
3861     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSlice3DSurf : No 3DSurf cells in this intercepts the specified plane !");
3862   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret=MEDCouplingUMesh::New("Slice3DSurf",1);
3863   ret->setCoords(mDesc1->getCoords());
3864   ret->setConnectivity(conn,connI,true);
3865   cellIds=candidates->selectByTupleId(cellIds2->begin(),cellIds2->end());
3866   return ret.retn();
3867 }
3868
3869 /*!
3870  * Finds cells whose bounding boxes intersect a given plane.
3871  *  \param [in] origin - 3 components of a point defining location of the plane.
3872  *  \param [in] vec - 3 components of a vector normal to the plane. Vector magnitude
3873  *         must be greater than 1e-6.
3874  *  \param [in] eps - half-thickness of the plane.
3875  *  \return DataArrayInt * - a new instance of DataArrayInt holding ids of the found
3876  *         cells. The caller is to delete this array using decrRef() as it is no more
3877  *         needed.
3878  *  \throw If the coordinates array is not set.
3879  *  \throw If the nodal connectivity of cells is not defined.
3880  *  \throw If \a this->getSpaceDimension() != 3.
3881  *  \throw If magnitude of \a vec is less than 1e-6.
3882  *  \sa buildSlice3D()
3883  */
3884 DataArrayInt *MEDCouplingUMesh::getCellIdsCrossingPlane(const double *origin, const double *vec, double eps) const
3885 {
3886   checkFullyDefined();
3887   if(getSpaceDimension()!=3)
3888     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSlice3D works on umeshes with spaceDim equal to 3 !");
3889   double normm=sqrt(vec[0]*vec[0]+vec[1]*vec[1]+vec[2]*vec[2]);
3890   if(normm<1e-6)
3891     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getCellIdsCrossingPlane : parameter 'vec' should have a norm2 greater than 1e-6 !");
3892   double vec2[3];
3893   vec2[0]=vec[1]; vec2[1]=-vec[0]; vec2[2]=0.;//vec2 is the result of cross product of vec with (0,0,1)
3894   double angle=acos(vec[2]/normm);
3895   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> cellIds;
3896   double bbox[6];
3897   if(angle>eps)
3898     {
3899       MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> coo=_coords->deepCpy();
3900       double normm2(sqrt(vec2[0]*vec2[0]+vec2[1]*vec2[1]+vec2[2]*vec2[2]));
3901       if(normm2/normm>1e-6)
3902         MEDCouplingPointSet::Rotate3DAlg(origin,vec2,angle,coo->getNumberOfTuples(),coo->getPointer());
3903       MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> mw=clone(false);//false -> shallow copy
3904       mw->setCoords(coo);
3905       mw->getBoundingBox(bbox);
3906       bbox[4]=origin[2]-eps; bbox[5]=origin[2]+eps;
3907       cellIds=mw->getCellsInBoundingBox(bbox,eps);
3908     }
3909   else
3910     {
3911       getBoundingBox(bbox);
3912       bbox[4]=origin[2]-eps; bbox[5]=origin[2]+eps;
3913       cellIds=getCellsInBoundingBox(bbox,eps);
3914     }
3915   return cellIds.retn();
3916 }
3917
3918 /*!
3919  * This method checks that \a this is a contiguous mesh. The user is expected to call this method on a mesh with meshdim==1.
3920  * If not an exception will thrown. If this is an empty mesh with no cell an exception will be thrown too.
3921  * No consideration of coordinate is done by this method.
3922  * A 1D mesh is said contiguous if : a cell i with nodal connectivity (k,p) the cell i+1 the nodal connectivity should be (p,m)
3923  * If not false is returned. In case that false is returned a call to ParaMEDMEM::MEDCouplingUMesh::mergeNodes could be usefull.
3924  */
3925 bool MEDCouplingUMesh::isContiguous1D() const
3926 {
3927   if(getMeshDimension()!=1)
3928     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::isContiguous1D : this method has a sense only for 1D mesh !");
3929   int nbCells=getNumberOfCells();
3930   if(nbCells<1)
3931     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::isContiguous1D : this method has a sense for non empty mesh !");
3932   const int *connI=_nodal_connec_index->getConstPointer();
3933   const int *conn=_nodal_connec->getConstPointer();
3934   int ref=conn[connI[0]+2];
3935   for(int i=1;i<nbCells;i++)
3936     {
3937       if(conn[connI[i]+1]!=ref)
3938         return false;
3939       ref=conn[connI[i]+2];
3940     }
3941   return true;
3942 }
3943
3944 /*!
3945  * This method is only callable on mesh with meshdim == 1 containing only SEG2 and spaceDim==3.
3946  * This method projects this on the 3D line defined by (pt,v). This methods first checks that all SEG2 are along v vector.
3947  * \param pt reference point of the line
3948  * \param v normalized director vector of the line
3949  * \param eps max precision before throwing an exception
3950  * \param res output of size this->getNumberOfCells
3951  */
3952 void MEDCouplingUMesh::project1D(const double *pt, const double *v, double eps, double *res) const
3953 {
3954   if(getMeshDimension()!=1)
3955     throw INTERP_KERNEL::Exception("Expected a umesh with meshDim == 1 for project1D !");
3956   if(_types.size()!=1 || *(_types.begin())!=INTERP_KERNEL::NORM_SEG2)
3957     throw INTERP_KERNEL::Exception("Expected a umesh with only NORM_SEG2 type of elements for project1D !");
3958   if(getSpaceDimension()!=3)
3959     throw INTERP_KERNEL::Exception("Expected a umesh with spaceDim==3 for project1D !");
3960   MEDCouplingAutoRefCountObjectPtr<MEDCouplingFieldDouble> f=buildDirectionVectorField();
3961   const double *fPtr=f->getArray()->getConstPointer();
3962   double tmp[3];
3963   for(int i=0;i<getNumberOfCells();i++)
3964     {
3965       const double *tmp1=fPtr+3*i;
3966       tmp[0]=tmp1[1]*v[2]-tmp1[2]*v[1];
3967       tmp[1]=tmp1[2]*v[0]-tmp1[0]*v[2];
3968       tmp[2]=tmp1[0]*v[1]-tmp1[1]*v[0];
3969       double n1=INTERP_KERNEL::norm<3>(tmp);
3970       n1/=INTERP_KERNEL::norm<3>(tmp1);
3971       if(n1>eps)
3972         throw INTERP_KERNEL::Exception("UMesh::Projection 1D failed !");
3973     }
3974   const double *coo=getCoords()->getConstPointer();
3975   for(int i=0;i<getNumberOfNodes();i++)
3976     {
3977       std::transform(coo+i*3,coo+i*3+3,pt,tmp,std::minus<double>());
3978       std::transform(tmp,tmp+3,v,tmp,std::multiplies<double>());
3979       res[i]=std::accumulate(tmp,tmp+3,0.);
3980     }
3981 }
3982
3983 /*!
3984  * This method computes the distance from a point \a pt to \a this and the first \a cellId in \a this corresponding to the returned distance. 
3985  * \a this is expected to be a mesh so that its space dimension is equal to its
3986  * mesh dimension + 1. Furthermore only mesh dimension 1 and 2 are supported for the moment.
3987  * Distance from \a ptBg to \a ptEnd is expected to be equal to the space dimension. \a this is also expected to be fully defined (connectivity and coordinates).
3988  *
3989  * WARNING, if there is some orphan nodes in \a this (nodes not fetched by any cells in \a this ( see MEDCouplingUMesh::zipCoords ) ) these nodes will ** not ** been taken
3990  * into account in this method. Only cells and nodes lying on them are considered in the algorithm (even if one of these orphan nodes is closer than returned distance).
3991  * A user that needs to consider orphan nodes should invoke DataArrayDouble::minimalDistanceTo method on the coordinates array of \a this.
3992  *
3993  * So this method is more accurate (so, more costly) than simply searching for the closest point in \a this.
3994  * If only this information is enough for you simply call \c getCoords()->distanceToTuple on \a this.
3995  *
3996  * \param [in] ptBg the start pointer (included) of the coordinates of the point
3997  * \param [in] ptEnd the end pointer (not included) of the coordinates of the point
3998  * \param [out] cellId that corresponds to minimal distance. If the closer node is not linked to any cell in \a this -1 is returned.
3999  * \return the positive value of the distance.
4000  * \throw if distance from \a ptBg to \a ptEnd is not equal to the space dimension. An exception is also thrown if mesh dimension of \a this is not equal to space
4001  * dimension - 1.
4002  * \sa DataArrayDouble::distanceToTuple, MEDCouplingUMesh::distanceToPoints
4003  */
4004 double MEDCouplingUMesh::distanceToPoint(const double *ptBg, const double *ptEnd, int& cellId) const
4005 {
4006   int meshDim=getMeshDimension(),spaceDim=getSpaceDimension();
4007   if(meshDim!=spaceDim-1)
4008     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::distanceToPoint works only for spaceDim=meshDim+1 !");
4009   if(meshDim!=2 && meshDim!=1)
4010     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::distanceToPoint : only mesh dimension 2 and 1 are implemented !");
4011   checkFullyDefined();
4012   if((int)std::distance(ptBg,ptEnd)!=spaceDim)
4013     { std::ostringstream oss; oss << "MEDCouplingUMesh::distanceToPoint : input point has to have dimension equal to the space dimension of this (" << spaceDim << ") !"; throw INTERP_KERNEL::Exception(oss.str().c_str()); }
4014   DataArrayInt *ret1=0;
4015   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> pts=DataArrayDouble::New(); pts->useArray(ptBg,false,C_DEALLOC,1,spaceDim);
4016   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> ret0=distanceToPoints(pts,ret1);
4017   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret1Safe(ret1);
4018   cellId=*ret1Safe->begin();
4019   return *ret0->begin();
4020 }
4021
4022 /*!
4023  * This method computes the distance from each point of points serie \a pts (stored in a DataArrayDouble in which each tuple represents a point)
4024  *  to \a this  and the first \a cellId in \a this corresponding to the returned distance. 
4025  * WARNING, if there is some orphan nodes in \a this (nodes not fetched by any cells in \a this ( see MEDCouplingUMesh::zipCoords ) ) these nodes will ** not ** been taken
4026  * into account in this method. Only cells and nodes lying on them are considered in the algorithm (even if one of these orphan nodes is closer than returned distance).
4027  * A user that needs to consider orphan nodes should invoke DataArrayDouble::minimalDistanceTo method on the coordinates array of \a this.
4028  * 
4029  * \a this is expected to be a mesh so that its space dimension is equal to its
4030  * mesh dimension + 1. Furthermore only mesh dimension 1 and 2 are supported for the moment.
4031  * Number of components of \a pts is expected to be equal to the space dimension. \a this is also expected to be fully defined (connectivity and coordinates).
4032  *
4033  * So this method is more accurate (so, more costly) than simply searching for each point in \a pts the closest point in \a this.
4034  * If only this information is enough for you simply call \c getCoords()->distanceToTuple on \a this.
4035  *
4036  * \param [in] pts the list of points in which each tuple represents a point
4037  * \param [out] cellIds a newly allocated object that tells for each point in \a pts the first cell id in \a this that minimizes the distance.
4038  * \return a newly allocated object to be dealed by the caller that tells for each point in \a pts the distance to \a this.
4039  * \throw if number of components of \a pts is not equal to the space dimension.
4040  * \throw if mesh dimension of \a this is not equal to space dimension - 1.
4041  * \sa DataArrayDouble::distanceToTuple, MEDCouplingUMesh::distanceToPoint
4042  */
4043 DataArrayDouble *MEDCouplingUMesh::distanceToPoints(const DataArrayDouble *pts, DataArrayInt *& cellIds) const
4044 {
4045   if(!pts)
4046     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::distanceToPoints : input points pointer is NULL !");
4047   pts->checkAllocated();
4048   int meshDim=getMeshDimension(),spaceDim=getSpaceDimension();
4049   if(meshDim!=spaceDim-1)
4050     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::distanceToPoints works only for spaceDim=meshDim+1 !");
4051   if(meshDim!=2 && meshDim!=1)
4052     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::distanceToPoints : only mesh dimension 2 and 1 are implemented !");
4053   if(pts->getNumberOfComponents()!=spaceDim)
4054     {
4055       std::ostringstream oss; oss << "MEDCouplingUMesh::distanceToPoints : input pts DataArrayDouble has " << pts->getNumberOfComponents() << " components whereas it should be equal to " << spaceDim << " (mesh spaceDimension) !";
4056       throw INTERP_KERNEL::Exception(oss.str().c_str());
4057     }
4058   checkFullyDefined();
4059   int nbCells=getNumberOfCells();
4060   if(nbCells==0)
4061     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::distanceToPoints : no cells in this !");
4062   int nbOfPts=pts->getNumberOfTuples();
4063   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> ret0=DataArrayDouble::New(); ret0->alloc(nbOfPts,1);
4064   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret1=DataArrayInt::New(); ret1->alloc(nbOfPts,1);
4065   const int *nc=_nodal_connec->begin(),*ncI=_nodal_connec_index->begin(); const double *coords=_coords->begin();
4066   double *ret0Ptr=ret0->getPointer(); int *ret1Ptr=ret1->getPointer(); const double *ptsPtr=pts->begin();
4067   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> bboxArr(getBoundingBoxForBBTree());
4068   const double *bbox(bboxArr->begin());
4069   switch(spaceDim)
4070   {
4071     case 3:
4072       {
4073         BBTreeDst<3> myTree(bbox,0,0,nbCells);
4074         for(int i=0;i<nbOfPts;i++,ret0Ptr++,ret1Ptr++,ptsPtr+=3)
4075           {
4076             double x=std::numeric_limits<double>::max();
4077             std::vector<int> elems;
4078             myTree.getMinDistanceOfMax(ptsPtr,x);
4079             myTree.getElemsWhoseMinDistanceToPtSmallerThan(ptsPtr,x,elems);
4080             DistanceToPoint3DSurfAlg(ptsPtr,&elems[0],&elems[0]+elems.size(),coords,nc,ncI,*ret0Ptr,*ret1Ptr);
4081           }
4082         break;
4083       }
4084     case 2:
4085       {
4086         BBTreeDst<2> myTree(bbox,0,0,nbCells);
4087         for(int i=0;i<nbOfPts;i++,ret0Ptr++,ret1Ptr++,ptsPtr+=2)
4088           {
4089             double x=std::numeric_limits<double>::max();
4090             std::vector<int> elems;
4091             myTree.getMinDistanceOfMax(ptsPtr,x);
4092             myTree.getElemsWhoseMinDistanceToPtSmallerThan(ptsPtr,x,elems);
4093             DistanceToPoint2DCurveAlg(ptsPtr,&elems[0],&elems[0]+elems.size(),coords,nc,ncI,*ret0Ptr,*ret1Ptr);
4094           }
4095         break;
4096       }
4097     default:
4098       throw INTERP_KERNEL::Exception("MEDCouplingUMesh::distanceToPoints : only spacedim 2 and 3 supported !");
4099   }
4100   cellIds=ret1.retn();
4101   return ret0.retn();
4102 }
4103
4104 /*!
4105  * \param [in] pt the start pointer (included) of the coordinates of the point
4106  * \param [in] cellIdsBg the start pointer (included) of cellIds
4107  * \param [in] cellIdsEnd the end pointer (excluded) of cellIds
4108  * \param [in] nc nodal connectivity
4109  * \param [in] ncI nodal connectivity index
4110  * \param [in,out] ret0 the min distance between \a this and the external input point
4111  * \param [out] cellId that corresponds to minimal distance. If the closer node is not linked to any cell in \a this -1 is returned.
4112  * \sa MEDCouplingUMesh::distanceToPoint, MEDCouplingUMesh::distanceToPoints
4113  */
4114 void MEDCouplingUMesh::DistanceToPoint3DSurfAlg(const double *pt, const int *cellIdsBg, const int *cellIdsEnd, const double *coords, const int *nc, const int *ncI, double& ret0, int& cellId)
4115 {
4116   cellId=-1;
4117   ret0=std::numeric_limits<double>::max();
4118   for(const int *zeCell=cellIdsBg;zeCell!=cellIdsEnd;zeCell++)
4119     {
4120       switch((INTERP_KERNEL::NormalizedCellType)nc[ncI[*zeCell]])
4121       {
4122         case INTERP_KERNEL::NORM_TRI3:
4123           {
4124             double tmp=INTERP_KERNEL::DistanceFromPtToTriInSpaceDim3(pt,coords+3*nc[ncI[*zeCell]+1],coords+3*nc[ncI[*zeCell]+2],coords+3*nc[ncI[*zeCell]+3]);
4125             if(tmp<ret0)
4126               { ret0=tmp; cellId=*zeCell; }
4127             break;
4128           }
4129         case INTERP_KERNEL::NORM_QUAD4:
4130         case INTERP_KERNEL::NORM_POLYGON:
4131           {
4132             double tmp=INTERP_KERNEL::DistanceFromPtToPolygonInSpaceDim3(pt,nc+ncI[*zeCell]+1,nc+ncI[*zeCell+1],coords);
4133             if(tmp<ret0)
4134               { ret0=tmp; cellId=*zeCell; }
4135             break;
4136           }
4137         default:
4138           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::distanceToPoint3DSurfAlg : not managed cell type ! Supporting TRI3, QUAD4 and POLYGON !");
4139       }
4140     }
4141 }
4142
4143 /*!
4144  * \param [in] pt the start pointer (included) of the coordinates of the point
4145  * \param [in] cellIdsBg the start pointer (included) of cellIds
4146  * \param [in] cellIdsEnd the end pointer (excluded) of cellIds
4147  * \param [in] nc nodal connectivity
4148  * \param [in] ncI nodal connectivity index
4149  * \param [in,out] ret0 the min distance between \a this and the external input point
4150  * \param [out] cellId that corresponds to minimal distance. If the closer node is not linked to any cell in \a this -1 is returned.
4151  * \sa MEDCouplingUMesh::distanceToPoint, MEDCouplingUMesh::distanceToPoints
4152  */
4153 void MEDCouplingUMesh::DistanceToPoint2DCurveAlg(const double *pt, const int *cellIdsBg, const int *cellIdsEnd, const double *coords, const int *nc, const int *ncI, double& ret0, int& cellId)
4154 {
4155   cellId=-1;
4156   ret0=std::numeric_limits<double>::max();
4157   for(const int *zeCell=cellIdsBg;zeCell!=cellIdsEnd;zeCell++)
4158     {
4159       switch((INTERP_KERNEL::NormalizedCellType)nc[ncI[*zeCell]])
4160       {
4161         case INTERP_KERNEL::NORM_SEG2:
4162           {
4163             std::size_t uselessEntry=0;
4164             double tmp=INTERP_KERNEL::SquareDistanceFromPtToSegInSpaceDim2(pt,coords+2*nc[ncI[*zeCell]+1],coords+2*nc[ncI[*zeCell]+2],uselessEntry);
4165             tmp=sqrt(tmp);
4166             if(tmp<ret0)
4167               { ret0=tmp; cellId=*zeCell; }
4168             break;
4169           }
4170         default:
4171           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::distanceToPoint2DCurveAlg : not managed cell type ! Supporting SEG2 !");
4172       }
4173     }
4174 }
4175
4176 /*!
4177  * Finds cells in contact with a ball (i.e. a point with precision). 
4178  * For speed reasons, the INTERP_KERNEL::NORM_QUAD4, INTERP_KERNEL::NORM_TRI6 and INTERP_KERNEL::NORM_QUAD8 cells are considered as convex cells to detect if a point is IN or OUT.
4179  * If it is not the case, please change their types to INTERP_KERNEL::NORM_POLYGON or INTERP_KERNEL::NORM_QPOLYG before invoking this method.
4180  *
4181  * \warning This method is suitable if the caller intends to evaluate only one
4182  *          point, for more points getCellsContainingPoints() is recommended as it is
4183  *          faster. 
4184  *  \param [in] pos - array of coordinates of the ball central point.
4185  *  \param [in] eps - ball radius.
4186  *  \return int - a smallest id of cells being in contact with the ball, -1 in case
4187  *         if there are no such cells.
4188  *  \throw If the coordinates array is not set.
4189  *  \throw If \a this->getMeshDimension() != \a this->getSpaceDimension().
4190  */
4191 int MEDCouplingUMesh::getCellContainingPoint(const double *pos, double eps) const
4192 {
4193   std::vector<int> elts;
4194   getCellsContainingPoint(pos,eps,elts);
4195   if(elts.empty())
4196     return -1;
4197   return elts.front();
4198 }
4199
4200 /*!
4201  * Finds cells in contact with a ball (i.e. a point with precision).
4202  * For speed reasons, the INTERP_KERNEL::NORM_QUAD4, INTERP_KERNEL::NORM_TRI6 and INTERP_KERNEL::NORM_QUAD8 cells are considered as convex cells to detect if a point is IN or OUT.
4203  * If it is not the case, please change their types to INTERP_KERNEL::NORM_POLYGON or INTERP_KERNEL::NORM_QPOLYG before invoking this method.
4204  * \warning This method is suitable if the caller intends to evaluate only one
4205  *          point, for more points getCellsContainingPoints() is recommended as it is
4206  *          faster. 
4207  *  \param [in] pos - array of coordinates of the ball central point.
4208  *  \param [in] eps - ball radius.
4209  *  \param [out] elts - vector returning ids of the found cells. It is cleared
4210  *         before inserting ids.
4211  *  \throw If the coordinates array is not set.
4212  *  \throw If \a this->getMeshDimension() != \a this->getSpaceDimension().
4213  *
4214  *  \if ENABLE_EXAMPLES
4215  *  \ref cpp_mcumesh_getCellsContainingPoint "Here is a C++ example".<br>
4216  *  \ref  py_mcumesh_getCellsContainingPoint "Here is a Python example".
4217  *  \endif
4218  */
4219 void MEDCouplingUMesh::getCellsContainingPoint(const double *pos, double eps, std::vector<int>& elts) const
4220 {
4221   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> eltsUg,eltsIndexUg;
4222   getCellsContainingPoints(pos,1,eps,eltsUg,eltsIndexUg);
4223   elts.clear(); elts.insert(elts.end(),eltsUg->begin(),eltsUg->end());
4224 }
4225
4226 /// @cond INTERNAL
4227
4228 namespace ParaMEDMEM
4229 {
4230   template<const int SPACEDIMM>
4231   class DummyClsMCUG
4232   {
4233   public:
4234     static const int MY_SPACEDIM=SPACEDIMM;
4235     static const int MY_MESHDIM=8;
4236     typedef int MyConnType;
4237     static const INTERP_KERNEL::NumberingPolicy My_numPol=INTERP_KERNEL::ALL_C_MODE;
4238     // begin
4239     // useless, but for windows compilation ...
4240     const double* getCoordinatesPtr() const { return 0; }
4241     const int* getConnectivityPtr() const { return 0; }
4242     const int* getConnectivityIndexPtr() const { return 0; }
4243     INTERP_KERNEL::NormalizedCellType getTypeOfElement(int) const { return (INTERP_KERNEL::NormalizedCellType)0; }
4244     // end
4245   };
4246
4247   INTERP_KERNEL::Edge *MEDCouplingUMeshBuildQPFromEdge2(INTERP_KERNEL::NormalizedCellType typ, const int *bg, const double *coords2D, std::map< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Node>,int>& m)
4248   {
4249     INTERP_KERNEL::Edge *ret(0);
4250     MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Node> n0(new INTERP_KERNEL::Node(coords2D[2*bg[0]],coords2D[2*bg[0]+1])),n1(new INTERP_KERNEL::Node(coords2D[2*bg[1]],coords2D[2*bg[1]+1]));
4251     m[n0]=bg[0]; m[n1]=bg[1];
4252     switch(typ)
4253     {
4254       case INTERP_KERNEL::NORM_SEG2:
4255         {
4256           ret=new INTERP_KERNEL::EdgeLin(n0,n1);
4257           break;
4258         }
4259       case INTERP_KERNEL::NORM_SEG3:
4260         {
4261           INTERP_KERNEL::Node *n2(new INTERP_KERNEL::Node(coords2D[2*bg[2]],coords2D[2*bg[2]+1])); m[n2]=bg[2];
4262           INTERP_KERNEL::EdgeLin *e1(new INTERP_KERNEL::EdgeLin(n0,n2)),*e2(new INTERP_KERNEL::EdgeLin(n2,n1));
4263           INTERP_KERNEL::SegSegIntersector inters(*e1,*e2);
4264           // is the SEG3 degenerated, and thus can be reduced to a SEG2?
4265           bool colinearity(inters.areColinears());
4266           delete e1; delete e2;
4267           if(colinearity)
4268             { ret=new INTERP_KERNEL::EdgeLin(n0,n1); }
4269           else
4270             { ret=new INTERP_KERNEL::EdgeArcCircle(n0,n2,n1); }
4271           break;
4272         }
4273       default:
4274         throw INTERP_KERNEL::Exception("MEDCouplingUMeshBuildQPFromEdge2 : Expecting a mesh with spaceDim==2 and meshDim==1 !");
4275     }
4276     return ret;
4277   }
4278
4279   INTERP_KERNEL::Edge *MEDCouplingUMeshBuildQPFromEdge(INTERP_KERNEL::NormalizedCellType typ, std::map<int, std::pair<INTERP_KERNEL::Node *,bool> >& mapp2, const int *bg)
4280   {
4281     INTERP_KERNEL::Edge *ret=0;
4282     switch(typ)
4283     {
4284       case INTERP_KERNEL::NORM_SEG2:
4285         {
4286           ret=new INTERP_KERNEL::EdgeLin(mapp2[bg[0]].first,mapp2[bg[1]].first);
4287           break;
4288         }
4289       case INTERP_KERNEL::NORM_SEG3:
4290         {
4291           INTERP_KERNEL::EdgeLin *e1=new INTERP_KERNEL::EdgeLin(mapp2[bg[0]].first,mapp2[bg[2]].first);
4292           INTERP_KERNEL::EdgeLin *e2=new INTERP_KERNEL::EdgeLin(mapp2[bg[2]].first,mapp2[bg[1]].first);
4293           INTERP_KERNEL::SegSegIntersector inters(*e1,*e2);
4294           // is the SEG3 degenerated, and thus can be reduced to a SEG2?
4295           bool colinearity=inters.areColinears();
4296           delete e1; delete e2;
4297           if(colinearity)
4298             ret=new INTERP_KERNEL::EdgeLin(mapp2[bg[0]].first,mapp2[bg[1]].first);
4299           else
4300             ret=new INTERP_KERNEL::EdgeArcCircle(mapp2[bg[0]].first,mapp2[bg[2]].first,mapp2[bg[1]].first);
4301           mapp2[bg[2]].second=false;
4302           break;
4303         }
4304       default:
4305         throw INTERP_KERNEL::Exception("MEDCouplingUMeshBuildQPFromEdge : Expecting a mesh with spaceDim==2 and meshDim==1 !");
4306     }
4307     return ret;
4308   }
4309
4310   /*!
4311    * This method creates a sub mesh in Geometric2D DS. The sub mesh is composed by the sub set of cells in 'candidates' taken from
4312    * the global mesh 'mDesc'.
4313    * The input mesh 'mDesc' must be so that mDim==1 and spaceDim==2.
4314    * 'mapp' returns a mapping between local numbering in submesh (represented by a Node*) and the global node numbering in 'mDesc'.
4315    */
4316   INTERP_KERNEL::QuadraticPolygon *MEDCouplingUMeshBuildQPFromMesh(const MEDCouplingUMesh *mDesc, const std::vector<int>& candidates,
4317                                                                    std::map<INTERP_KERNEL::Node *,int>& mapp)
4318   {
4319     mapp.clear();
4320     std::map<int, std::pair<INTERP_KERNEL::Node *,bool> > mapp2;//bool is for a flag specifying if node is boundary (true) or only a middle for SEG3.
4321     const double *coo=mDesc->getCoords()->getConstPointer();
4322     const int *c=mDesc->getNodalConnectivity()->getConstPointer();
4323     const int *cI=mDesc->getNodalConnectivityIndex()->getConstPointer();
4324     std::set<int> s;
4325     for(std::vector<int>::const_iterator it=candidates.begin();it!=candidates.end();it++)
4326       s.insert(c+cI[*it]+1,c+cI[(*it)+1]);
4327     for(std::set<int>::const_iterator it2=s.begin();it2!=s.end();it2++)
4328       {
4329         INTERP_KERNEL::Node *n=new INTERP_KERNEL::Node(coo[2*(*it2)],coo[2*(*it2)+1]);
4330         mapp2[*it2]=std::pair<INTERP_KERNEL::Node *,bool>(n,true);
4331       }
4332     INTERP_KERNEL::QuadraticPolygon *ret=new INTERP_KERNEL::QuadraticPolygon;
4333     for(std::vector<int>::const_iterator it=candidates.begin();it!=candidates.end();it++)
4334       {
4335         INTERP_KERNEL::NormalizedCellType typ=(INTERP_KERNEL::NormalizedCellType)c[cI[*it]];
4336         ret->pushBack(MEDCouplingUMeshBuildQPFromEdge(typ,mapp2,c+cI[*it]+1));
4337       }
4338     for(std::map<int, std::pair<INTERP_KERNEL::Node *,bool> >::const_iterator it2=mapp2.begin();it2!=mapp2.end();it2++)
4339       {
4340         if((*it2).second.second)
4341           mapp[(*it2).second.first]=(*it2).first;
4342         ((*it2).second.first)->decrRef();
4343       }
4344     return ret;
4345   }
4346
4347   INTERP_KERNEL::Node *MEDCouplingUMeshBuildQPNode(int nodeId, const double *coo1, int offset1, const double *coo2, int offset2, const std::vector<double>& addCoo)
4348   {
4349     if(nodeId>=offset2)
4350       {
4351         int locId=nodeId-offset2;
4352         return new INTERP_KERNEL::Node(addCoo[2*locId],addCoo[2*locId+1]);
4353       }
4354     if(nodeId>=offset1)
4355       {
4356         int locId=nodeId-offset1;
4357         return new INTERP_KERNEL::Node(coo2[2*locId],coo2[2*locId+1]);
4358       }
4359     return new INTERP_KERNEL::Node(coo1[2*nodeId],coo1[2*nodeId+1]);
4360   }
4361
4362   /**
4363    * Construct a mapping between set of Nodes and the standart MEDCoupling connectivity format (c, cI).
4364    */
4365   void MEDCouplingUMeshBuildQPFromMesh3(const double *coo1, int offset1, const double *coo2, int offset2, const std::vector<double>& addCoo,
4366                                         const int *desc1Bg, const int *desc1End, const std::vector<std::vector<int> >& intesctEdges1,
4367                                         /*output*/std::map<INTERP_KERNEL::Node *,int>& mapp, std::map<int,INTERP_KERNEL::Node *>& mappRev)
4368   {
4369     for(const int *desc1=desc1Bg;desc1!=desc1End;desc1++)
4370       {
4371         int eltId1=abs(*desc1)-1;
4372         for(std::vector<int>::const_iterator it1=intesctEdges1[eltId1].begin();it1!=intesctEdges1[eltId1].end();it1++)
4373           {
4374             std::map<int,INTERP_KERNEL::Node *>::const_iterator it=mappRev.find(*it1);
4375             if(it==mappRev.end())
4376               {
4377                 INTERP_KERNEL::Node *node=MEDCouplingUMeshBuildQPNode(*it1,coo1,offset1,coo2,offset2,addCoo);
4378                 mapp[node]=*it1;
4379                 mappRev[*it1]=node;
4380               }
4381           }
4382       }
4383   }
4384 }
4385
4386 /// @endcond
4387
4388 template<int SPACEDIM>
4389 void MEDCouplingUMesh::getCellsContainingPointsAlg(const double *coords, const double *pos, int nbOfPoints,
4390                                                    double eps, MEDCouplingAutoRefCountObjectPtr<DataArrayInt>& elts, MEDCouplingAutoRefCountObjectPtr<DataArrayInt>& eltsIndex) const
4391 {
4392   elts=DataArrayInt::New(); eltsIndex=DataArrayInt::New(); eltsIndex->alloc(nbOfPoints+1,1); eltsIndex->setIJ(0,0,0); elts->alloc(0,1);
4393   int *eltsIndexPtr(eltsIndex->getPointer());
4394   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> bboxArr(getBoundingBoxForBBTree(eps));
4395   const double *bbox(bboxArr->begin());
4396   int nbOfCells=getNumberOfCells();
4397   const int *conn=_nodal_connec->getConstPointer();
4398   const int *connI=_nodal_connec_index->getConstPointer();
4399   double bb[2*SPACEDIM];
4400   BBTree<SPACEDIM,int> myTree(&bbox[0],0,0,nbOfCells,-eps);
4401   for(int i=0;i<nbOfPoints;i++)
4402     {
4403       eltsIndexPtr[i+1]=eltsIndexPtr[i];
4404       for(int j=0;j<SPACEDIM;j++)
4405         {
4406           bb[2*j]=pos[SPACEDIM*i+j];
4407           bb[2*j+1]=pos[SPACEDIM*i+j];
4408         }
4409       std::vector<int> candidates;
4410       myTree.getIntersectingElems(bb,candidates);
4411       for(std::vector<int>::const_iterator iter=candidates.begin();iter!=candidates.end();iter++)
4412         {
4413           int sz(connI[(*iter)+1]-connI[*iter]-1);
4414           INTERP_KERNEL::NormalizedCellType ct((INTERP_KERNEL::NormalizedCellType)conn[connI[*iter]]);
4415           bool status(false);
4416           if(ct!=INTERP_KERNEL::NORM_POLYGON && ct!=INTERP_KERNEL::NORM_QPOLYG)
4417             status=INTERP_KERNEL::PointLocatorAlgos<DummyClsMCUG<SPACEDIM> >::isElementContainsPoint(pos+i*SPACEDIM,ct,coords,conn+connI[*iter]+1,sz,eps);
4418           else
4419             {
4420               if(SPACEDIM!=2)
4421                 throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getCellsContainingPointsAlg : not implemented yet for POLYGON and QPOLYGON in spaceDim 3 !");
4422               INTERP_KERNEL::QUADRATIC_PLANAR::_precision=eps;
4423               INTERP_KERNEL::QUADRATIC_PLANAR::_arc_detection_precision=eps;
4424               std::vector<INTERP_KERNEL::Node *> nodes(sz);
4425               INTERP_KERNEL::QuadraticPolygon *pol(0);
4426               for(int j=0;j<sz;j++)
4427                 {
4428                   int nodeId(conn[connI[*iter]+1+j]);
4429                   nodes[j]=new INTERP_KERNEL::Node(coords[nodeId*SPACEDIM],coords[nodeId*SPACEDIM+1]);
4430                 }
4431               if(!INTERP_KERNEL::CellModel::GetCellModel(ct).isQuadratic())
4432                 pol=INTERP_KERNEL::QuadraticPolygon::BuildLinearPolygon(nodes);
4433               else
4434                 pol=INTERP_KERNEL::QuadraticPolygon::BuildArcCirclePolygon(nodes);
4435               INTERP_KERNEL::Node *n(new INTERP_KERNEL::Node(pos[i*SPACEDIM],pos[i*SPACEDIM+1]));
4436               double a(0.),b(0.),c(0.);
4437               a=pol->normalizeMe(b,c); n->applySimilarity(b,c,a);
4438               status=pol->isInOrOut2(n);
4439               delete pol; n->decrRef();
4440             }
4441           if(status)
4442             {
4443               eltsIndexPtr[i+1]++;
4444               elts->pushBackSilent(*iter);
4445             }
4446         }
4447     }
4448 }
4449 /*!
4450  * Finds cells in contact with several balls (i.e. points with precision).
4451  * This method is an extension of getCellContainingPoint() and
4452  * getCellsContainingPoint() for the case of multiple points.
4453  * For speed reasons, the INTERP_KERNEL::NORM_QUAD4, INTERP_KERNEL::NORM_TRI6 and INTERP_KERNEL::NORM_QUAD8 cells are considered as convex cells to detect if a point is IN or OUT.
4454  * If it is not the case, please change their types to INTERP_KERNEL::NORM_POLYGON or INTERP_KERNEL::NORM_QPOLYG before invoking this method.
4455  *  \param [in] pos - an array of coordinates of points in full interlace mode :
4456  *         X0,Y0,Z0,X1,Y1,Z1,... Size of the array must be \a
4457  *         this->getSpaceDimension() * \a nbOfPoints 
4458  *  \param [in] nbOfPoints - number of points to locate within \a this mesh.
4459  *  \param [in] eps - radius of balls (i.e. the precision).
4460  *  \param [out] elts - vector returning ids of found cells.
4461  *  \param [out] eltsIndex - an array, of length \a nbOfPoints + 1,
4462  *         dividing cell ids in \a elts into groups each referring to one
4463  *         point. Its every element (except the last one) is an index pointing to the
4464  *         first id of a group of cells. For example cells in contact with the *i*-th
4465  *         point are described by following range of indices:
4466  *         [ \a eltsIndex[ *i* ], \a eltsIndex[ *i*+1 ] ) and the cell ids are
4467  *         \a elts[ \a eltsIndex[ *i* ]], \a elts[ \a eltsIndex[ *i* ] + 1 ], ...
4468  *         Number of cells in contact with the *i*-th point is
4469  *         \a eltsIndex[ *i*+1 ] - \a eltsIndex[ *i* ].
4470  *  \throw If the coordinates array is not set.
4471  *  \throw If \a this->getMeshDimension() != \a this->getSpaceDimension().
4472  *
4473  *  \if ENABLE_EXAMPLES
4474  *  \ref cpp_mcumesh_getCellsContainingPoints "Here is a C++ example".<br>
4475  *  \ref  py_mcumesh_getCellsContainingPoints "Here is a Python example".
4476  *  \endif
4477  */
4478 void MEDCouplingUMesh::getCellsContainingPoints(const double *pos, int nbOfPoints, double eps,
4479                                                 MEDCouplingAutoRefCountObjectPtr<DataArrayInt>& elts, MEDCouplingAutoRefCountObjectPtr<DataArrayInt>& eltsIndex) const
4480 {
4481   int spaceDim=getSpaceDimension();
4482   int mDim=getMeshDimension();
4483   if(spaceDim==3)
4484     {
4485       if(mDim==3)
4486         {
4487           const double *coords=_coords->getConstPointer();
4488           getCellsContainingPointsAlg<3>(coords,pos,nbOfPoints,eps,elts,eltsIndex);
4489         }
4490       /*else if(mDim==2)
4491         {
4492
4493         }*/
4494       else
4495         throw INTERP_KERNEL::Exception("For spaceDim==3 only meshDim==3 implemented for getelementscontainingpoints !");
4496     }
4497   else if(spaceDim==2)
4498     {
4499       if(mDim==2)
4500         {
4501           const double *coords=_coords->getConstPointer();
4502           getCellsContainingPointsAlg<2>(coords,pos,nbOfPoints,eps,elts,eltsIndex);
4503         }
4504       else
4505         throw INTERP_KERNEL::Exception("For spaceDim==2 only meshDim==2 implemented for getelementscontainingpoints !");
4506     }
4507   else if(spaceDim==1)
4508     {
4509       if(mDim==1)
4510         {
4511           const double *coords=_coords->getConstPointer();
4512           getCellsContainingPointsAlg<1>(coords,pos,nbOfPoints,eps,elts,eltsIndex);
4513         }
4514       else
4515         throw INTERP_KERNEL::Exception("For spaceDim==1 only meshDim==1 implemented for getelementscontainingpoints !");
4516     }
4517   else
4518     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getCellsContainingPoints : not managed for mdim not in [1,2,3] !");
4519 }
4520
4521 /*!
4522  * Finds butterfly cells in \a this mesh. A 2D cell is considered to be butterfly if at
4523  * least two its edges intersect each other anywhere except their extremities. An
4524  * INTERP_KERNEL::NORM_NORI3 cell can \b not be butterfly.
4525  *  \param [in,out] cells - a vector returning ids of the found cells. It is not
4526  *         cleared before filling in.
4527  *  \param [in] eps - precision.
4528  *  \throw If \a this->getMeshDimension() != 2.
4529  *  \throw If \a this->getSpaceDimension() != 2 && \a this->getSpaceDimension() != 3.
4530  */
4531 void MEDCouplingUMesh::checkButterflyCells(std::vector<int>& cells, double eps) const
4532 {
4533   const char msg[]="Butterfly detection work only for 2D cells with spaceDim==2 or 3!";
4534   if(getMeshDimension()!=2)
4535     throw INTERP_KERNEL::Exception(msg);
4536   int spaceDim=getSpaceDimension();
4537   if(spaceDim!=2 && spaceDim!=3)
4538     throw INTERP_KERNEL::Exception(msg);
4539   const int *conn=_nodal_connec->getConstPointer();
4540   const int *connI=_nodal_connec_index->getConstPointer();
4541   int nbOfCells=getNumberOfCells();
4542   std::vector<double> cell2DinS2;
4543   for(int i=0;i<nbOfCells;i++)
4544     {
4545       int offset=connI[i];
4546       int nbOfNodesForCell=connI[i+1]-offset-1;
4547       if(nbOfNodesForCell<=3)
4548         continue;
4549       bool isQuad=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[offset]).isQuadratic();
4550       project2DCellOnXY(conn+offset+1,conn+connI[i+1],cell2DinS2);
4551       if(isButterfly2DCell(cell2DinS2,isQuad,eps))
4552         cells.push_back(i);
4553       cell2DinS2.clear();
4554     }
4555 }
4556
4557 /*!
4558  * This method is typically requested to unbutterfly 2D linear cells in \b this.
4559  *
4560  * This method expects that space dimension is equal to 2 and mesh dimension is equal to 2 too. If it is not the case an INTERP_KERNEL::Exception will be thrown.
4561  * This method works only for linear 2D cells. If there is any of non linear cells (INTERP_KERNEL::NORM_QUAD8 for example) an INTERP_KERNEL::Exception will be thrown too.
4562  * 
4563  * For each 2D linear cell in \b this, this method builds the convex envelop (or the convex hull) of the current cell.
4564  * This convex envelop is computed using Jarvis march algorithm.
4565  * The coordinates and the number of cells of \b this remain unchanged on invocation of this method.
4566  * Only connectivity of some cells could be modified if those cells were not representing a convex envelop. If a cell already equals its convex envelop (regardless orientation)
4567  * its connectivity will remain unchanged. If the computation leads to a modification of nodal connectivity of a cell its geometric type will be modified to INTERP_KERNEL::NORM_POLYGON.
4568  *
4569  * \return a newly allocated array containing cellIds that have been modified if any. If no cells have been impacted by this method NULL is returned.
4570  * \sa MEDCouplingUMesh::colinearize2D
4571  */
4572 DataArrayInt *MEDCouplingUMesh::convexEnvelop2D()
4573 {
4574   if(getMeshDimension()!=2 || getSpaceDimension()!=2)
4575     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convexEnvelop2D  works only for meshDim=2 and spaceDim=2 !");
4576   checkFullyDefined();
4577   const double *coords=getCoords()->getConstPointer();
4578   int nbOfCells=getNumberOfCells();
4579   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> nodalConnecIndexOut=DataArrayInt::New();
4580   nodalConnecIndexOut->alloc(nbOfCells+1,1);
4581   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> nodalConnecOut(DataArrayInt::New());
4582   int *workIndexOut=nodalConnecIndexOut->getPointer();
4583   *workIndexOut=0;
4584   const int *nodalConnecIn=_nodal_connec->getConstPointer();
4585   const int *nodalConnecIndexIn=_nodal_connec_index->getConstPointer();
4586   std::set<INTERP_KERNEL::NormalizedCellType> types;
4587   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> isChanged(DataArrayInt::New());
4588   isChanged->alloc(0,1);
4589   for(int i=0;i<nbOfCells;i++,workIndexOut++)
4590     {
4591       int pos=nodalConnecOut->getNumberOfTuples();
4592       if(BuildConvexEnvelopOf2DCellJarvis(coords,nodalConnecIn+nodalConnecIndexIn[i],nodalConnecIn+nodalConnecIndexIn[i+1],nodalConnecOut))
4593         isChanged->pushBackSilent(i);
4594       types.insert((INTERP_KERNEL::NormalizedCellType)nodalConnecOut->getIJ(pos,0));
4595       workIndexOut[1]=nodalConnecOut->getNumberOfTuples();
4596     }
4597   if(isChanged->empty())
4598     return 0;
4599   setConnectivity(nodalConnecOut,nodalConnecIndexOut,false);
4600   _types=types;
4601   return isChanged.retn();
4602 }
4603
4604 /*!
4605  * This method is \b NOT const because it can modify \a this.
4606  * \a this is expected to be an unstructured mesh with meshDim==2 and spaceDim==3. If not an exception will be thrown.
4607  * \param mesh1D is an unstructured mesh with MeshDim==1 and spaceDim==3. If not an exception will be thrown.
4608  * \param policy specifies the type of extrusion chosen. \b 0 for translation (most simple),
4609  * \b 1 for translation and rotation around point of 'mesh1D'.
4610  * \return an unstructured mesh with meshDim==3 and spaceDim==3. The returned mesh has the same coords than \a this.  
4611  */
4612 MEDCouplingUMesh *MEDCouplingUMesh::buildExtrudedMesh(const MEDCouplingUMesh *mesh1D, int policy)
4613 {
4614   checkFullyDefined();
4615   mesh1D->checkFullyDefined();
4616   if(!mesh1D->isContiguous1D())
4617     throw INTERP_KERNEL::Exception("buildExtrudedMesh : 1D mesh passed in parameter is not contiguous !");
4618   if(getSpaceDimension()!=mesh1D->getSpaceDimension())
4619     throw INTERP_KERNEL::Exception("Invalid call to buildExtrudedMesh this and mesh1D must have same space dimension !");
4620   if((getMeshDimension()!=2 || getSpaceDimension()!=3) && (getMeshDimension()!=1 || getSpaceDimension()!=2))
4621     throw INTERP_KERNEL::Exception("Invalid 'this' for buildExtrudedMesh method : must be (meshDim==2 and spaceDim==3) or (meshDim==1 and spaceDim==2) !");
4622   if(mesh1D->getMeshDimension()!=1)
4623     throw INTERP_KERNEL::Exception("Invalid 'mesh1D' for buildExtrudedMesh method : must be meshDim==1 !");
4624   bool isQuad=false;
4625   if(isPresenceOfQuadratic())
4626     {
4627       if(mesh1D->isFullyQuadratic())
4628         isQuad=true;
4629       else
4630         throw INTERP_KERNEL::Exception("Invalid 2D mesh and 1D mesh because 2D mesh has quadratic cells and 1D is not fully quadratic !");
4631     }
4632   int oldNbOfNodes=getNumberOfNodes();
4633   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> newCoords;
4634   switch(policy)
4635   {
4636     case 0:
4637       {
4638         newCoords=fillExtCoordsUsingTranslation(mesh1D,isQuad);
4639         break;
4640       }
4641     case 1:
4642       {
4643         newCoords=fillExtCoordsUsingTranslAndAutoRotation(mesh1D,isQuad);
4644         break;
4645       }
4646     default:
4647       throw INTERP_KERNEL::Exception("Not implemented extrusion policy : must be in (0) !");
4648   }
4649   setCoords(newCoords);
4650   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret=buildExtrudedMeshFromThisLowLev(oldNbOfNodes,isQuad);
4651   updateTime();
4652   return ret.retn();
4653 }
4654
4655 /*!
4656  * This method works on a 3D curve linear mesh that is to say (meshDim==1 and spaceDim==3).
4657  * If it is not the case an exception will be thrown.
4658  * This method is non const because the coordinate of \a this can be appended with some new points issued from
4659  * intersection of plane defined by ('origin','vec').
4660  * This method has one in/out parameter : 'cut3DCurve'.
4661  * Param 'cut3DCurve' is expected to be of size 'this->getNumberOfCells()'. For each i in [0,'this->getNumberOfCells()')
4662  * if cut3DCurve[i]==-2, it means that for cell #i in \a this nothing has been detected previously.
4663  * if cut3DCurve[i]==-1, it means that cell#i has been already detected to be fully part of plane defined by ('origin','vec').
4664  * This method will throw an exception if \a this contains a non linear segment.
4665  */
4666 void MEDCouplingUMesh::split3DCurveWithPlane(const double *origin, const double *vec, double eps, std::vector<int>& cut3DCurve)
4667 {
4668   checkFullyDefined();
4669   if(getMeshDimension()!=1 || getSpaceDimension()!=3)
4670     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::split3DCurveWithPlane works on umeshes with meshdim equal to 1 and spaceDim equal to 3 !");
4671   int ncells=getNumberOfCells();
4672   int nnodes=getNumberOfNodes();
4673   double vec2[3],vec3[3],vec4[3];
4674   double normm=sqrt(vec[0]*vec[0]+vec[1]*vec[1]+vec[2]*vec[2]);
4675   if(normm<1e-6)
4676     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::split3DCurveWithPlane : parameter 'vec' should have a norm2 greater than 1e-6 !");
4677   vec2[0]=vec[0]/normm; vec2[1]=vec[1]/normm; vec2[2]=vec[2]/normm;
4678   const int *conn=_nodal_connec->getConstPointer();
4679   const int *connI=_nodal_connec_index->getConstPointer();
4680   const double *coo=_coords->getConstPointer();
4681   std::vector<double> addCoo;
4682   for(int i=0;i<ncells;i++)
4683     {
4684       if(conn[connI[i]]==(int)INTERP_KERNEL::NORM_SEG2)
4685         {
4686           if(cut3DCurve[i]==-2)
4687             {
4688               int st=conn[connI[i]+1],endd=conn[connI[i]+2];
4689               vec3[0]=coo[3*endd]-coo[3*st]; vec3[1]=coo[3*endd+1]-coo[3*st+1]; vec3[2]=coo[3*endd+2]-coo[3*st+2];
4690               double normm2=sqrt(vec3[0]*vec3[0]+vec3[1]*vec3[1]+vec3[2]*vec3[2]);
4691               double colin=std::abs((vec3[0]*vec2[0]+vec3[1]*vec2[1]+vec3[2]*vec2[2])/normm2);
4692               if(colin>eps)//if colin<=eps -> current SEG2 is colinear to the input plane
4693                 {
4694                   const double *st2=coo+3*st;
4695                   vec4[0]=st2[0]-origin[0]; vec4[1]=st2[1]-origin[1]; vec4[2]=st2[2]-origin[2];
4696                   double pos=-(vec4[0]*vec2[0]+vec4[1]*vec2[1]+vec4[2]*vec2[2])/((vec3[0]*vec2[0]+vec3[1]*vec2[1]+vec3[2]*vec2[2]));
4697                   if(pos>eps && pos<1-eps)
4698                     {
4699                       int nNode=((int)addCoo.size())/3;
4700                       vec4[0]=st2[0]+pos*vec3[0]; vec4[1]=st2[1]+pos*vec3[1]; vec4[2]=st2[2]+pos*vec3[2];
4701                       addCoo.insert(addCoo.end(),vec4,vec4+3);
4702                       cut3DCurve[i]=nnodes+nNode;
4703                     }
4704                 }
4705             }
4706         }
4707       else
4708         throw INTERP_KERNEL::Exception("MEDCouplingUMesh::split3DCurveWithPlane : this method is only available for linear cell (NORM_SEG2) !");
4709     }
4710   if(!addCoo.empty())
4711     {
4712       int newNbOfNodes=nnodes+((int)addCoo.size())/3;
4713       MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> coo2=DataArrayDouble::New();
4714       coo2->alloc(newNbOfNodes,3);
4715       double *tmp=coo2->getPointer();
4716       tmp=std::copy(_coords->begin(),_coords->end(),tmp);
4717       std::copy(addCoo.begin(),addCoo.end(),tmp);
4718       DataArrayDouble::SetArrayIn(coo2,_coords);
4719     }
4720 }
4721
4722 /*!
4723  * This method incarnates the policy 0 for MEDCouplingUMesh::buildExtrudedMesh method.
4724  * \param mesh1D is the input 1D mesh used for translation computation.
4725  * \return newCoords new coords filled by this method. 
4726  */
4727 DataArrayDouble *MEDCouplingUMesh::fillExtCoordsUsingTranslation(const MEDCouplingUMesh *mesh1D, bool isQuad) const
4728 {
4729   int oldNbOfNodes=getNumberOfNodes();
4730   int nbOf1DCells=mesh1D->getNumberOfCells();
4731   int spaceDim=getSpaceDimension();
4732   DataArrayDouble *ret=DataArrayDouble::New();
4733   std::vector<bool> isQuads;
4734   int nbOfLevsInVec=isQuad?2*nbOf1DCells+1:nbOf1DCells+1;
4735   ret->alloc(oldNbOfNodes*nbOfLevsInVec,spaceDim);
4736   double *retPtr=ret->getPointer();
4737   const double *coords=getCoords()->getConstPointer();
4738   double *work=std::copy(coords,coords+spaceDim*oldNbOfNodes,retPtr);
4739   std::vector<int> v;
4740   std::vector<double> c;
4741   double vec[3];
4742   v.reserve(3);
4743   c.reserve(6);
4744   for(int i=0;i<nbOf1DCells;i++)
4745     {
4746       v.resize(0);
4747       mesh1D->getNodeIdsOfCell(i,v);
4748       c.resize(0);
4749       mesh1D->getCoordinatesOfNode(v[isQuad?2:1],c);
4750       mesh1D->getCoordinatesOfNode(v[0],c);
4751       std::transform(c.begin(),c.begin()+spaceDim,c.begin()+spaceDim,vec,std::minus<double>());
4752       for(int j=0;j<oldNbOfNodes;j++)
4753         work=std::transform(vec,vec+spaceDim,retPtr+spaceDim*(i*oldNbOfNodes+j),work,std::plus<double>());
4754       if(isQuad)
4755         {
4756           c.resize(0);
4757           mesh1D->getCoordinatesOfNode(v[1],c);
4758           mesh1D->getCoordinatesOfNode(v[0],c);
4759           std::transform(c.begin(),c.begin()+spaceDim,c.begin()+spaceDim,vec,std::minus<double>());
4760           for(int j=0;j<oldNbOfNodes;j++)
4761             work=std::transform(vec,vec+spaceDim,retPtr+spaceDim*(i*oldNbOfNodes+j),work,std::plus<double>());
4762         }
4763     }
4764   ret->copyStringInfoFrom(*getCoords());
4765   return ret;
4766 }
4767
4768 /*!
4769  * This method incarnates the policy 1 for MEDCouplingUMesh::buildExtrudedMesh method.
4770  * \param mesh1D is the input 1D mesh used for translation and automatic rotation computation.
4771  * \return newCoords new coords filled by this method. 
4772  */
4773 DataArrayDouble *MEDCouplingUMesh::fillExtCoordsUsingTranslAndAutoRotation(const MEDCouplingUMesh *mesh1D, bool isQuad) const
4774 {
4775   if(mesh1D->getSpaceDimension()==2)
4776     return fillExtCoordsUsingTranslAndAutoRotation2D(mesh1D,isQuad);
4777   if(mesh1D->getSpaceDimension()==3)
4778     return fillExtCoordsUsingTranslAndAutoRotation3D(mesh1D,isQuad);
4779   throw INTERP_KERNEL::Exception("Not implemented rotation and translation alg. for spacedim other than 2 and 3 !");
4780 }
4781
4782 /*!
4783  * This method incarnates the policy 1 for MEDCouplingUMesh::buildExtrudedMesh method.
4784  * \param mesh1D is the input 1D mesh used for translation and automatic rotation computation.
4785  * \return newCoords new coords filled by this method. 
4786  */
4787 DataArrayDouble *MEDCouplingUMesh::fillExtCoordsUsingTranslAndAutoRotation2D(const MEDCouplingUMesh *mesh1D, bool isQuad) const
4788 {
4789   if(isQuad)
4790     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::fillExtCoordsUsingTranslAndAutoRotation2D : not implemented for quadratic cells !");
4791   int oldNbOfNodes=getNumberOfNodes();
4792   int nbOf1DCells=mesh1D->getNumberOfCells();
4793   if(nbOf1DCells<2)
4794     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::fillExtCoordsUsingTranslAndAutoRotation2D : impossible to detect any angle of rotation ! Change extrusion policy 1->0 !");
4795   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> ret=DataArrayDouble::New();
4796   int nbOfLevsInVec=nbOf1DCells+1;
4797   ret->alloc(oldNbOfNodes*nbOfLevsInVec,2);
4798   double *retPtr=ret->getPointer();
4799   retPtr=std::copy(getCoords()->getConstPointer(),getCoords()->getConstPointer()+getCoords()->getNbOfElems(),retPtr);
4800   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> tmp=MEDCouplingUMesh::New();
4801   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> tmp2=getCoords()->deepCpy();
4802   tmp->setCoords(tmp2);
4803   const double *coo1D=mesh1D->getCoords()->getConstPointer();
4804   const int *conn1D=mesh1D->getNodalConnectivity()->getConstPointer();
4805   const int *connI1D=mesh1D->getNodalConnectivityIndex()->getConstPointer();
4806   for(int i=1;i<nbOfLevsInVec;i++)
4807     {
4808       const double *begin=coo1D+2*conn1D[connI1D[i-1]+1];
4809       const double *end=coo1D+2*conn1D[connI1D[i-1]+2];
4810       const double *third=i+1<nbOfLevsInVec?coo1D+2*conn1D[connI1D[i]+2]:coo1D+2*conn1D[connI1D[i-2]+1];
4811       const double vec[2]={end[0]-begin[0],end[1]-begin[1]};
4812       tmp->translate(vec);
4813       double tmp3[2],radius,alpha,alpha0;
4814       const double *p0=i+1<nbOfLevsInVec?begin:third;
4815       const double *p1=i+1<nbOfLevsInVec?end:begin;
4816       const double *p2=i+1<nbOfLevsInVec?third:end;
4817       INTERP_KERNEL::EdgeArcCircle::GetArcOfCirclePassingThru(p0,p1,p2,tmp3,radius,alpha,alpha0);
4818       double cosangle=i+1<nbOfLevsInVec?(p0[0]-tmp3[0])*(p1[0]-tmp3[0])+(p0[1]-tmp3[1])*(p1[1]-tmp3[1]):(p2[0]-tmp3[0])*(p1[0]-tmp3[0])+(p2[1]-tmp3[1])*(p1[1]-tmp3[1]);
4819       double angle=acos(cosangle/(radius*radius));
4820       tmp->rotate(end,0,angle);
4821       retPtr=std::copy(tmp2->getConstPointer(),tmp2->getConstPointer()+tmp2->getNbOfElems(),retPtr);
4822     }
4823   return ret.retn();
4824 }
4825
4826 /*!
4827  * This method incarnates the policy 1 for MEDCouplingUMesh::buildExtrudedMesh method.
4828  * \param mesh1D is the input 1D mesh used for translation and automatic rotation computation.
4829  * \return newCoords new coords filled by this method. 
4830  */
4831 DataArrayDouble *MEDCouplingUMesh::fillExtCoordsUsingTranslAndAutoRotation3D(const MEDCouplingUMesh *mesh1D, bool isQuad) const
4832 {
4833   if(isQuad)
4834     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::fillExtCoordsUsingTranslAndAutoRotation3D : not implemented for quadratic cells !");
4835   int oldNbOfNodes=getNumberOfNodes();
4836   int nbOf1DCells=mesh1D->getNumberOfCells();
4837   if(nbOf1DCells<2)
4838     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::fillExtCoordsUsingTranslAndAutoRotation3D : impossible to detect any angle of rotation ! Change extrusion policy 1->0 !");
4839   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> ret=DataArrayDouble::New();
4840   int nbOfLevsInVec=nbOf1DCells+1;
4841   ret->alloc(oldNbOfNodes*nbOfLevsInVec,3);
4842   double *retPtr=ret->getPointer();
4843   retPtr=std::copy(getCoords()->getConstPointer(),getCoords()->getConstPointer()+getCoords()->getNbOfElems(),retPtr);
4844   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> tmp=MEDCouplingUMesh::New();
4845   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> tmp2=getCoords()->deepCpy();
4846   tmp->setCoords(tmp2);
4847   const double *coo1D=mesh1D->getCoords()->getConstPointer();
4848   const int *conn1D=mesh1D->getNodalConnectivity()->getConstPointer();
4849   const int *connI1D=mesh1D->getNodalConnectivityIndex()->getConstPointer();
4850   for(int i=1;i<nbOfLevsInVec;i++)
4851     {
4852       const double *begin=coo1D+3*conn1D[connI1D[i-1]+1];
4853       const double *end=coo1D+3*conn1D[connI1D[i-1]+2];
4854       const double *third=i+1<nbOfLevsInVec?coo1D+3*conn1D[connI1D[i]+2]:coo1D+3*conn1D[connI1D[i-2]+1];
4855       const double vec[3]={end[0]-begin[0],end[1]-begin[1],end[2]-begin[2]};
4856       tmp->translate(vec);
4857       double tmp3[2],radius,alpha,alpha0;
4858       const double *p0=i+1<nbOfLevsInVec?begin:third;
4859       const double *p1=i+1<nbOfLevsInVec?end:begin;
4860       const double *p2=i+1<nbOfLevsInVec?third:end;
4861       double vecPlane[3]={
4862         (p1[1]-p0[1])*(p2[2]-p1[2])-(p1[2]-p0[2])*(p2[1]-p1[1]),
4863         (p1[2]-p0[2])*(p2[0]-p1[0])-(p1[0]-p0[0])*(p2[2]-p1[2]),
4864         (p1[0]-p0[0])*(p2[1]-p1[1])-(p1[1]-p0[1])*(p2[0]-p1[0]),
4865       };
4866       double norm=sqrt(vecPlane[0]*vecPlane[0]+vecPlane[1]*vecPlane[1]+vecPlane[2]*vecPlane[2]);
4867       if(norm>1.e-7)
4868         {
4869           vecPlane[0]/=norm; vecPlane[1]/=norm; vecPlane[2]/=norm;
4870           double norm2=sqrt(vecPlane[0]*vecPlane[0]+vecPlane[1]*vecPlane[1]);
4871           double vec2[2]={vecPlane[1]/norm2,-vecPlane[0]/norm2};
4872           double s2=norm2;
4873           double c2=cos(asin(s2));
4874           double m[3][3]={
4875             {vec2[0]*vec2[0]*(1-c2)+c2, vec2[0]*vec2[1]*(1-c2), vec2[1]*s2},
4876             {vec2[0]*vec2[1]*(1-c2), vec2[1]*vec2[1]*(1-c2)+c2, -vec2[0]*s2},
4877             {-vec2[1]*s2, vec2[0]*s2, c2}
4878           };
4879           double p0r[3]={m[0][0]*p0[0]+m[0][1]*p0[1]+m[0][2]*p0[2], m[1][0]*p0[0]+m[1][1]*p0[1]+m[1][2]*p0[2], m[2][0]*p0[0]+m[2][1]*p0[1]+m[2][2]*p0[2]};
4880           double p1r[3]={m[0][0]*p1[0]+m[0][1]*p1[1]+m[0][2]*p1[2], m[1][0]*p1[0]+m[1][1]*p1[1]+m[1][2]*p1[2], m[2][0]*p1[0]+m[2][1]*p1[1]+m[2][2]*p1[2]};
4881           double p2r[3]={m[0][0]*p2[0]+m[0][1]*p2[1]+m[0][2]*p2[2], m[1][0]*p2[0]+m[1][1]*p2[1]+m[1][2]*p2[2], m[2][0]*p2[0]+m[2][1]*p2[1]+m[2][2]*p2[2]};
4882           INTERP_KERNEL::EdgeArcCircle::GetArcOfCirclePassingThru(p0r,p1r,p2r,tmp3,radius,alpha,alpha0);
4883           double cosangle=i+1<nbOfLevsInVec?(p0r[0]-tmp3[0])*(p1r[0]-tmp3[0])+(p0r[1]-tmp3[1])*(p1r[1]-tmp3[1]):(p2r[0]-tmp3[0])*(p1r[0]-tmp3[0])+(p2r[1]-tmp3[1])*(p1r[1]-tmp3[1]);
4884           double angle=acos(cosangle/(radius*radius));
4885           tmp->rotate(end,vecPlane,angle);
4886         }
4887       retPtr=std::copy(tmp2->getConstPointer(),tmp2->getConstPointer()+tmp2->getNbOfElems(),retPtr);
4888     }
4889   return ret.retn();
4890 }
4891
4892 /*!
4893  * This method is private because not easy to use for end user. This method is const contrary to
4894  * MEDCouplingUMesh::buildExtrudedMesh method because this->_coords are expected to contain
4895  * the coords sorted slice by slice.
4896  * \param isQuad specifies presence of quadratic cells.
4897  */
4898 MEDCouplingUMesh *MEDCouplingUMesh::buildExtrudedMeshFromThisLowLev(int nbOfNodesOf1Lev, bool isQuad) const
4899 {
4900   int nbOf1DCells=getNumberOfNodes()/nbOfNodesOf1Lev-1;
4901   int nbOf2DCells=getNumberOfCells();
4902   int nbOf3DCells=nbOf2DCells*nbOf1DCells;
4903   MEDCouplingUMesh *ret=MEDCouplingUMesh::New("Extruded",getMeshDimension()+1);
4904   const int *conn=_nodal_connec->getConstPointer();
4905   const int *connI=_nodal_connec_index->getConstPointer();
4906   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConn=DataArrayInt::New();
4907   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConnI=DataArrayInt::New();
4908   newConnI->alloc(nbOf3DCells+1,1);
4909   int *newConnIPtr=newConnI->getPointer();
4910   *newConnIPtr++=0;
4911   std::vector<int> newc;
4912   for(int j=0;j<nbOf2DCells;j++)
4913     {
4914       AppendExtrudedCell(conn+connI[j],conn+connI[j+1],nbOfNodesOf1Lev,isQuad,newc);
4915       *newConnIPtr++=(int)newc.size();
4916     }
4917   newConn->alloc((int)(newc.size())*nbOf1DCells,1);
4918   int *newConnPtr=newConn->getPointer();
4919   int deltaPerLev=isQuad?2*nbOfNodesOf1Lev:nbOfNodesOf1Lev;
4920   newConnIPtr=newConnI->getPointer();
4921   for(int iz=0;iz<nbOf1DCells;iz++)
4922     {
4923       if(iz!=0)
4924         std::transform(newConnIPtr+1,newConnIPtr+1+nbOf2DCells,newConnIPtr+1+iz*nbOf2DCells,std::bind2nd(std::plus<int>(),newConnIPtr[iz*nbOf2DCells]));
4925       for(std::vector<int>::const_iterator iter=newc.begin();iter!=newc.end();iter++,newConnPtr++)
4926         {
4927           int icell=(int)(iter-newc.begin());
4928           if(std::find(newConnIPtr,newConnIPtr+nbOf2DCells,icell)==newConnIPtr+nbOf2DCells)
4929             {
4930               if(*iter!=-1)
4931                 *newConnPtr=(*iter)+iz*deltaPerLev;
4932               else
4933                 *newConnPtr=-1;
4934             }
4935           else
4936             *newConnPtr=(*iter);
4937         }
4938     }
4939   ret->setConnectivity(newConn,newConnI,true);
4940   ret->setCoords(getCoords());
4941   return ret;
4942 }
4943
4944 /*!
4945  * Checks if \a this mesh is constituted by only quadratic cells.
4946  *  \return bool - \c true if there are only quadratic cells in \a this mesh.
4947  *  \throw If the coordinates array is not set.
4948  *  \throw If the nodal connectivity of cells is not defined.
4949  */
4950 bool MEDCouplingUMesh::isFullyQuadratic() const
4951 {
4952   checkFullyDefined();
4953   bool ret=true;
4954   int nbOfCells=getNumberOfCells();
4955   for(int i=0;i<nbOfCells && ret;i++)
4956     {
4957       INTERP_KERNEL::NormalizedCellType type=getTypeOfCell(i);
4958       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(type);
4959       ret=cm.isQuadratic();
4960     }
4961   return ret;
4962 }
4963
4964 /*!
4965  * Checks if \a this mesh includes any quadratic cell.
4966  *  \return bool - \c true if there is at least one quadratic cells in \a this mesh.
4967  *  \throw If the coordinates array is not set.
4968  *  \throw If the nodal connectivity of cells is not defined.
4969  */
4970 bool MEDCouplingUMesh::isPresenceOfQuadratic() const
4971 {
4972   checkFullyDefined();
4973   bool ret=false;
4974   int nbOfCells=getNumberOfCells();
4975   for(int i=0;i<nbOfCells && !ret;i++)
4976     {
4977       INTERP_KERNEL::NormalizedCellType type=getTypeOfCell(i);
4978       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(type);
4979       ret=cm.isQuadratic();
4980     }
4981   return ret;
4982 }
4983
4984 /*!
4985  * Converts all quadratic cells to linear ones. If there are no quadratic cells in \a
4986  * this mesh, it remains unchanged.
4987  *  \throw If the coordinates array is not set.
4988  *  \throw If the nodal connectivity of cells is not defined.
4989  */
4990 void MEDCouplingUMesh::convertQuadraticCellsToLinear()
4991 {
4992   checkFullyDefined();
4993   int nbOfCells=getNumberOfCells();
4994   int delta=0;
4995   const int *iciptr=_nodal_connec_index->getConstPointer();
4996   for(int i=0;i<nbOfCells;i++)
4997     {
4998       INTERP_KERNEL::NormalizedCellType type=getTypeOfCell(i);
4999       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(type);
5000       if(cm.isQuadratic())
5001         {
5002           INTERP_KERNEL::NormalizedCellType typel=cm.getLinearType();
5003           const INTERP_KERNEL::CellModel& cml=INTERP_KERNEL::CellModel::GetCellModel(typel);
5004           if(!cml.isDynamic())
5005             delta+=cm.getNumberOfNodes()-cml.getNumberOfNodes();
5006           else
5007             delta+=(iciptr[i+1]-iciptr[i]-1)/2;
5008         }
5009     }
5010   if(delta==0)
5011     return ;
5012   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConn=DataArrayInt::New();
5013   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConnI=DataArrayInt::New();
5014   const int *icptr=_nodal_connec->getConstPointer();
5015   newConn->alloc(getMeshLength()-delta,1);
5016   newConnI->alloc(nbOfCells+1,1);
5017   int *ocptr=newConn->getPointer();
5018   int *ociptr=newConnI->getPointer();
5019   *ociptr=0;
5020   _types.clear();
5021   for(int i=0;i<nbOfCells;i++,ociptr++)
5022     {
5023       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)icptr[iciptr[i]];
5024       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(type);
5025       if(!cm.isQuadratic())
5026         {
5027           _types.insert(type);
5028           ocptr=std::copy(icptr+iciptr[i],icptr+iciptr[i+1],ocptr);
5029           ociptr[1]=ociptr[0]+iciptr[i+1]-iciptr[i];
5030         }
5031       else
5032         {
5033           INTERP_KERNEL::NormalizedCellType typel=cm.getLinearType();
5034           _types.insert(typel);
5035           const INTERP_KERNEL::CellModel& cml=INTERP_KERNEL::CellModel::GetCellModel(typel);
5036           int newNbOfNodes=cml.getNumberOfNodes();
5037           if(cml.isDynamic())
5038             newNbOfNodes=(iciptr[i+1]-iciptr[i]-1)/2;
5039           *ocptr++=(int)typel;
5040           ocptr=std::copy(icptr+iciptr[i]+1,icptr+iciptr[i]+newNbOfNodes+1,ocptr);
5041           ociptr[1]=ociptr[0]+newNbOfNodes+1;
5042         }
5043     }
5044   setConnectivity(newConn,newConnI,false);
5045 }
5046
5047 /*!
5048  * This method converts all linear cell in \a this to quadratic one.
5049  * Contrary to MEDCouplingUMesh::convertQuadraticCellsToLinear method, here it is needed to specify the target
5050  * type of cells expected. For example INTERP_KERNEL::NORM_TRI3 can be converted to INTERP_KERNEL::NORM_TRI6 if \a conversionType is equal to 0 (the default)
5051  * or to INTERP_KERNEL::NORM_TRI7 if \a conversionType is equal to 1. All non linear cells and polyhedron in \a this are let untouched.
5052  * Contrary to MEDCouplingUMesh::convertQuadraticCellsToLinear method, the coordinates in \a this can be become bigger. All created nodes will be put at the
5053  * end of the existing coordinates.
5054  * 
5055  * \param [in] conversionType specifies the type of conversion expected. Only 0 (default) and 1 are supported presently. 0 those that creates the 'most' simple
5056  *             corresponding quadratic cells. 1 is those creating the 'most' complex.
5057  * \return a newly created DataArrayInt instance that the caller should deal with containing cell ids of converted cells.
5058  * 
5059  * \throw if \a this is not fully defined. It throws too if \a conversionType is not in [0,1].
5060  *
5061  * \sa MEDCouplingUMesh::convertQuadraticCellsToLinear
5062  */
5063 DataArrayInt *MEDCouplingUMesh::convertLinearCellsToQuadratic(int conversionType)
5064 {
5065   DataArrayInt *conn=0,*connI=0;
5066   DataArrayDouble *coords=0;
5067   std::set<INTERP_KERNEL::NormalizedCellType> types;
5068   checkFullyDefined();
5069   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret,connSafe,connISafe;
5070   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> coordsSafe;
5071   int meshDim=getMeshDimension();
5072   switch(conversionType)
5073   {
5074     case 0:
5075       switch(meshDim)
5076       {
5077         case 1:
5078           ret=convertLinearCellsToQuadratic1D0(conn,connI,coords,types);
5079           connSafe=conn; connISafe=connI; coordsSafe=coords;
5080           break;
5081         case 2:
5082           ret=convertLinearCellsToQuadratic2D0(conn,connI,coords,types);
5083           connSafe=conn; connISafe=connI; coordsSafe=coords;
5084           break;
5085         case 3:
5086           ret=convertLinearCellsToQuadratic3D0(conn,connI,coords,types);
5087           connSafe=conn; connISafe=connI; coordsSafe=coords;
5088           break;
5089         default:
5090           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertLinearCellsToQuadratic : conversion of type 0 mesh dimensions available are [1,2,3] !");
5091       }
5092       break;
5093         case 1:
5094           {
5095             switch(meshDim)
5096             {
5097               case 1:
5098                 ret=convertLinearCellsToQuadratic1D0(conn,connI,coords,types);//it is not a bug. In 1D policy 0 and 1 are equals
5099                 connSafe=conn; connISafe=connI; coordsSafe=coords;
5100                 break;
5101               case 2:
5102                 ret=convertLinearCellsToQuadratic2D1(conn,connI,coords,types);
5103                 connSafe=conn; connISafe=connI; coordsSafe=coords;
5104                 break;
5105               case 3:
5106                 ret=convertLinearCellsToQuadratic3D1(conn,connI,coords,types);
5107                 connSafe=conn; connISafe=connI; coordsSafe=coords;
5108                 break;
5109               default:
5110                 throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertLinearCellsToQuadratic : conversion of type 1 mesh dimensions available are [1,2,3] !");
5111             }
5112             break;
5113           }
5114         default:
5115           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertLinearCellsToQuadratic : conversion type available are 0 (default, the simplest) and 1 (the most complex) !");
5116   }
5117   setConnectivity(connSafe,connISafe,false);
5118   _types=types;
5119   setCoords(coordsSafe);
5120   return ret.retn();
5121 }
5122
5123 #if 0
5124 /*!
5125  * This method only works if \a this has spaceDimension equal to 2 and meshDimension also equal to 2.
5126  * This method allows to modify connectivity of cells in \a this that shares some edges in \a edgeIdsToBeSplit.
5127  * The nodes to be added in those 2D cells are defined by the pair of \a  nodeIdsToAdd and \a nodeIdsIndexToAdd.
5128  * Length of \a nodeIdsIndexToAdd is expected to equal to length of \a edgeIdsToBeSplit + 1.
5129  * The node ids in \a nodeIdsToAdd should be valid. Those nodes have to be sorted exactly following exactly the direction of the edge.
5130  * This method can be seen as the opposite method of colinearize2D.
5131  * This method can be lead to create some new nodes if quadratic polygon cells have to be split. In this case the added nodes will be put at the end
5132  * to avoid to modify the numbering of existing nodes.
5133  *
5134  * \param [in] nodeIdsToAdd - the list of node ids to be added (\a nodeIdsIndexToAdd array allows to walk on this array)
5135  * \param [in] nodeIdsIndexToAdd - the entry point of \a nodeIdsToAdd to point to the corresponding nodes to be added.
5136  * \param [in] mesh1Desc - 1st output of buildDescendingConnectivity2 on \a this.
5137  * \param [in] desc - 2nd output of buildDescendingConnectivity2 on \a this.
5138  * \param [in] descI - 3rd output of buildDescendingConnectivity2 on \a this.
5139  * \param [in] revDesc - 4th output of buildDescendingConnectivity2 on \a this.
5140  * \param [in] revDescI - 5th output of buildDescendingConnectivity2 on \a this.
5141  *
5142  * \sa buildDescendingConnectivity2
5143  */
5144 void MEDCouplingUMesh::splitSomeEdgesOf2DMesh(const DataArrayInt *nodeIdsToAdd, const DataArrayInt *nodeIdsIndexToAdd, const DataArrayInt *edgeIdsToBeSplit,
5145                                               const MEDCouplingUMesh *mesh1Desc, const DataArrayInt *desc, const DataArrayInt *descI, const DataArrayInt *revDesc, const DataArrayInt *revDescI)
5146 {
5147   if(!nodeIdsToAdd || !nodeIdsIndexToAdd || !edgeIdsToBeSplit || !mesh1Desc || !desc || !descI || !revDesc || !revDescI)
5148     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::splitSomeEdgesOf2DMesh : input pointers must be not NULL !");
5149   nodeIdsToAdd->checkAllocated(); nodeIdsIndexToAdd->checkAllocated(); edgeIdsToBeSplit->checkAllocated(); desc->checkAllocated(); descI->checkAllocated(); revDesc->checkAllocated(); revDescI->checkAllocated();
5150   if(getSpaceDimension()!=2 || getMeshDimension()!=2)
5151     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::splitSomeEdgesOf2DMesh : this must have spacedim=meshdim=2 !");
5152   if(mesh1Desc->getSpaceDimension()!=2 || mesh1Desc->getMeshDimension()!=1)
5153     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::splitSomeEdgesOf2DMesh : mesh1Desc must be the explosion of this with spaceDim=2 and meshDim = 1 !");
5154   //DataArrayInt *out0(0),*outi0(0);
5155   //MEDCouplingUMesh::ExtractFromIndexedArrays(idsInDesc2DToBeRefined->begin(),idsInDesc2DToBeRefined->end(),dd3,dd4,out0,outi0);
5156   //MEDCouplingAutoRefCountObjectPtr<DataArrayInt> out0s(out0),outi0s(outi0);
5157   //out0s=out0s->buildUnique(); out0s->sort(true);
5158 }
5159 #endif
5160
5161 /*!
5162  * Implementes \a conversionType 0 for meshes with meshDim = 1, of MEDCouplingUMesh::convertLinearCellsToQuadratic method.
5163  * \return a newly created DataArrayInt instance that the caller should deal with containing cell ids of converted cells.
5164  * \sa MEDCouplingUMesh::convertLinearCellsToQuadratic.
5165  */
5166 DataArrayInt *MEDCouplingUMesh::convertLinearCellsToQuadratic1D0(DataArrayInt *&conn, DataArrayInt *&connI, DataArrayDouble *& coords, std::set<INTERP_KERNEL::NormalizedCellType>& types) const
5167 {
5168   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> bary=getBarycenterAndOwner();
5169   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConn=DataArrayInt::New(); newConn->alloc(0,1);
5170   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConnI=DataArrayInt::New(); newConnI->alloc(1,1); newConnI->setIJ(0,0,0);
5171   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New(); ret->alloc(0,1);
5172   int nbOfCells=getNumberOfCells();
5173   int nbOfNodes=getNumberOfNodes();
5174   const int *cPtr=_nodal_connec->getConstPointer();
5175   const int *icPtr=_nodal_connec_index->getConstPointer();
5176   int lastVal=0,offset=nbOfNodes;
5177   for(int i=0;i<nbOfCells;i++,icPtr++)
5178     {
5179       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)cPtr[*icPtr];
5180       if(type==INTERP_KERNEL::NORM_SEG2)
5181         {
5182           types.insert(INTERP_KERNEL::NORM_SEG3);
5183           newConn->pushBackSilent((int)INTERP_KERNEL::NORM_SEG3);
5184           newConn->pushBackValsSilent(cPtr+icPtr[0]+1,cPtr+icPtr[0]+3);
5185           newConn->pushBackSilent(offset++);
5186           lastVal+=4;
5187           newConnI->pushBackSilent(lastVal);
5188           ret->pushBackSilent(i);
5189         }
5190       else
5191         {
5192           types.insert(type);
5193           lastVal+=(icPtr[1]-icPtr[0]);
5194           newConnI->pushBackSilent(lastVal);
5195           newConn->pushBackValsSilent(cPtr+icPtr[0],cPtr+icPtr[1]);
5196         }
5197     }
5198   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> tmp=bary->selectByTupleIdSafe(ret->begin(),ret->end());
5199   coords=DataArrayDouble::Aggregate(getCoords(),tmp); conn=newConn.retn(); connI=newConnI.retn();
5200   return ret.retn();
5201 }
5202
5203 DataArrayInt *MEDCouplingUMesh::convertLinearCellsToQuadratic2DAnd3D0(const MEDCouplingUMesh *m1D, const DataArrayInt *desc, const DataArrayInt *descI, DataArrayInt *&conn, DataArrayInt *&connI, DataArrayDouble *& coords, std::set<INTERP_KERNEL::NormalizedCellType>& types) const
5204 {
5205   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConn=DataArrayInt::New(); newConn->alloc(0,1);
5206   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConnI=DataArrayInt::New(); newConnI->alloc(1,1); newConnI->setIJ(0,0,0);
5207   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New(); ret->alloc(0,1);
5208   //
5209   const int *descPtr(desc->begin()),*descIPtr(descI->begin());
5210   DataArrayInt *conn1D=0,*conn1DI=0;
5211   std::set<INTERP_KERNEL::NormalizedCellType> types1D;
5212   DataArrayDouble *coordsTmp=0;
5213   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret1D=m1D->convertLinearCellsToQuadratic1D0(conn1D,conn1DI,coordsTmp,types1D); ret1D=0;
5214   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> coordsTmpSafe(coordsTmp);
5215   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn1DSafe(conn1D),conn1DISafe(conn1DI);
5216   const int *c1DPtr=conn1D->begin();
5217   const int *c1DIPtr=conn1DI->begin();
5218   int nbOfCells=getNumberOfCells();
5219   const int *cPtr=_nodal_connec->getConstPointer();
5220   const int *icPtr=_nodal_connec_index->getConstPointer();
5221   int lastVal=0;
5222   for(int i=0;i<nbOfCells;i++,icPtr++,descIPtr++)
5223     {
5224       INTERP_KERNEL::NormalizedCellType typ=(INTERP_KERNEL::NormalizedCellType)cPtr[*icPtr];
5225       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(typ);
5226       if(!cm.isQuadratic())
5227         {
5228           INTERP_KERNEL::NormalizedCellType typ2=cm.getQuadraticType();
5229           types.insert(typ2); newConn->pushBackSilent(typ2);
5230           newConn->pushBackValsSilent(cPtr+icPtr[0]+1,cPtr+icPtr[1]);
5231           for(const int *d=descPtr+descIPtr[0];d!=descPtr+descIPtr[1];d++)
5232             newConn->pushBackSilent(c1DPtr[c1DIPtr[*d]+3]);
5233           lastVal+=(icPtr[1]-icPtr[0])+(descIPtr[1]-descIPtr[0]);
5234           newConnI->pushBackSilent(lastVal);
5235           ret->pushBackSilent(i);
5236         }
5237       else
5238         {
5239           types.insert(typ);
5240           lastVal+=(icPtr[1]-icPtr[0]);
5241           newConnI->pushBackSilent(lastVal);
5242           newConn->pushBackValsSilent(cPtr+icPtr[0],cPtr+icPtr[1]);
5243         }
5244     }
5245   conn=newConn.retn(); connI=newConnI.retn(); coords=coordsTmpSafe.retn();
5246   return ret.retn();
5247 }
5248
5249 /*!
5250  * Implementes \a conversionType 0 for meshes with meshDim = 2, of MEDCouplingUMesh::convertLinearCellsToQuadratic method.
5251  * \return a newly created DataArrayInt instance that the caller should deal with containing cell ids of converted cells.
5252  * \sa MEDCouplingUMesh::convertLinearCellsToQuadratic.
5253  */
5254 DataArrayInt *MEDCouplingUMesh::convertLinearCellsToQuadratic2D0(DataArrayInt *&conn, DataArrayInt *&connI, DataArrayDouble *& coords, std::set<INTERP_KERNEL::NormalizedCellType>& types) const
5255 {
5256   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> desc(DataArrayInt::New()),descI(DataArrayInt::New()),tmp2(DataArrayInt::New()),tmp3(DataArrayInt::New());
5257   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m1D=buildDescendingConnectivity(desc,descI,tmp2,tmp3); tmp2=0; tmp3=0;
5258   return convertLinearCellsToQuadratic2DAnd3D0(m1D,desc,descI,conn,connI,coords,types);
5259 }
5260
5261 DataArrayInt *MEDCouplingUMesh::convertLinearCellsToQuadratic2D1(DataArrayInt *&conn, DataArrayInt *&connI, DataArrayDouble *& coords, std::set<INTERP_KERNEL::NormalizedCellType>& types) const
5262 {
5263   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> desc(DataArrayInt::New()),descI(DataArrayInt::New()),tmp2(DataArrayInt::New()),tmp3(DataArrayInt::New());
5264   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m1D=buildDescendingConnectivity(desc,descI,tmp2,tmp3); tmp2=0; tmp3=0;
5265   //
5266   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConn=DataArrayInt::New(); newConn->alloc(0,1);
5267   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConnI=DataArrayInt::New(); newConnI->alloc(1,1); newConnI->setIJ(0,0,0);
5268   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New(); ret->alloc(0,1);
5269   //
5270   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> bary=getBarycenterAndOwner();
5271   const int *descPtr(desc->begin()),*descIPtr(descI->begin());
5272   DataArrayInt *conn1D=0,*conn1DI=0;
5273   std::set<INTERP_KERNEL::NormalizedCellType> types1D;
5274   DataArrayDouble *coordsTmp=0;
5275   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret1D=m1D->convertLinearCellsToQuadratic1D0(conn1D,conn1DI,coordsTmp,types1D); ret1D=0;
5276   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> coordsTmpSafe(coordsTmp);
5277   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn1DSafe(conn1D),conn1DISafe(conn1DI);
5278   const int *c1DPtr=conn1D->begin();
5279   const int *c1DIPtr=conn1DI->begin();
5280   int nbOfCells=getNumberOfCells();
5281   const int *cPtr=_nodal_connec->getConstPointer();
5282   const int *icPtr=_nodal_connec_index->getConstPointer();
5283   int lastVal=0,offset=coordsTmpSafe->getNumberOfTuples();
5284   for(int i=0;i<nbOfCells;i++,icPtr++,descIPtr++)
5285     {
5286       INTERP_KERNEL::NormalizedCellType typ=(INTERP_KERNEL::NormalizedCellType)cPtr[*icPtr];
5287       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(typ);
5288       if(!cm.isQuadratic())
5289         {
5290           INTERP_KERNEL::NormalizedCellType typ2=cm.getQuadraticType2();
5291           types.insert(typ2); newConn->pushBackSilent(typ2);
5292           newConn->pushBackValsSilent(cPtr+icPtr[0]+1,cPtr+icPtr[1]);
5293           for(const int *d=descPtr+descIPtr[0];d!=descPtr+descIPtr[1];d++)
5294             newConn->pushBackSilent(c1DPtr[c1DIPtr[*d]+3]);
5295           newConn->pushBackSilent(offset+ret->getNumberOfTuples());
5296           lastVal+=(icPtr[1]-icPtr[0])+(descIPtr[1]-descIPtr[0])+1;
5297           newConnI->pushBackSilent(lastVal);
5298           ret->pushBackSilent(i);
5299         }
5300       else
5301         {
5302           types.insert(typ);
5303           lastVal+=(icPtr[1]-icPtr[0]);
5304           newConnI->pushBackSilent(lastVal);
5305           newConn->pushBackValsSilent(cPtr+icPtr[0],cPtr+icPtr[1]);
5306         }
5307     }
5308   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> tmp=bary->selectByTupleIdSafe(ret->begin(),ret->end());
5309   coords=DataArrayDouble::Aggregate(coordsTmpSafe,tmp); conn=newConn.retn(); connI=newConnI.retn();
5310   return ret.retn();
5311 }
5312
5313 /*!
5314  * Implementes \a conversionType 0 for meshes with meshDim = 3, of MEDCouplingUMesh::convertLinearCellsToQuadratic method.
5315  * \return a newly created DataArrayInt instance that the caller should deal with containing cell ids of converted cells.
5316  * \sa MEDCouplingUMesh::convertLinearCellsToQuadratic.
5317  */
5318 DataArrayInt *MEDCouplingUMesh::convertLinearCellsToQuadratic3D0(DataArrayInt *&conn, DataArrayInt *&connI, DataArrayDouble *& coords, std::set<INTERP_KERNEL::NormalizedCellType>& types) const
5319 {
5320   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> desc(DataArrayInt::New()),descI(DataArrayInt::New()),tmp2(DataArrayInt::New()),tmp3(DataArrayInt::New());
5321   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m1D=explode3DMeshTo1D(desc,descI,tmp2,tmp3); tmp2=0; tmp3=0;
5322   return convertLinearCellsToQuadratic2DAnd3D0(m1D,desc,descI,conn,connI,coords,types);
5323 }
5324
5325 DataArrayInt *MEDCouplingUMesh::convertLinearCellsToQuadratic3D1(DataArrayInt *&conn, DataArrayInt *&connI, DataArrayDouble *& coords, std::set<INTERP_KERNEL::NormalizedCellType>& types) const
5326 {
5327   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> desc2(DataArrayInt::New()),desc2I(DataArrayInt::New()),tmp2(DataArrayInt::New()),tmp3(DataArrayInt::New());
5328   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m2D=buildDescendingConnectivityGen<MinusOneSonsGeneratorBiQuadratic>(desc2,desc2I,tmp2,tmp3,MEDCouplingFastNbrer); tmp2=0; tmp3=0;
5329   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> desc1(DataArrayInt::New()),desc1I(DataArrayInt::New()),tmp4(DataArrayInt::New()),tmp5(DataArrayInt::New());
5330   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m1D=explode3DMeshTo1D(desc1,desc1I,tmp4,tmp5); tmp4=0; tmp5=0;
5331   //
5332   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConn=DataArrayInt::New(); newConn->alloc(0,1);
5333   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConnI=DataArrayInt::New(); newConnI->alloc(1,1); newConnI->setIJ(0,0,0);
5334   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New(),ret2=DataArrayInt::New(); ret->alloc(0,1); ret2->alloc(0,1);
5335   //
5336   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> bary=getBarycenterAndOwner();
5337   const int *descPtr(desc1->begin()),*descIPtr(desc1I->begin()),*desc2Ptr(desc2->begin()),*desc2IPtr(desc2I->begin());
5338   DataArrayInt *conn1D=0,*conn1DI=0,*conn2D=0,*conn2DI=0;
5339   std::set<INTERP_KERNEL::NormalizedCellType> types1D,types2D;
5340   DataArrayDouble *coordsTmp=0,*coordsTmp2=0;
5341   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret1D=m1D->convertLinearCellsToQuadratic1D0(conn1D,conn1DI,coordsTmp,types1D); ret1D=DataArrayInt::New(); ret1D->alloc(0,1);
5342   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn1DSafe(conn1D),conn1DISafe(conn1DI);
5343   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> coordsTmpSafe(coordsTmp);
5344   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret2D=m2D->convertLinearCellsToQuadratic2D1(conn2D,conn2DI,coordsTmp2,types2D); ret2D=DataArrayInt::New(); ret2D->alloc(0,1);
5345   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> coordsTmp2Safe(coordsTmp2);
5346   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn2DSafe(conn2D),conn2DISafe(conn2DI);
5347   const int *c1DPtr=conn1D->begin(),*c1DIPtr=conn1DI->begin(),*c2DPtr=conn2D->begin(),*c2DIPtr=conn2DI->begin();
5348   int nbOfCells=getNumberOfCells();
5349   const int *cPtr=_nodal_connec->getConstPointer();
5350   const int *icPtr=_nodal_connec_index->getConstPointer();
5351   int lastVal=0,offset=coordsTmpSafe->getNumberOfTuples();
5352   for(int i=0;i<nbOfCells;i++,icPtr++,descIPtr++,desc2IPtr++)
5353     {
5354       INTERP_KERNEL::NormalizedCellType typ=(INTERP_KERNEL::NormalizedCellType)cPtr[*icPtr];
5355       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(typ);
5356       if(!cm.isQuadratic())
5357         {
5358           INTERP_KERNEL::NormalizedCellType typ2=cm.getQuadraticType2();
5359           if(typ2==INTERP_KERNEL::NORM_ERROR)
5360             {
5361               std::ostringstream oss; oss << "MEDCouplingUMesh::convertLinearCellsToQuadratic3D1 : On cell #" << i << " the linear cell type does not support advanced quadratization !";
5362               throw INTERP_KERNEL::Exception(oss.str().c_str());
5363             }
5364           types.insert(typ2); newConn->pushBackSilent(typ2);
5365           newConn->pushBackValsSilent(cPtr+icPtr[0]+1,cPtr+icPtr[1]);
5366           for(const int *d=descPtr+descIPtr[0];d!=descPtr+descIPtr[1];d++)
5367             newConn->pushBackSilent(c1DPtr[c1DIPtr[*d]+3]);
5368           for(const int *d=desc2Ptr+desc2IPtr[0];d!=desc2Ptr+desc2IPtr[1];d++)
5369             {
5370               int nodeId2=c2DPtr[c2DIPtr[(*d)+1]-1];
5371               int tmpPos=newConn->getNumberOfTuples();
5372               newConn->pushBackSilent(nodeId2);
5373               ret2D->pushBackSilent(nodeId2); ret1D->pushBackSilent(tmpPos);
5374             }
5375           newConn->pushBackSilent(offset+ret->getNumberOfTuples());
5376           lastVal+=(icPtr[1]-icPtr[0])+(descIPtr[1]-descIPtr[0])+(desc2IPtr[1]-desc2IPtr[0])+1;
5377           newConnI->pushBackSilent(lastVal);
5378           ret->pushBackSilent(i);
5379         }
5380       else
5381         {
5382           types.insert(typ);
5383           lastVal+=(icPtr[1]-icPtr[0]);
5384           newConnI->pushBackSilent(lastVal);
5385           newConn->pushBackValsSilent(cPtr+icPtr[0],cPtr+icPtr[1]);
5386         }
5387     }
5388   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> diffRet2D=ret2D->getDifferentValues();
5389   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> o2nRet2D=diffRet2D->invertArrayN2O2O2N(coordsTmp2Safe->getNumberOfTuples());
5390   coordsTmp2Safe=coordsTmp2Safe->selectByTupleId(diffRet2D->begin(),diffRet2D->end());
5391   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> tmp=bary->selectByTupleIdSafe(ret->begin(),ret->end());
5392   std::vector<const DataArrayDouble *> v(3); v[0]=coordsTmpSafe; v[1]=coordsTmp2Safe; v[2]=tmp;
5393   int *c=newConn->getPointer();
5394   const int *cI(newConnI->begin());
5395   for(const int *elt=ret1D->begin();elt!=ret1D->end();elt++)
5396     c[*elt]=o2nRet2D->getIJ(c[*elt],0)+offset;
5397   offset=coordsTmp2Safe->getNumberOfTuples();
5398   for(const int *elt=ret->begin();elt!=ret->end();elt++)
5399     c[cI[(*elt)+1]-1]+=offset;
5400   coords=DataArrayDouble::Aggregate(v); conn=newConn.retn(); connI=newConnI.retn();
5401   return ret.retn();
5402 }
5403
5404 /*!
5405  * Tessellates \a this 2D mesh by dividing not straight edges of quadratic faces,
5406  * so that the number of cells remains the same. Quadratic faces are converted to
5407  * polygons. This method works only for 2D meshes in
5408  * 2D space. If no cells are quadratic (INTERP_KERNEL::NORM_QUAD8,
5409  * INTERP_KERNEL::NORM_TRI6, INTERP_KERNEL::NORM_QPOLYG ), \a this mesh remains unchanged.
5410  * \warning This method can lead to a huge amount of nodes if \a eps is very low.
5411  *  \param [in] eps - specifies the maximal angle (in radians) between 2 sub-edges of
5412  *         a polylinized edge constituting the input polygon.
5413  *  \throw If the coordinates array is not set.
5414  *  \throw If the nodal connectivity of cells is not defined.
5415  *  \throw If \a this->getMeshDimension() != 2.
5416  *  \throw If \a this->getSpaceDimension() != 2.
5417  */
5418 void MEDCouplingUMesh::tessellate2D(double eps)
5419 {
5420   checkFullyDefined();
5421   if(getMeshDimension()!=2 || getSpaceDimension()!=2)  
5422     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::tessellate2D works on umeshes with meshdim equal to 2 and spaceDim equal to 2 too!");
5423   double epsa=fabs(eps);
5424   if(epsa<std::numeric_limits<double>::min())
5425     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::tessellate2DCurve : epsilon is null ! Please specify a higher epsilon. If too tiny it can lead to a huge amount of nodes and memory !");
5426   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> desc1=DataArrayInt::New();
5427   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> descIndx1=DataArrayInt::New();
5428   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revDesc1=DataArrayInt::New();
5429   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revDescIndx1=DataArrayInt::New();
5430   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> mDesc=buildDescendingConnectivity2(desc1,descIndx1,revDesc1,revDescIndx1);
5431   revDesc1=0; revDescIndx1=0;
5432   mDesc->tessellate2DCurve(eps);
5433   subDivide2DMesh(mDesc->_nodal_connec->getConstPointer(),mDesc->_nodal_connec_index->getConstPointer(),desc1->getConstPointer(),descIndx1->getConstPointer());
5434   setCoords(mDesc->getCoords());
5435 }
5436
5437 /*!
5438  * Tessellates \a this 1D mesh in 2D space by dividing not straight quadratic edges.
5439  * \warning This method can lead to a huge amount of nodes if \a eps is very low.
5440  *  \param [in] eps - specifies the maximal angle (in radian) between 2 sub-edges of
5441  *         a sub-divided edge.
5442  *  \throw If the coordinates array is not set.
5443  *  \throw If the nodal connectivity of cells is not defined.
5444  *  \throw If \a this->getMeshDimension() != 1.
5445  *  \throw If \a this->getSpaceDimension() != 2.
5446  */
5447 void MEDCouplingUMesh::tessellate2DCurve(double eps)
5448 {
5449   checkFullyDefined();
5450   if(getMeshDimension()!=1 || getSpaceDimension()!=2)
5451     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::tessellate2DCurve works on umeshes with meshdim equal to 1 and spaceDim equal to 2 too!");
5452   double epsa=fabs(eps);
5453   if(epsa<std::numeric_limits<double>::min())
5454     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::tessellate2DCurve : epsilon is null ! Please specify a higher epsilon. If too tiny it can lead to a huge amount of nodes and memory !");
5455   INTERP_KERNEL::QUADRATIC_PLANAR::_arc_detection_precision=1.e-10;
5456   int nbCells=getNumberOfCells();
5457   int nbNodes=getNumberOfNodes();
5458   const int *conn=_nodal_connec->getConstPointer();
5459   const int *connI=_nodal_connec_index->getConstPointer();
5460   const double *coords=_coords->getConstPointer();
5461   std::vector<double> addCoo;
5462   std::vector<int> newConn;//no direct DataArrayInt because interface with Geometric2D
5463   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConnI(DataArrayInt::New());
5464   newConnI->alloc(nbCells+1,1);
5465   int *newConnIPtr=newConnI->getPointer();
5466   *newConnIPtr=0;
5467   int tmp1[3];
5468   INTERP_KERNEL::Node *tmp2[3];
5469   std::set<INTERP_KERNEL::NormalizedCellType> types;
5470   for(int i=0;i<nbCells;i++,newConnIPtr++)
5471     {
5472       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[connI[i]]);
5473       if(cm.isQuadratic())
5474         {//assert(connI[i+1]-connI[i]-1==3)
5475           tmp1[0]=conn[connI[i]+1+0]; tmp1[1]=conn[connI[i]+1+1]; tmp1[2]=conn[connI[i]+1+2];
5476           tmp2[0]=new INTERP_KERNEL::Node(coords[2*tmp1[0]],coords[2*tmp1[0]+1]);
5477           tmp2[1]=new INTERP_KERNEL::Node(coords[2*tmp1[1]],coords[2*tmp1[1]+1]);
5478           tmp2[2]=new INTERP_KERNEL::Node(coords[2*tmp1[2]],coords[2*tmp1[2]+1]);
5479           INTERP_KERNEL::EdgeArcCircle *eac=INTERP_KERNEL::EdgeArcCircle::BuildFromNodes(tmp2[0],tmp2[2],tmp2[1]);
5480           if(eac)
5481             {
5482               eac->tesselate(tmp1,nbNodes,epsa,newConn,addCoo);
5483               types.insert((INTERP_KERNEL::NormalizedCellType)newConn[newConnIPtr[0]]);
5484               delete eac;
5485               newConnIPtr[1]=(int)newConn.size();
5486             }
5487           else
5488             {
5489               types.insert(INTERP_KERNEL::NORM_SEG2);
5490               newConn.push_back(INTERP_KERNEL::NORM_SEG2);
5491               newConn.insert(newConn.end(),conn+connI[i]+1,conn+connI[i]+3);
5492               newConnIPtr[1]=newConnIPtr[0]+3;
5493             }
5494         }
5495       else
5496         {
5497           types.insert((INTERP_KERNEL::NormalizedCellType)conn[connI[i]]);
5498           newConn.insert(newConn.end(),conn+connI[i],conn+connI[i+1]);
5499           newConnIPtr[1]=newConnIPtr[0]+3;
5500         }
5501     }
5502   if(addCoo.empty() && ((int)newConn.size())==_nodal_connec->getNumberOfTuples())//nothing happens during tessellation : no update needed
5503     return ;
5504   _types=types;
5505   DataArrayInt::SetArrayIn(newConnI,_nodal_connec_index);
5506   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConnArr=DataArrayInt::New();
5507   newConnArr->alloc((int)newConn.size(),1);
5508   std::copy(newConn.begin(),newConn.end(),newConnArr->getPointer());
5509   DataArrayInt::SetArrayIn(newConnArr,_nodal_connec);
5510   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> newCoords=DataArrayDouble::New();
5511   newCoords->alloc(nbNodes+((int)addCoo.size())/2,2);
5512   double *work=std::copy(_coords->begin(),_coords->end(),newCoords->getPointer());
5513   std::copy(addCoo.begin(),addCoo.end(),work);
5514   DataArrayDouble::SetArrayIn(newCoords,_coords);
5515   updateTime();
5516 }
5517
5518 /*!
5519  * Divides every cell of \a this mesh into simplices (triangles in 2D and tetrahedra in 3D).
5520  * In addition, returns an array mapping new cells to old ones. <br>
5521  * This method typically increases the number of cells in \a this mesh
5522  * but the number of nodes remains \b unchanged.
5523  * That's why the 3D splitting policies
5524  * INTERP_KERNEL::GENERAL_24 and INTERP_KERNEL::GENERAL_48 are not available here.
5525  *  \param [in] policy - specifies a pattern used for splitting.
5526  * The semantic of \a policy is:
5527  * - 0 - to split QUAD4 by cutting it along 0-2 diagonal (for 2D mesh only).
5528  * - 1 - to split QUAD4 by cutting it along 1-3 diagonal (for 2D mesh only).
5529  * - INTERP_KERNEL::PLANAR_FACE_5 - to split HEXA8  into 5 TETRA4 (for 3D mesh only).
5530  * - INTERP_KERNEL::PLANAR_FACE_6 - to split HEXA8  into 6 TETRA4 (for 3D mesh only).
5531  *  \return DataArrayInt * - a new instance of DataArrayInt holding, for each new cell,
5532  *          an id of old cell producing it. The caller is to delete this array using
5533  *         decrRef() as it is no more needed. 
5534  *  \throw If \a policy is 0 or 1 and \a this->getMeshDimension() != 2.
5535  *  \throw If \a policy is INTERP_KERNEL::PLANAR_FACE_5 or INTERP_KERNEL::PLANAR_FACE_6
5536  *          and \a this->getMeshDimension() != 3. 
5537  *  \throw If \a policy is not one of the four discussed above.
5538  *  \throw If the nodal connectivity of cells is not defined.
5539  * \sa MEDCouplingUMesh::tetrahedrize, MEDCoupling1SGTUMesh::sortHexa8EachOther
5540  */
5541 DataArrayInt *MEDCouplingUMesh::simplexize(int policy)
5542 {
5543   switch(policy)
5544   {
5545     case 0:
5546       return simplexizePol0();
5547     case 1:
5548       return simplexizePol1();
5549     case (int) INTERP_KERNEL::PLANAR_FACE_5:
5550         return simplexizePlanarFace5();
5551     case (int) INTERP_KERNEL::PLANAR_FACE_6:
5552         return simplexizePlanarFace6();
5553     default:
5554       throw INTERP_KERNEL::Exception("MEDCouplingUMesh::simplexize : unrecognized policy ! Must be :\n  - 0 or 1 (only available for meshdim=2) \n  - PLANAR_FACE_5, PLANAR_FACE_6  (only for meshdim=3)");
5555   }
5556 }
5557
5558 /*!
5559  * Checks if \a this mesh is constituted by simplex cells only. Simplex cells are:
5560  * - 1D: INTERP_KERNEL::NORM_SEG2
5561  * - 2D: INTERP_KERNEL::NORM_TRI3
5562  * - 3D: INTERP_KERNEL::NORM_TETRA4.
5563  *
5564  * This method is useful for users that need to use P1 field services as
5565  * MEDCouplingFieldDouble::getValueOn(), MEDCouplingField::buildMeasureField() etc.
5566  * All these methods need mesh support containing only simplex cells.
5567  *  \return bool - \c true if there are only simplex cells in \a this mesh.
5568  *  \throw If the coordinates array is not set.
5569  *  \throw If the nodal connectivity of cells is not defined.
5570  *  \throw If \a this->getMeshDimension() < 1.
5571  */
5572 bool MEDCouplingUMesh::areOnlySimplexCells() const
5573 {
5574   checkFullyDefined();
5575   int mdim=getMeshDimension();
5576   if(mdim<1 || mdim>3)
5577     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::areOnlySimplexCells : only available with meshes having a meshdim 1, 2 or 3 !");
5578   int nbCells=getNumberOfCells();
5579   const int *conn=_nodal_connec->getConstPointer();
5580   const int *connI=_nodal_connec_index->getConstPointer();
5581   for(int i=0;i<nbCells;i++)
5582     {
5583       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[connI[i]]);
5584       if(!cm.isSimplex())
5585         return false;
5586     }
5587   return true;
5588 }
5589
5590 /*!
5591  * This method implements policy 0 of virtual method ParaMEDMEM::MEDCouplingUMesh::simplexize.
5592  */
5593 DataArrayInt *MEDCouplingUMesh::simplexizePol0()
5594 {
5595   checkConnectivityFullyDefined();
5596   if(getMeshDimension()!=2)
5597     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::simplexizePol0 : this policy is only available for mesh with meshdim == 2 !");
5598   int nbOfCells=getNumberOfCells();
5599   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New();
5600   int nbOfCutCells=getNumberOfCellsWithType(INTERP_KERNEL::NORM_QUAD4);
5601   ret->alloc(nbOfCells+nbOfCutCells,1);
5602   if(nbOfCutCells==0) { ret->iota(0); return ret.retn(); }
5603   int *retPt=ret->getPointer();
5604   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConn=DataArrayInt::New();
5605   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConnI=DataArrayInt::New();
5606   newConnI->alloc(nbOfCells+nbOfCutCells+1,1);
5607   newConn->alloc(getMeshLength()+3*nbOfCutCells,1);
5608   int *pt=newConn->getPointer();
5609   int *ptI=newConnI->getPointer();
5610   ptI[0]=0;
5611   const int *oldc=_nodal_connec->getConstPointer();
5612   const int *ci=_nodal_connec_index->getConstPointer();
5613   for(int i=0;i<nbOfCells;i++,ci++)
5614     {
5615       if((INTERP_KERNEL::NormalizedCellType)oldc[ci[0]]==INTERP_KERNEL::NORM_QUAD4)
5616         {
5617           const int tmp[8]={(int)INTERP_KERNEL::NORM_TRI3,oldc[ci[0]+1],oldc[ci[0]+2],oldc[ci[0]+3],
5618             (int)INTERP_KERNEL::NORM_TRI3,oldc[ci[0]+1],oldc[ci[0]+3],oldc[ci[0]+4]};
5619           pt=std::copy(tmp,tmp+8,pt);
5620           ptI[1]=ptI[0]+4;
5621           ptI[2]=ptI[0]+8;
5622           *retPt++=i;
5623           *retPt++=i;
5624           ptI+=2;
5625         }
5626       else
5627         {
5628           pt=std::copy(oldc+ci[0],oldc+ci[1],pt);
5629           ptI[1]=ptI[0]+ci[1]-ci[0];
5630           ptI++;
5631           *retPt++=i;
5632         }
5633     }
5634   _nodal_connec->decrRef();
5635   _nodal_connec=newConn.retn();
5636   _nodal_connec_index->decrRef();
5637   _nodal_connec_index=newConnI.retn();
5638   computeTypes();
5639   updateTime();
5640   return ret.retn();
5641 }
5642
5643 /*!
5644  * This method implements policy 1 of virtual method ParaMEDMEM::MEDCouplingUMesh::simplexize.
5645  */
5646 DataArrayInt *MEDCouplingUMesh::simplexizePol1()
5647 {
5648   checkConnectivityFullyDefined();
5649   if(getMeshDimension()!=2)
5650     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::simplexizePol0 : this policy is only available for mesh with meshdim == 2 !");
5651   int nbOfCells=getNumberOfCells();
5652   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New();
5653   int nbOfCutCells=getNumberOfCellsWithType(INTERP_KERNEL::NORM_QUAD4);
5654   ret->alloc(nbOfCells+nbOfCutCells,1);
5655   if(nbOfCutCells==0) { ret->iota(0); return ret.retn(); }
5656   int *retPt=ret->getPointer();
5657   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConn=DataArrayInt::New();
5658   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConnI=DataArrayInt::New();
5659   newConnI->alloc(nbOfCells+nbOfCutCells+1,1);
5660   newConn->alloc(getMeshLength()+3*nbOfCutCells,1);
5661   int *pt=newConn->getPointer();
5662   int *ptI=newConnI->getPointer();
5663   ptI[0]=0;
5664   const int *oldc=_nodal_connec->getConstPointer();
5665   const int *ci=_nodal_connec_index->getConstPointer();
5666   for(int i=0;i<nbOfCells;i++,ci++)
5667     {
5668       if((INTERP_KERNEL::NormalizedCellType)oldc[ci[0]]==INTERP_KERNEL::NORM_QUAD4)
5669         {
5670           const int tmp[8]={(int)INTERP_KERNEL::NORM_TRI3,oldc[ci[0]+1],oldc[ci[0]+2],oldc[ci[0]+4],
5671             (int)INTERP_KERNEL::NORM_TRI3,oldc[ci[0]+2],oldc[ci[0]+3],oldc[ci[0]+4]};
5672           pt=std::copy(tmp,tmp+8,pt);
5673           ptI[1]=ptI[0]+4;
5674           ptI[2]=ptI[0]+8;
5675           *retPt++=i;
5676           *retPt++=i;
5677           ptI+=2;
5678         }
5679       else
5680         {
5681           pt=std::copy(oldc+ci[0],oldc+ci[1],pt);
5682           ptI[1]=ptI[0]+ci[1]-ci[0];
5683           ptI++;
5684           *retPt++=i;
5685         }
5686     }
5687   _nodal_connec->decrRef();
5688   _nodal_connec=newConn.retn();
5689   _nodal_connec_index->decrRef();
5690   _nodal_connec_index=newConnI.retn();
5691   computeTypes();
5692   updateTime();
5693   return ret.retn();
5694 }
5695
5696 /*!
5697  * This method implements policy INTERP_KERNEL::PLANAR_FACE_5 of virtual method ParaMEDMEM::MEDCouplingUMesh::simplexize.
5698  */
5699 DataArrayInt *MEDCouplingUMesh::simplexizePlanarFace5()
5700 {
5701   checkConnectivityFullyDefined();
5702   if(getMeshDimension()!=3)
5703     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::simplexizePlanarFace5 : this policy is only available for mesh with meshdim == 3 !");
5704   int nbOfCells=getNumberOfCells();
5705   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New();
5706   int nbOfCutCells=getNumberOfCellsWithType(INTERP_KERNEL::NORM_HEXA8);
5707   ret->alloc(nbOfCells+4*nbOfCutCells,1);
5708   if(nbOfCutCells==0) { ret->iota(0); return ret.retn(); }
5709   int *retPt=ret->getPointer();
5710   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConn=DataArrayInt::New();
5711   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConnI=DataArrayInt::New();
5712   newConnI->alloc(nbOfCells+4*nbOfCutCells+1,1);
5713   newConn->alloc(getMeshLength()+16*nbOfCutCells,1);//21
5714   int *pt=newConn->getPointer();
5715   int *ptI=newConnI->getPointer();
5716   ptI[0]=0;
5717   const int *oldc=_nodal_connec->getConstPointer();
5718   const int *ci=_nodal_connec_index->getConstPointer();
5719   for(int i=0;i<nbOfCells;i++,ci++)
5720     {
5721       if((INTERP_KERNEL::NormalizedCellType)oldc[ci[0]]==INTERP_KERNEL::NORM_HEXA8)
5722         {
5723           for(int j=0;j<5;j++,pt+=5,ptI++)
5724             {
5725               pt[0]=(int)INTERP_KERNEL::NORM_TETRA4;
5726               pt[1]=oldc[ci[0]+INTERP_KERNEL::SPLIT_NODES_5_WO[4*j+0]+1]; pt[2]=oldc[ci[0]+INTERP_KERNEL::SPLIT_NODES_5_WO[4*j+1]+1]; pt[3]=oldc[ci[0]+INTERP_KERNEL::SPLIT_NODES_5_WO[4*j+2]+1]; pt[4]=oldc[ci[0]+INTERP_KERNEL::SPLIT_NODES_5_WO[4*j+3]+1];
5727               *retPt++=i;
5728               ptI[1]=ptI[0]+5;
5729             }
5730         }
5731       else
5732         {
5733           pt=std::copy(oldc+ci[0],oldc+ci[1],pt);
5734           ptI[1]=ptI[0]+ci[1]-ci[0];
5735           ptI++;
5736           *retPt++=i;
5737         }
5738     }
5739   _nodal_connec->decrRef();
5740   _nodal_connec=newConn.retn();
5741   _nodal_connec_index->decrRef();
5742   _nodal_connec_index=newConnI.retn();
5743   computeTypes();
5744   updateTime();
5745   return ret.retn();
5746 }
5747
5748 /*!
5749  * This method implements policy INTERP_KERNEL::PLANAR_FACE_6 of virtual method ParaMEDMEM::MEDCouplingUMesh::simplexize.
5750  */
5751 DataArrayInt *MEDCouplingUMesh::simplexizePlanarFace6()
5752 {
5753   checkConnectivityFullyDefined();
5754   if(getMeshDimension()!=3)
5755     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::simplexizePlanarFace6 : this policy is only available for mesh with meshdim == 3 !");
5756   int nbOfCells=getNumberOfCells();
5757   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New();
5758   int nbOfCutCells=getNumberOfCellsWithType(INTERP_KERNEL::NORM_HEXA8);
5759   ret->alloc(nbOfCells+5*nbOfCutCells,1);
5760   if(nbOfCutCells==0) { ret->iota(0); return ret.retn(); }
5761   int *retPt=ret->getPointer();
5762   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConn=DataArrayInt::New();
5763   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConnI=DataArrayInt::New();
5764   newConnI->alloc(nbOfCells+5*nbOfCutCells+1,1);
5765   newConn->alloc(getMeshLength()+21*nbOfCutCells,1);
5766   int *pt=newConn->getPointer();
5767   int *ptI=newConnI->getPointer();
5768   ptI[0]=0;
5769   const int *oldc=_nodal_connec->getConstPointer();
5770   const int *ci=_nodal_connec_index->getConstPointer();
5771   for(int i=0;i<nbOfCells;i++,ci++)
5772     {
5773       if((INTERP_KERNEL::NormalizedCellType)oldc[ci[0]]==INTERP_KERNEL::NORM_HEXA8)
5774         {
5775           for(int j=0;j<6;j++,pt+=5,ptI++)
5776             {
5777               pt[0]=(int)INTERP_KERNEL::NORM_TETRA4;
5778               pt[1]=oldc[ci[0]+INTERP_KERNEL::SPLIT_NODES_6_WO[4*j+0]+1]; pt[2]=oldc[ci[0]+INTERP_KERNEL::SPLIT_NODES_6_WO[4*j+1]+1]; pt[3]=oldc[ci[0]+INTERP_KERNEL::SPLIT_NODES_6_WO[4*j+2]+1]; pt[4]=oldc[ci[0]+INTERP_KERNEL::SPLIT_NODES_6_WO[4*j+3]+1];
5779               *retPt++=i;
5780               ptI[1]=ptI[0]+5;
5781             }
5782         }
5783       else
5784         {
5785           pt=std::copy(oldc+ci[0],oldc+ci[1],pt);
5786           ptI[1]=ptI[0]+ci[1]-ci[0];
5787           ptI++;
5788           *retPt++=i;
5789         }
5790     }
5791   _nodal_connec->decrRef();
5792   _nodal_connec=newConn.retn();
5793   _nodal_connec_index->decrRef();
5794   _nodal_connec_index=newConnI.retn();
5795   computeTypes();
5796   updateTime();
5797   return ret.retn();
5798 }
5799
5800 /*!
5801  * This private method is used to subdivide edges of a mesh with meshdim==2. If \a this has no a meshdim equal to 2 an exception will be thrown.
5802  * This method completly ignore coordinates.
5803  * \param nodeSubdived is the nodal connectivity of subdivision of edges
5804  * \param nodeIndxSubdived is the nodal connectivity index of subdivision of edges
5805  * \param desc is descending connectivity in format specified in MEDCouplingUMesh::buildDescendingConnectivity2
5806  * \param descIndex is descending connectivity index in format specified in MEDCouplingUMesh::buildDescendingConnectivity2
5807  */
5808 void MEDCouplingUMesh::subDivide2DMesh(const int *nodeSubdived, const int *nodeIndxSubdived, const int *desc, const int *descIndex)
5809 {
5810   checkFullyDefined();
5811   if(getMeshDimension()!=2)
5812     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::subDivide2DMesh : works only on umesh with meshdim==2 !");
5813   int nbOfCells=getNumberOfCells();
5814   int *connI=_nodal_connec_index->getPointer();
5815   int newConnLgth=0;
5816   for(int i=0;i<nbOfCells;i++,connI++)
5817     {
5818       int offset=descIndex[i];
5819       int nbOfEdges=descIndex[i+1]-offset;
5820       //
5821       bool ddirect=desc[offset+nbOfEdges-1]>0;
5822       int eedgeId=std::abs(desc[offset+nbOfEdges-1])-1;
5823       int ref=ddirect?nodeSubdived[nodeIndxSubdived[eedgeId+1]-1]:nodeSubdived[nodeIndxSubdived[eedgeId]+1];
5824       for(int j=0;j<nbOfEdges;j++)
5825         {
5826           bool direct=desc[offset+j]>0;
5827           int edgeId=std::abs(desc[offset+j])-1;
5828           if(!INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)nodeSubdived[nodeIndxSubdived[edgeId]]).isQuadratic())
5829             {
5830               int id1=nodeSubdived[nodeIndxSubdived[edgeId]+1];
5831               int id2=nodeSubdived[nodeIndxSubdived[edgeId+1]-1];
5832               int ref2=direct?id1:id2;
5833               if(ref==ref2)
5834                 {
5835                   int nbOfSubNodes=nodeIndxSubdived[edgeId+1]-nodeIndxSubdived[edgeId]-1;
5836                   newConnLgth+=nbOfSubNodes-1;
5837                   ref=direct?id2:id1;
5838                 }
5839               else
5840                 {
5841                   std::ostringstream oss; oss << "MEDCouplingUMesh::subDivide2DMesh : On polygon #" << i << " edgeid #" << j << " subedges mismatch : end subedge k!=start subedge k+1 !";
5842                   throw INTERP_KERNEL::Exception(oss.str().c_str());
5843                 }
5844             }
5845           else
5846             {
5847               throw INTERP_KERNEL::Exception("MEDCouplingUMesh::subDivide2DMesh : this method only subdivides into linear edges !");
5848             }
5849         }
5850       newConnLgth++;//+1 is for cell type
5851       connI[1]=newConnLgth;
5852     }
5853   //
5854   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConn=DataArrayInt::New();
5855   newConn->alloc(newConnLgth,1);
5856   int *work=newConn->getPointer();
5857   for(int i=0;i<nbOfCells;i++)
5858     {
5859       *work++=INTERP_KERNEL::NORM_POLYGON;
5860       int offset=descIndex[i];
5861       int nbOfEdges=descIndex[i+1]-offset;
5862       for(int j=0;j<nbOfEdges;j++)
5863         {
5864           bool direct=desc[offset+j]>0;
5865           int edgeId=std::abs(desc[offset+j])-1;
5866           if(direct)
5867             work=std::copy(nodeSubdived+nodeIndxSubdived[edgeId]+1,nodeSubdived+nodeIndxSubdived[edgeId+1]-1,work);
5868           else
5869             {
5870               int nbOfSubNodes=nodeIndxSubdived[edgeId+1]-nodeIndxSubdived[edgeId]-1;
5871               std::reverse_iterator<const int *> it(nodeSubdived+nodeIndxSubdived[edgeId+1]);
5872               work=std::copy(it,it+nbOfSubNodes-1,work);
5873             }
5874         }
5875     }
5876   DataArrayInt::SetArrayIn(newConn,_nodal_connec);
5877   _types.clear();
5878   if(nbOfCells>0)
5879     _types.insert(INTERP_KERNEL::NORM_POLYGON);
5880 }
5881
5882 /*!
5883  * Converts degenerated 2D or 3D linear cells of \a this mesh into cells of simpler
5884  * type. For example an INTERP_KERNEL::NORM_QUAD4 cell having only three unique nodes in
5885  * its connectivity is transformed into an INTERP_KERNEL::NORM_TRI3 cell. This method
5886  * does \b not perform geometrical checks and checks only nodal connectivity of cells,
5887  * so it can be useful to call mergeNodes() before calling this method.
5888  *  \throw If \a this->getMeshDimension() <= 1.
5889  *  \throw If the coordinates array is not set.
5890  *  \throw If the nodal connectivity of cells is not defined.
5891  */
5892 void MEDCouplingUMesh::convertDegeneratedCells()
5893 {
5894   checkFullyDefined();
5895   if(getMeshDimension()<=1)
5896     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertDegeneratedCells works on umeshes with meshdim equals to 2 or 3 !");
5897   int nbOfCells=getNumberOfCells();
5898   if(nbOfCells<1)
5899     return ;
5900   int initMeshLgth=getMeshLength();
5901   int *conn=_nodal_connec->getPointer();
5902   int *index=_nodal_connec_index->getPointer();
5903   int posOfCurCell=0;
5904   int newPos=0;
5905   int lgthOfCurCell;
5906   for(int i=0;i<nbOfCells;i++)
5907     {
5908       lgthOfCurCell=index[i+1]-posOfCurCell;
5909       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)conn[posOfCurCell];
5910       int newLgth;
5911       INTERP_KERNEL::NormalizedCellType newType=INTERP_KERNEL::CellSimplify::simplifyDegeneratedCell(type,conn+posOfCurCell+1,lgthOfCurCell-1,
5912                                                                                                      conn+newPos+1,newLgth);
5913       conn[newPos]=newType;
5914       newPos+=newLgth+1;
5915       posOfCurCell=index[i+1];
5916       index[i+1]=newPos;
5917     }
5918   if(newPos!=initMeshLgth)
5919     _nodal_connec->reAlloc(newPos);
5920   computeTypes();
5921 }
5922
5923 /*!
5924  * Finds incorrectly oriented cells of this 2D mesh in 3D space.
5925  * A cell is considered to be oriented correctly if an angle between its
5926  * normal vector and a given vector is less than \c PI / \c 2.
5927  *  \param [in] vec - 3 components of the vector specifying the correct orientation of
5928  *         cells. 
5929  *  \param [in] polyOnly - if \c true, only polygons are checked, else, all cells are
5930  *         checked.
5931  *  \param [in,out] cells - a vector returning ids of incorrectly oriented cells. It
5932  *         is not cleared before filling in.
5933  *  \throw If \a this->getMeshDimension() != 2.
5934  *  \throw If \a this->getSpaceDimension() != 3.
5935  *
5936  *  \if ENABLE_EXAMPLES
5937  *  \ref cpp_mcumesh_are2DCellsNotCorrectlyOriented "Here is a C++ example".<br>
5938  *  \ref  py_mcumesh_are2DCellsNotCorrectlyOriented "Here is a Python example".
5939  *  \endif
5940  */
5941 void MEDCouplingUMesh::are2DCellsNotCorrectlyOriented(const double *vec, bool polyOnly, std::vector<int>& cells) const
5942 {
5943   if(getMeshDimension()!=2 || getSpaceDimension()!=3)
5944     throw INTERP_KERNEL::Exception("Invalid mesh to apply are2DCellsNotCorrectlyOriented on it : must be meshDim==2 and spaceDim==3 !");
5945   int nbOfCells=getNumberOfCells();
5946   const int *conn=_nodal_connec->getConstPointer();
5947   const int *connI=_nodal_connec_index->getConstPointer();
5948   const double *coordsPtr=_coords->getConstPointer();
5949   for(int i=0;i<nbOfCells;i++)
5950     {
5951       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)conn[connI[i]];
5952       if(!polyOnly || (type==INTERP_KERNEL::NORM_POLYGON || type==INTERP_KERNEL::NORM_QPOLYG))
5953         {
5954           bool isQuadratic=INTERP_KERNEL::CellModel::GetCellModel(type).isQuadratic();
5955           if(!IsPolygonWellOriented(isQuadratic,vec,conn+connI[i]+1,conn+connI[i+1],coordsPtr))
5956             cells.push_back(i);
5957         }
5958     }
5959 }
5960
5961 /*!
5962  * Reverse connectivity of 2D cells whose orientation is not correct. A cell is
5963  * considered to be oriented correctly if an angle between its normal vector and a
5964  * given vector is less than \c PI / \c 2. 
5965  *  \param [in] vec - 3 components of the vector specifying the correct orientation of
5966  *         cells. 
5967  *  \param [in] polyOnly - if \c true, only polygons are checked, else, all cells are
5968  *         checked.
5969  *  \throw If \a this->getMeshDimension() != 2.
5970  *  \throw If \a this->getSpaceDimension() != 3.
5971  *
5972  *  \if ENABLE_EXAMPLES
5973  *  \ref cpp_mcumesh_are2DCellsNotCorrectlyOriented "Here is a C++ example".<br>
5974  *  \ref  py_mcumesh_are2DCellsNotCorrectlyOriented "Here is a Python example".
5975  *  \endif
5976  *
5977  *  \sa changeOrientationOfCells
5978  */
5979 void MEDCouplingUMesh::orientCorrectly2DCells(const double *vec, bool polyOnly)
5980 {
5981   if(getMeshDimension()!=2 || getSpaceDimension()!=3)
5982     throw INTERP_KERNEL::Exception("Invalid mesh to apply orientCorrectly2DCells on it : must be meshDim==2 and spaceDim==3 !");
5983   int nbOfCells(getNumberOfCells()),*conn(_nodal_connec->getPointer());
5984   const int *connI(_nodal_connec_index->getConstPointer());
5985   const double *coordsPtr(_coords->getConstPointer());
5986   bool isModified(false);
5987   for(int i=0;i<nbOfCells;i++)
5988     {
5989       INTERP_KERNEL::NormalizedCellType type((INTERP_KERNEL::NormalizedCellType)conn[connI[i]]);
5990       if(!polyOnly || (type==INTERP_KERNEL::NORM_POLYGON || type==INTERP_KERNEL::NORM_QPOLYG))
5991         {
5992           const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(type));
5993           bool isQuadratic(cm.isQuadratic());
5994           if(!IsPolygonWellOriented(isQuadratic,vec,conn+connI[i]+1,conn+connI[i+1],coordsPtr))
5995             {
5996               isModified=true;
5997               cm.changeOrientationOf2D(conn+connI[i]+1,(unsigned int)(connI[i+1]-connI[i]-1));
5998             }
5999         }
6000     }
6001   if(isModified)
6002     _nodal_connec->declareAsNew();
6003   updateTime();
6004 }
6005
6006 /*!
6007  * This method change the orientation of cells in \a this without any consideration of coordinates. Only connectivity is impacted.
6008  *
6009  * \sa orientCorrectly2DCells
6010  */
6011 void MEDCouplingUMesh::changeOrientationOfCells()
6012 {
6013   int mdim(getMeshDimension());
6014   if(mdim!=2 && mdim!=1)
6015     throw INTERP_KERNEL::Exception("Invalid mesh to apply changeOrientationOfCells on it : must be meshDim==2 or meshDim==1 !");
6016   int nbOfCells(getNumberOfCells()),*conn(_nodal_connec->getPointer());
6017   const int *connI(_nodal_connec_index->getConstPointer());
6018   if(mdim==2)
6019     {//2D
6020       for(int i=0;i<nbOfCells;i++)
6021         {
6022           INTERP_KERNEL::NormalizedCellType type((INTERP_KERNEL::NormalizedCellType)conn[connI[i]]);
6023           const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(type));
6024           cm.changeOrientationOf2D(conn+connI[i]+1,(unsigned int)(connI[i+1]-connI[i]-1));
6025         }
6026     }
6027   else
6028     {//1D
6029       for(int i=0;i<nbOfCells;i++)
6030         {
6031           INTERP_KERNEL::NormalizedCellType type((INTERP_KERNEL::NormalizedCellType)conn[connI[i]]);
6032           const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(type));
6033           cm.changeOrientationOf1D(conn+connI[i]+1,(unsigned int)(connI[i+1]-connI[i]-1));
6034         }
6035     }
6036 }
6037
6038 /*!
6039  * Finds incorrectly oriented polyhedral cells, i.e. polyhedrons having correctly
6040  * oriented facets. The normal vector of the facet should point out of the cell.
6041  *  \param [in,out] cells - a vector returning ids of incorrectly oriented cells. It
6042  *         is not cleared before filling in.
6043  *  \throw If \a this->getMeshDimension() != 3.
6044  *  \throw If \a this->getSpaceDimension() != 3.
6045  *  \throw If the coordinates array is not set.
6046  *  \throw If the nodal connectivity of cells is not defined.
6047  *
6048  *  \if ENABLE_EXAMPLES
6049  *  \ref cpp_mcumesh_arePolyhedronsNotCorrectlyOriented "Here is a C++ example".<br>
6050  *  \ref  py_mcumesh_arePolyhedronsNotCorrectlyOriented "Here is a Python example".
6051  *  \endif
6052  */
6053 void MEDCouplingUMesh::arePolyhedronsNotCorrectlyOriented(std::vector<int>& cells) const
6054 {
6055   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
6056     throw INTERP_KERNEL::Exception("Invalid mesh to apply arePolyhedronsNotCorrectlyOriented on it : must be meshDim==3 and spaceDim==3 !");
6057   int nbOfCells=getNumberOfCells();
6058   const int *conn=_nodal_connec->getConstPointer();
6059   const int *connI=_nodal_connec_index->getConstPointer();
6060   const double *coordsPtr=_coords->getConstPointer();
6061   for(int i=0;i<nbOfCells;i++)
6062     {
6063       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)conn[connI[i]];
6064       if(type==INTERP_KERNEL::NORM_POLYHED)
6065         {
6066           if(!IsPolyhedronWellOriented(conn+connI[i]+1,conn+connI[i+1],coordsPtr))
6067             cells.push_back(i);
6068         }
6069     }
6070 }
6071
6072 /*!
6073  * Tries to fix connectivity of polyhedra, so that normal vector of all facets to point
6074  * out of the cell. 
6075  *  \throw If \a this->getMeshDimension() != 3.
6076  *  \throw If \a this->getSpaceDimension() != 3.
6077  *  \throw If the coordinates array is not set.
6078  *  \throw If the nodal connectivity of cells is not defined.
6079  *  \throw If the reparation fails.
6080  *
6081  *  \if ENABLE_EXAMPLES
6082  *  \ref cpp_mcumesh_arePolyhedronsNotCorrectlyOriented "Here is a C++ example".<br>
6083  *  \ref  py_mcumesh_arePolyhedronsNotCorrectlyOriented "Here is a Python example".
6084  *  \endif
6085  * \sa MEDCouplingUMesh::findAndCorrectBadOriented3DCells
6086  */
6087 void MEDCouplingUMesh::orientCorrectlyPolyhedrons()
6088 {
6089   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
6090     throw INTERP_KERNEL::Exception("Invalid mesh to apply orientCorrectlyPolyhedrons on it : must be meshDim==3 and spaceDim==3 !");
6091   int nbOfCells=getNumberOfCells();
6092   int *conn=_nodal_connec->getPointer();
6093   const int *connI=_nodal_connec_index->getConstPointer();
6094   const double *coordsPtr=_coords->getConstPointer();
6095   for(int i=0;i<nbOfCells;i++)
6096     {
6097       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)conn[connI[i]];
6098       if(type==INTERP_KERNEL::NORM_POLYHED)
6099         {
6100           try
6101           {
6102               if(!IsPolyhedronWellOriented(conn+connI[i]+1,conn+connI[i+1],coordsPtr))
6103                 TryToCorrectPolyhedronOrientation(conn+connI[i]+1,conn+connI[i+1],coordsPtr);
6104           }
6105           catch(INTERP_KERNEL::Exception& e)
6106           {
6107               std::ostringstream oss; oss << "Something wrong in polyhedron #" << i << " : " << e.what();
6108               throw INTERP_KERNEL::Exception(oss.str().c_str());
6109           }
6110         }
6111     }
6112   updateTime();
6113 }
6114
6115 /*!
6116  * Finds and fixes incorrectly oriented linear extruded volumes (INTERP_KERNEL::NORM_HEXA8,
6117  * INTERP_KERNEL::NORM_PENTA6, INTERP_KERNEL::NORM_HEXGP12 etc) to respect the MED convention
6118  * according to which the first facet of the cell should be oriented to have the normal vector
6119  * pointing out of cell.
6120  *  \return DataArrayInt * - a new instance of DataArrayInt holding ids of fixed
6121  *         cells. The caller is to delete this array using decrRef() as it is no more
6122  *         needed. 
6123  *  \throw If \a this->getMeshDimension() != 3.
6124  *  \throw If \a this->getSpaceDimension() != 3.
6125  *  \throw If the coordinates array is not set.
6126  *  \throw If the nodal connectivity of cells is not defined.
6127  *
6128  *  \if ENABLE_EXAMPLES
6129  *  \ref cpp_mcumesh_findAndCorrectBadOriented3DExtrudedCells "Here is a C++ example".<br>
6130  *  \ref  py_mcumesh_findAndCorrectBadOriented3DExtrudedCells "Here is a Python example".
6131  *  \endif
6132  * \sa MEDCouplingUMesh::findAndCorrectBadOriented3DCells
6133  */
6134 DataArrayInt *MEDCouplingUMesh::findAndCorrectBadOriented3DExtrudedCells()
6135 {
6136   const char msg[]="check3DCellsWellOriented detection works only for 3D cells !";
6137   if(getMeshDimension()!=3)
6138     throw INTERP_KERNEL::Exception(msg);
6139   int spaceDim=getSpaceDimension();
6140   if(spaceDim!=3)
6141     throw INTERP_KERNEL::Exception(msg);
6142   //
6143   int nbOfCells=getNumberOfCells();
6144   int *conn=_nodal_connec->getPointer();
6145   const int *connI=_nodal_connec_index->getConstPointer();
6146   const double *coo=getCoords()->getConstPointer();
6147   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> cells(DataArrayInt::New()); cells->alloc(0,1);
6148   for(int i=0;i<nbOfCells;i++)
6149     {
6150       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[connI[i]]);
6151       if(cm.isExtruded() && !cm.isDynamic() && !cm.isQuadratic())
6152         {
6153           if(!Is3DExtrudedStaticCellWellOriented(conn+connI[i]+1,conn+connI[i+1],coo))
6154             {
6155               CorrectExtrudedStaticCell(conn+connI[i]+1,conn+connI[i+1]);
6156               cells->pushBackSilent(i);
6157             }
6158         }
6159     }
6160   return cells.retn();
6161 }
6162
6163 /*!
6164  * This method is a faster method to correct orientation of all 3D cells in \a this.
6165  * This method works only if \a this is a 3D mesh, that is to say a mesh with mesh dimension 3 and a space dimension 3.
6166  * This method makes the hypothesis that \a this a coherent that is to say MEDCouplingUMesh::checkCoherency2 should throw no exception.
6167  * 
6168  * \ret a newly allocated int array with one components containing cell ids renumbered to fit the convention of MED (MED file and MEDCoupling)
6169  * \sa MEDCouplingUMesh::orientCorrectlyPolyhedrons, 
6170  */
6171 DataArrayInt *MEDCouplingUMesh::findAndCorrectBadOriented3DCells()
6172 {
6173   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
6174     throw INTERP_KERNEL::Exception("Invalid mesh to apply findAndCorrectBadOriented3DCells on it : must be meshDim==3 and spaceDim==3 !");
6175   int nbOfCells=getNumberOfCells();
6176   int *conn=_nodal_connec->getPointer();
6177   const int *connI=_nodal_connec_index->getConstPointer();
6178   const double *coordsPtr=_coords->getConstPointer();
6179   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New(); ret->alloc(0,1);
6180   for(int i=0;i<nbOfCells;i++)
6181     {
6182       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)conn[connI[i]];
6183       switch(type)
6184       {
6185         case INTERP_KERNEL::NORM_TETRA4:
6186           {
6187             if(!IsTetra4WellOriented(conn+connI[i]+1,conn+connI[i+1],coordsPtr))
6188               {
6189                 std::swap(*(conn+connI[i]+2),*(conn+connI[i]+3));
6190                 ret->pushBackSilent(i);
6191               }
6192             break;
6193           }
6194         case INTERP_KERNEL::NORM_PYRA5:
6195           {
6196             if(!IsPyra5WellOriented(conn+connI[i]+1,conn+connI[i+1],coordsPtr))
6197               {
6198                 std::swap(*(conn+connI[i]+2),*(conn+connI[i]+4));
6199                 ret->pushBackSilent(i);
6200               }
6201             break;
6202           }
6203         case INTERP_KERNEL::NORM_PENTA6:
6204         case INTERP_KERNEL::NORM_HEXA8:
6205         case INTERP_KERNEL::NORM_HEXGP12:
6206           {
6207             if(!Is3DExtrudedStaticCellWellOriented(conn+connI[i]+1,conn+connI[i+1],coordsPtr))
6208               {
6209                 CorrectExtrudedStaticCell(conn+connI[i]+1,conn+connI[i+1]);
6210                 ret->pushBackSilent(i);
6211               }
6212             break;
6213           }
6214         case INTERP_KERNEL::NORM_POLYHED:
6215           {
6216             if(!IsPolyhedronWellOriented(conn+connI[i]+1,conn+connI[i+1],coordsPtr))
6217               {
6218                 TryToCorrectPolyhedronOrientation(conn+connI[i]+1,conn+connI[i+1],coordsPtr);
6219                 ret->pushBackSilent(i);
6220               }
6221             break;
6222           }
6223         default:
6224           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::orientCorrectly3DCells : Your mesh contains type of cell not supported yet ! send mail to anthony.geay@cea.fr to add it !");
6225       }
6226     }
6227   updateTime();
6228   return ret.retn();
6229 }
6230
6231 /*!
6232  * This method has a sense for meshes with spaceDim==3 and meshDim==2.
6233  * If it is not the case an exception will be thrown.
6234  * This method is fast because the first cell of \a this is used to compute the plane.
6235  * \param vec output of size at least 3 used to store the normal vector (with norm equal to Area ) of searched plane.
6236  * \param pos output of size at least 3 used to store a point owned of searched plane.
6237  */
6238 void MEDCouplingUMesh::getFastAveragePlaneOfThis(double *vec, double *pos) const
6239 {
6240   if(getMeshDimension()!=2 || getSpaceDimension()!=3)
6241     throw INTERP_KERNEL::Exception("Invalid mesh to apply getFastAveragePlaneOfThis on it : must be meshDim==2 and spaceDim==3 !");
6242   const int *conn=_nodal_connec->getConstPointer();
6243   const int *connI=_nodal_connec_index->getConstPointer();
6244   const double *coordsPtr=_coords->getConstPointer();
6245   INTERP_KERNEL::areaVectorOfPolygon<int,INTERP_KERNEL::ALL_C_MODE>(conn+1,connI[1]-connI[0]-1,coordsPtr,vec);
6246   std::copy(coordsPtr+3*conn[1],coordsPtr+3*conn[1]+3,pos);
6247 }
6248
6249 /*!
6250  * Creates a new MEDCouplingFieldDouble holding Edge Ratio values of all
6251  * cells. Currently cells of the following types are treated:
6252  * INTERP_KERNEL::NORM_TRI3, INTERP_KERNEL::NORM_QUAD4 and INTERP_KERNEL::NORM_TETRA4.
6253  * For a cell of other type an exception is thrown.
6254  * Space dimension of a 2D mesh can be either 2 or 3.
6255  * The Edge Ratio of a cell \f$t\f$ is: 
6256  *  \f$\frac{|t|_\infty}{|t|_0}\f$,
6257  *  where \f$|t|_\infty\f$ and \f$|t|_0\f$ respectively denote the greatest and
6258  *  the smallest edge lengths of \f$t\f$.
6259  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
6260  *          cells and one time, lying on \a this mesh. The caller is to delete this
6261  *          field using decrRef() as it is no more needed. 
6262  *  \throw If the coordinates array is not set.
6263  *  \throw If \a this mesh contains elements of dimension different from the mesh dimension.
6264  *  \throw If the connectivity data array has more than one component.
6265  *  \throw If the connectivity data array has a named component.
6266  *  \throw If the connectivity index data array has more than one component.
6267  *  \throw If the connectivity index data array has a named component.
6268  *  \throw If \a this->getMeshDimension() is neither 2 nor 3.
6269  *  \throw If \a this->getSpaceDimension() is neither 2 nor 3.
6270  *  \throw If \a this mesh includes cells of type different from the ones enumerated above.
6271  */
6272 MEDCouplingFieldDouble *MEDCouplingUMesh::getEdgeRatioField() const
6273 {
6274   checkCoherency();
6275   int spaceDim=getSpaceDimension();
6276   int meshDim=getMeshDimension();
6277   if(spaceDim!=2 && spaceDim!=3)
6278     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getEdgeRatioField : SpaceDimension must be equal to 2 or 3 !");
6279   if(meshDim!=2 && meshDim!=3)
6280     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getEdgeRatioField : MeshDimension must be equal to 2 or 3 !");
6281   MEDCouplingAutoRefCountObjectPtr<MEDCouplingFieldDouble> ret=MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME);
6282   ret->setMesh(this);
6283   int nbOfCells=getNumberOfCells();
6284   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> arr=DataArrayDouble::New();
6285   arr->alloc(nbOfCells,1);
6286   double *pt=arr->getPointer();
6287   ret->setArray(arr);//In case of throw to avoid mem leaks arr will be used after decrRef.
6288   const int *conn=_nodal_connec->getConstPointer();
6289   const int *connI=_nodal_connec_index->getConstPointer();
6290   const double *coo=_coords->getConstPointer();
6291   double tmp[12];
6292   for(int i=0;i<nbOfCells;i++,pt++)
6293     {
6294       INTERP_KERNEL::NormalizedCellType t=(INTERP_KERNEL::NormalizedCellType)*conn;
6295       switch(t)
6296       {
6297         case INTERP_KERNEL::NORM_TRI3:
6298           {
6299             FillInCompact3DMode(spaceDim,3,conn+1,coo,tmp);
6300             *pt=INTERP_KERNEL::triEdgeRatio(tmp);
6301             break;
6302           }
6303         case INTERP_KERNEL::NORM_QUAD4:
6304           {
6305             FillInCompact3DMode(spaceDim,4,conn+1,coo,tmp);
6306             *pt=INTERP_KERNEL::quadEdgeRatio(tmp);
6307             break;
6308           }
6309         case INTERP_KERNEL::NORM_TETRA4:
6310           {
6311             FillInCompact3DMode(spaceDim,4,conn+1,coo,tmp);
6312             *pt=INTERP_KERNEL::tetraEdgeRatio(tmp);
6313             break;
6314           }
6315         default:
6316           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getEdgeRatioField : A cell with not manged type (NORM_TRI3, NORM_QUAD4 and NORM_TETRA4) has been detected !");
6317       }
6318       conn+=connI[i+1]-connI[i];
6319     }
6320   ret->setName("EdgeRatio");
6321   ret->synchronizeTimeWithSupport();
6322   return ret.retn();
6323 }
6324
6325 /*!
6326  * Creates a new MEDCouplingFieldDouble holding Aspect Ratio values of all
6327  * cells. Currently cells of the following types are treated:
6328  * INTERP_KERNEL::NORM_TRI3, INTERP_KERNEL::NORM_QUAD4 and INTERP_KERNEL::NORM_TETRA4.
6329  * For a cell of other type an exception is thrown.
6330  * Space dimension of a 2D mesh can be either 2 or 3.
6331  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
6332  *          cells and one time, lying on \a this mesh. The caller is to delete this
6333  *          field using decrRef() as it is no more needed. 
6334  *  \throw If the coordinates array is not set.
6335  *  \throw If \a this mesh contains elements of dimension different from the mesh dimension.
6336  *  \throw If the connectivity data array has more than one component.
6337  *  \throw If the connectivity data array has a named component.
6338  *  \throw If the connectivity index data array has more than one component.
6339  *  \throw If the connectivity index data array has a named component.
6340  *  \throw If \a this->getMeshDimension() is neither 2 nor 3.
6341  *  \throw If \a this->getSpaceDimension() is neither 2 nor 3.
6342  *  \throw If \a this mesh includes cells of type different from the ones enumerated above.
6343  */
6344 MEDCouplingFieldDouble *MEDCouplingUMesh::getAspectRatioField() const
6345 {
6346   checkCoherency();
6347   int spaceDim=getSpaceDimension();
6348   int meshDim=getMeshDimension();
6349   if(spaceDim!=2 && spaceDim!=3)
6350     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getAspectRatioField : SpaceDimension must be equal to 2 or 3 !");
6351   if(meshDim!=2 && meshDim!=3)
6352     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getAspectRatioField : MeshDimension must be equal to 2 or 3 !");
6353   MEDCouplingAutoRefCountObjectPtr<MEDCouplingFieldDouble> ret=MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME);
6354   ret->setMesh(this);
6355   int nbOfCells=getNumberOfCells();
6356   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> arr=DataArrayDouble::New();
6357   arr->alloc(nbOfCells,1);
6358   double *pt=arr->getPointer();
6359   ret->setArray(arr);//In case of throw to avoid mem leaks arr will be used after decrRef.
6360   const int *conn=_nodal_connec->getConstPointer();
6361   const int *connI=_nodal_connec_index->getConstPointer();
6362   const double *coo=_coords->getConstPointer();
6363   double tmp[12];
6364   for(int i=0;i<nbOfCells;i++,pt++)
6365     {
6366       INTERP_KERNEL::NormalizedCellType t=(INTERP_KERNEL::NormalizedCellType)*conn;
6367       switch(t)
6368       {
6369         case INTERP_KERNEL::NORM_TRI3:
6370           {
6371             FillInCompact3DMode(spaceDim,3,conn+1,coo,tmp);
6372             *pt=INTERP_KERNEL::triAspectRatio(tmp);
6373             break;
6374           }
6375         case INTERP_KERNEL::NORM_QUAD4:
6376           {
6377             FillInCompact3DMode(spaceDim,4,conn+1,coo,tmp);
6378             *pt=INTERP_KERNEL::quadAspectRatio(tmp);
6379             break;
6380           }
6381         case INTERP_KERNEL::NORM_TETRA4:
6382           {
6383             FillInCompact3DMode(spaceDim,4,conn+1,coo,tmp);
6384             *pt=INTERP_KERNEL::tetraAspectRatio(tmp);
6385             break;
6386           }
6387         default:
6388           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getAspectRatioField : A cell with not manged type (NORM_TRI3, NORM_QUAD4 and NORM_TETRA4) has been detected !");
6389       }
6390       conn+=connI[i+1]-connI[i];
6391     }
6392   ret->setName("AspectRatio");
6393   ret->synchronizeTimeWithSupport();
6394   return ret.retn();
6395 }
6396
6397 /*!
6398  * Creates a new MEDCouplingFieldDouble holding Warping factor values of all
6399  * cells of \a this 2D mesh in 3D space. Currently cells of the following types are
6400  * treated: INTERP_KERNEL::NORM_QUAD4.
6401  * For a cell of other type an exception is thrown.
6402  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
6403  *          cells and one time, lying on \a this mesh. The caller is to delete this
6404  *          field using decrRef() as it is no more needed. 
6405  *  \throw If the coordinates array is not set.
6406  *  \throw If \a this mesh contains elements of dimension different from the mesh dimension.
6407  *  \throw If the connectivity data array has more than one component.
6408  *  \throw If the connectivity data array has a named component.
6409  *  \throw If the connectivity index data array has more than one component.
6410  *  \throw If the connectivity index data array has a named component.
6411  *  \throw If \a this->getMeshDimension() != 2.
6412  *  \throw If \a this->getSpaceDimension() != 3.
6413  *  \throw If \a this mesh includes cells of type different from the ones enumerated above.
6414  */
6415 MEDCouplingFieldDouble *MEDCouplingUMesh::getWarpField() const
6416 {
6417   checkCoherency();
6418   int spaceDim=getSpaceDimension();
6419   int meshDim=getMeshDimension();
6420   if(spaceDim!=3)
6421     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getWarpField : SpaceDimension must be equal to 3 !");
6422   if(meshDim!=2)
6423     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getWarpField : MeshDimension must be equal to 2 !");
6424   MEDCouplingAutoRefCountObjectPtr<MEDCouplingFieldDouble> ret=MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME);
6425   ret->setMesh(this);
6426   int nbOfCells=getNumberOfCells();
6427   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> arr=DataArrayDouble::New();
6428   arr->alloc(nbOfCells,1);
6429   double *pt=arr->getPointer();
6430   ret->setArray(arr);//In case of throw to avoid mem leaks arr will be used after decrRef.
6431   const int *conn=_nodal_connec->getConstPointer();
6432   const int *connI=_nodal_connec_index->getConstPointer();
6433   const double *coo=_coords->getConstPointer();
6434   double tmp[12];
6435   for(int i=0;i<nbOfCells;i++,pt++)
6436     {
6437       INTERP_KERNEL::NormalizedCellType t=(INTERP_KERNEL::NormalizedCellType)*conn;
6438       switch(t)
6439       {
6440         case INTERP_KERNEL::NORM_QUAD4:
6441           {
6442             FillInCompact3DMode(3,4,conn+1,coo,tmp);
6443             *pt=INTERP_KERNEL::quadWarp(tmp);
6444             break;
6445           }
6446         default:
6447           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getWarpField : A cell with not manged type (NORM_QUAD4) has been detected !");
6448       }
6449       conn+=connI[i+1]-connI[i];
6450     }
6451   ret->setName("Warp");
6452   ret->synchronizeTimeWithSupport();
6453   return ret.retn();
6454 }
6455
6456
6457 /*!
6458  * Creates a new MEDCouplingFieldDouble holding Skew factor values of all
6459  * cells of \a this 2D mesh in 3D space. Currently cells of the following types are
6460  * treated: INTERP_KERNEL::NORM_QUAD4.
6461  * For a cell of other type an exception is thrown.
6462  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
6463  *          cells and one time, lying on \a this mesh. The caller is to delete this
6464  *          field using decrRef() as it is no more needed. 
6465  *  \throw If the coordinates array is not set.
6466  *  \throw If \a this mesh contains elements of dimension different from the mesh dimension.
6467  *  \throw If the connectivity data array has more than one component.
6468  *  \throw If the connectivity data array has a named component.
6469  *  \throw If the connectivity index data array has more than one component.
6470  *  \throw If the connectivity index data array has a named component.
6471  *  \throw If \a this->getMeshDimension() != 2.
6472  *  \throw If \a this->getSpaceDimension() != 3.
6473  *  \throw If \a this mesh includes cells of type different from the ones enumerated above.
6474  */
6475 MEDCouplingFieldDouble *MEDCouplingUMesh::getSkewField() const
6476 {
6477   checkCoherency();
6478   int spaceDim=getSpaceDimension();
6479   int meshDim=getMeshDimension();
6480   if(spaceDim!=3)
6481     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getSkewField : SpaceDimension must be equal to 3 !");
6482   if(meshDim!=2)
6483     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getSkewField : MeshDimension must be equal to 2 !");
6484   MEDCouplingAutoRefCountObjectPtr<MEDCouplingFieldDouble> ret=MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME);
6485   ret->setMesh(this);
6486   int nbOfCells=getNumberOfCells();
6487   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> arr=DataArrayDouble::New();
6488   arr->alloc(nbOfCells,1);
6489   double *pt=arr->getPointer();
6490   ret->setArray(arr);//In case of throw to avoid mem leaks arr will be used after decrRef.
6491   const int *conn=_nodal_connec->getConstPointer();
6492   const int *connI=_nodal_connec_index->getConstPointer();
6493   const double *coo=_coords->getConstPointer();
6494   double tmp[12];
6495   for(int i=0;i<nbOfCells;i++,pt++)
6496     {
6497       INTERP_KERNEL::NormalizedCellType t=(INTERP_KERNEL::NormalizedCellType)*conn;
6498       switch(t)
6499       {
6500         case INTERP_KERNEL::NORM_QUAD4:
6501           {
6502             FillInCompact3DMode(3,4,conn+1,coo,tmp);
6503             *pt=INTERP_KERNEL::quadSkew(tmp);
6504             break;
6505           }
6506         default:
6507           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getSkewField : A cell with not manged type (NORM_QUAD4) has been detected !");
6508       }
6509       conn+=connI[i+1]-connI[i];
6510     }
6511   ret->setName("Skew");
6512   ret->synchronizeTimeWithSupport();
6513   return ret.retn();
6514 }
6515
6516 /*!
6517  * This method aggregate the bbox of each cell and put it into bbox parameter.
6518  * 
6519  * \param [in] arcDetEps - a parameter specifying in case of 2D quadratic polygon cell the detection limit between linear and arc circle. (By default 1e-12)
6520  *                         For all other cases this input parameter is ignored.
6521  * \return DataArrayDouble * - newly created object (to be managed by the caller) \a this number of cells tuples and 2*spacedim components.
6522  * 
6523  * \throw If \a this is not fully set (coordinates and connectivity).
6524  * \throw If a cell in \a this has no valid nodeId.
6525  * \sa MEDCouplingUMesh::getBoundingBoxForBBTreeFast, MEDCouplingUMesh::getBoundingBoxForBBTree2DQuadratic
6526  */
6527 DataArrayDouble *MEDCouplingUMesh::getBoundingBoxForBBTree(double arcDetEps) const
6528 {
6529   int mDim(getMeshDimension()),sDim(getSpaceDimension());
6530   if((mDim==3 && sDim==3) || (mDim==2 && sDim==3) || (mDim==1 && sDim==1) || ( mDim==1 && sDim==3))  // Compute refined boundary box for quadratic elements only in 2D.
6531     return getBoundingBoxForBBTreeFast();
6532   if((mDim==2 && sDim==2) || (mDim==1 && sDim==2))
6533     {
6534       bool presenceOfQuadratic(false);
6535       for(std::set<INTERP_KERNEL::NormalizedCellType>::const_iterator it=_types.begin();it!=_types.end();it++)
6536         {
6537           const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(*it));
6538           if(cm.isQuadratic())
6539             presenceOfQuadratic=true;
6540         }
6541       if(!presenceOfQuadratic)
6542         return getBoundingBoxForBBTreeFast();
6543       if(mDim==2 && sDim==2)
6544         return getBoundingBoxForBBTree2DQuadratic(arcDetEps);
6545       else
6546         return getBoundingBoxForBBTree1DQuadratic(arcDetEps);
6547     }
6548   throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getBoundingBoxForBBTree : Managed dimensions are (mDim=1,sDim=1), (mDim=1,sDim=2), (mDim=1,sDim=3), (mDim=2,sDim=2), (mDim=2,sDim=3) and (mDim=3,sDim=3) !");
6549 }
6550
6551 /*!
6552  * This method aggregate the bbox of each cell only considering the nodes constituting each cell and put it into bbox parameter.
6553  * So meshes having quadratic cells the computed bounding boxes can be invalid !
6554  * 
6555  * \return DataArrayDouble * - newly created object (to be managed by the caller) \a this number of cells tuples and 2*spacedim components.
6556  * 
6557  * \throw If \a this is not fully set (coordinates and connectivity).
6558  * \throw If a cell in \a this has no valid nodeId.
6559  */
6560 DataArrayDouble *MEDCouplingUMesh::getBoundingBoxForBBTreeFast() const
6561 {
6562   checkFullyDefined();
6563   int spaceDim(getSpaceDimension()),nbOfCells(getNumberOfCells()),nbOfNodes(getNumberOfNodes());
6564   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> ret(DataArrayDouble::New()); ret->alloc(nbOfCells,2*spaceDim);
6565   double *bbox(ret->getPointer());
6566   for(int i=0;i<nbOfCells*spaceDim;i++)
6567     {
6568       bbox[2*i]=std::numeric_limits<double>::max();
6569       bbox[2*i+1]=-std::numeric_limits<double>::max();
6570     }
6571   const double *coordsPtr(_coords->getConstPointer());
6572   const int *conn(_nodal_connec->getConstPointer()),*connI(_nodal_connec_index->getConstPointer());
6573   for(int i=0;i<nbOfCells;i++)
6574     {
6575       int offset=connI[i]+1;
6576       int nbOfNodesForCell(connI[i+1]-offset),kk(0);
6577       for(int j=0;j<nbOfNodesForCell;j++)
6578         {
6579           int nodeId=conn[offset+j];
6580           if(nodeId>=0 && nodeId<nbOfNodes)
6581             {
6582               for(int k=0;k<spaceDim;k++)
6583                 {
6584                   bbox[2*spaceDim*i+2*k]=std::min(bbox[2*spaceDim*i+2*k],coordsPtr[spaceDim*nodeId+k]);
6585                   bbox[2*spaceDim*i+2*k+1]=std::max(bbox[2*spaceDim*i+2*k+1],coordsPtr[spaceDim*nodeId+k]);
6586                 }
6587               kk++;
6588             }
6589         }
6590       if(kk==0)
6591         {
6592           std::ostringstream oss; oss << "MEDCouplingUMesh::getBoundingBoxForBBTree : cell #" << i << " contains no valid nodeId !";
6593           throw INTERP_KERNEL::Exception(oss.str().c_str());
6594         }
6595     }
6596   return ret.retn();
6597 }
6598
6599 /*!
6600  * This method aggregates the bbox of each 2D cell in \a this considering the whole shape. This method is particularly
6601  * useful for 2D meshes having quadratic cells
6602  * because for this type of cells getBoundingBoxForBBTreeFast method may return invalid bounding boxes (since it just considers
6603  * the two extremities of the arc of circle).
6604  * 
6605  * \param [in] arcDetEps - a parameter specifying in case of 2D quadratic polygon cell the detection limit between linear and arc circle. (By default 1e-12)
6606  * \return DataArrayDouble * - newly created object (to be managed by the caller) \a this number of cells tuples and 2*spacedim components.
6607  * \throw If \a this is not fully defined.
6608  * \throw If \a this is not a mesh with meshDimension equal to 2.
6609  * \throw If \a this is not a mesh with spaceDimension equal to 2.
6610  * \sa MEDCouplingUMesh::getBoundingBoxForBBTree1DQuadratic
6611  */
6612 DataArrayDouble *MEDCouplingUMesh::getBoundingBoxForBBTree2DQuadratic(double arcDetEps) const
6613 {
6614   checkFullyDefined();
6615   int spaceDim(getSpaceDimension()),mDim(getMeshDimension()),nbOfCells(getNumberOfCells());
6616   if(spaceDim!=2 || mDim!=2)
6617     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getBoundingBoxForBBTree2DQuadratic : This method should be applied on mesh with mesh dimension equal to 2 and space dimension also equal to 2!");
6618   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> ret(DataArrayDouble::New()); ret->alloc(nbOfCells,2*spaceDim);
6619   double *bbox(ret->getPointer());
6620   const double *coords(_coords->getConstPointer());
6621   const int *conn(_nodal_connec->getConstPointer()),*connI(_nodal_connec_index->getConstPointer());
6622   for(int i=0;i<nbOfCells;i++,bbox+=4,connI++)
6623     {
6624       const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[*connI]));
6625       int sz(connI[1]-connI[0]-1);
6626       INTERP_KERNEL::QUADRATIC_PLANAR::_arc_detection_precision=arcDetEps;
6627       std::vector<INTERP_KERNEL::Node *> nodes(sz);
6628       INTERP_KERNEL::QuadraticPolygon *pol(0);
6629       for(int j=0;j<sz;j++)
6630         {
6631           int nodeId(conn[*connI+1+j]);
6632           nodes[j]=new INTERP_KERNEL::Node(coords[nodeId*2],coords[nodeId*2+1]);
6633         }
6634       if(!cm.isQuadratic())
6635         pol=INTERP_KERNEL::QuadraticPolygon::BuildLinearPolygon(nodes);
6636       else
6637         pol=INTERP_KERNEL::QuadraticPolygon::BuildArcCirclePolygon(nodes);
6638       INTERP_KERNEL::Bounds b; b.prepareForAggregation(); pol->fillBounds(b); delete pol;
6639       bbox[0]=b.getXMin(); bbox[1]=b.getXMax(); bbox[2]=b.getYMin(); bbox[3]=b.getYMax(); 
6640     }
6641   return ret.retn();
6642 }
6643
6644 /*!
6645  * This method aggregates the bbox of each 1D cell in \a this considering the whole shape. This method is particularly
6646  * useful for 2D meshes having quadratic cells
6647  * because for this type of cells getBoundingBoxForBBTreeFast method may return invalid bounding boxes (since it just considers
6648  * the two extremities of the arc of circle).
6649  * 
6650  * \param [in] arcDetEps - a parameter specifying in case of 2D quadratic polygon cell the detection limit between linear and arc circle. (By default 1e-12)
6651  * \return DataArrayDouble * - newly created object (to be managed by the caller) \a this number of cells tuples and 2*spacedim components.
6652  * \throw If \a this is not fully defined.
6653  * \throw If \a this is not a mesh with meshDimension equal to 1.
6654  * \throw If \a this is not a mesh with spaceDimension equal to 2.
6655  * \sa MEDCouplingUMesh::getBoundingBoxForBBTree2DQuadratic
6656  */
6657 DataArrayDouble *MEDCouplingUMesh::getBoundingBoxForBBTree1DQuadratic(double arcDetEps) const
6658 {
6659   checkFullyDefined();
6660   int spaceDim(getSpaceDimension()),mDim(getMeshDimension()),nbOfCells(getNumberOfCells());
6661   if(spaceDim!=2 || mDim!=1)
6662     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getBoundingBoxForBBTree1DQuadratic : This method should be applied on mesh with mesh dimension equal to 1 and space dimension also equal to 2!");
6663   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> ret(DataArrayDouble::New()); ret->alloc(nbOfCells,2*spaceDim);
6664   double *bbox(ret->getPointer());
6665   const double *coords(_coords->getConstPointer());
6666   const int *conn(_nodal_connec->getConstPointer()),*connI(_nodal_connec_index->getConstPointer());
6667   for(int i=0;i<nbOfCells;i++,bbox+=4,connI++)
6668     {
6669       const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[*connI]));
6670       int sz(connI[1]-connI[0]-1);
6671       INTERP_KERNEL::QUADRATIC_PLANAR::_arc_detection_precision=arcDetEps;
6672       std::vector<INTERP_KERNEL::Node *> nodes(sz);
6673       INTERP_KERNEL::Edge *edge(0);
6674       for(int j=0;j<sz;j++)
6675         {
6676           int nodeId(conn[*connI+1+j]);
6677           nodes[j]=new INTERP_KERNEL::Node(coords[nodeId*2],coords[nodeId*2+1]);
6678         }
6679       if(!cm.isQuadratic())
6680         edge=INTERP_KERNEL::QuadraticPolygon::BuildLinearEdge(nodes);
6681       else
6682         edge=INTERP_KERNEL::QuadraticPolygon::BuildArcCircleEdge(nodes);
6683       const INTERP_KERNEL::Bounds& b(edge->getBounds());
6684       bbox[0]=b.getXMin(); bbox[1]=b.getXMax(); bbox[2]=b.getYMin(); bbox[3]=b.getYMax(); edge->decrRef();
6685     }
6686   return ret.retn();
6687 }
6688
6689 /// @cond INTERNAL
6690
6691 namespace ParaMEDMEMImpl
6692 {
6693   class ConnReader
6694   {
6695   public:
6696     ConnReader(const int *c, int val):_conn(c),_val(val) { }
6697     bool operator() (const int& pos) { return _conn[pos]!=_val; }
6698   private:
6699     const int *_conn;
6700     int _val;
6701   };
6702
6703   class ConnReader2
6704   {
6705   public:
6706     ConnReader2(const int *c, int val):_conn(c),_val(val) { }
6707     bool operator() (const int& pos) { return _conn[pos]==_val; }
6708   private:
6709     const int *_conn;
6710     int _val;
6711   };
6712 }
6713
6714 /// @endcond
6715
6716 /*!
6717  * This method expects that \a this is sorted by types. If not an exception will be thrown.
6718  * This method returns in the same format as code (see MEDCouplingUMesh::checkTypeConsistencyAndContig or MEDCouplingUMesh::splitProfilePerType) how
6719  * \a this is composed in cell types.
6720  * The returned array is of size 3*n where n is the number of different types present in \a this. 
6721  * For every k in [0,n] ret[3*k+2]==-1 because it has no sense here. 
6722  * This parameter is kept only for compatibility with other methode listed above.
6723  */
6724 std::vector<int> MEDCouplingUMesh::getDistributionOfTypes() const
6725 {
6726   checkConnectivityFullyDefined();
6727   const int *conn=_nodal_connec->getConstPointer();
6728   const int *connI=_nodal_connec_index->getConstPointer();
6729   const int *work=connI;
6730   int nbOfCells=getNumberOfCells();
6731   std::size_t n=getAllGeoTypes().size();
6732   std::vector<int> ret(3*n,-1); //ret[3*k+2]==-1 because it has no sense here
6733   std::set<INTERP_KERNEL::NormalizedCellType> types;
6734   for(std::size_t i=0;work!=connI+nbOfCells;i++)
6735     {
6736       INTERP_KERNEL::NormalizedCellType typ=(INTERP_KERNEL::NormalizedCellType)conn[*work];
6737       if(types.find(typ)!=types.end())
6738         {
6739           std::ostringstream oss; oss << "MEDCouplingUMesh::getDistributionOfTypes : Type " << INTERP_KERNEL::CellModel::GetCellModel(typ).getRepr();
6740           oss << " is not contiguous !";
6741           throw INTERP_KERNEL::Exception(oss.str().c_str());
6742         }
6743       types.insert(typ);
6744       ret[3*i]=typ;
6745       const int *work2=std::find_if(work+1,connI+nbOfCells,ParaMEDMEMImpl::ConnReader(conn,typ));
6746       ret[3*i+1]=(int)std::distance(work,work2);
6747       work=work2;
6748     }
6749   return ret;
6750 }
6751
6752 /*!
6753  * This method is used to check that this has contiguous cell type in same order than described in \a code.
6754  * only for types cell, type node is not managed.
6755  * Format of \a code is the following. \a code should be of size 3*n and non empty. If not an exception is thrown.
6756  * foreach k in [0,n) on 3*k pos represent the geometric type and 3*k+1 number of elements of type 3*k.
6757  * 3*k+2 refers if different from -1 the pos in 'idsPerType' to get the corresponding array.
6758  * If 2 or more same geometric type is in \a code and exception is thrown too.
6759  *
6760  * This method firstly checks
6761  * If it exists k so that 3*k geometric type is not in geometric types of this an exception will be thrown.
6762  * If it exists k so that 3*k geometric type exists but the number of consecutive cell types does not match,
6763  * an exception is thrown too.
6764  * 
6765  * If all geometric types in \a code are exactly those in \a this null pointer is returned.
6766  * If it exists a geometric type in \a this \b not in \a code \b no exception is thrown 
6767  * and a DataArrayInt instance is returned that the user has the responsability to deallocate.
6768  */
6769 DataArrayInt *MEDCouplingUMesh::checkTypeConsistencyAndContig(const std::vector<int>& code, const std::vector<const DataArrayInt *>& idsPerType) const
6770 {
6771   if(code.empty())
6772     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::checkTypeConsistencyAndContig : code is empty, should not !");
6773   std::size_t sz=code.size();
6774   std::size_t n=sz/3;
6775   if(sz%3!=0)
6776     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::checkTypeConsistencyAndContig : code size is NOT %3 !");
6777   std::vector<INTERP_KERNEL::NormalizedCellType> types;
6778   int nb=0;
6779   bool isNoPflUsed=true;
6780   for(std::size_t i=0;i<n;i++)
6781     if(std::find(types.begin(),types.end(),(INTERP_KERNEL::NormalizedCellType)code[3*i])==types.end())
6782       {
6783         types.push_back((INTERP_KERNEL::NormalizedCellType)code[3*i]);
6784         nb+=code[3*i+1];
6785         if(_types.find((INTERP_KERNEL::NormalizedCellType)code[3*i])==_types.end())
6786           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::checkTypeConsistencyAndContig : expected geo types not in this !");
6787         isNoPflUsed=isNoPflUsed && (code[3*i+2]==-1);
6788       }
6789   if(types.size()!=n)
6790     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::checkTypeConsistencyAndContig : code contains duplication of types in unstructured mesh !");
6791   if(isNoPflUsed)
6792     {
6793       if(!checkConsecutiveCellTypesAndOrder(&types[0],&types[0]+types.size()))
6794         throw INTERP_KERNEL::Exception("MEDCouplingUMesh::checkTypeConsistencyAndContig : non contiguous type !");
6795       if(types.size()==_types.size())
6796         return 0;
6797     }
6798   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New();
6799   ret->alloc(nb,1);
6800   int *retPtr=ret->getPointer();
6801   const int *connI=_nodal_connec_index->getConstPointer();
6802   const int *conn=_nodal_connec->getConstPointer();
6803   int nbOfCells=getNumberOfCells();
6804   const int *i=connI;
6805   int kk=0;
6806   for(std::vector<INTERP_KERNEL::NormalizedCellType>::const_iterator it=types.begin();it!=types.end();it++,kk++)
6807     {
6808       i=std::find_if(i,connI+nbOfCells,ParaMEDMEMImpl::ConnReader2(conn,(int)(*it)));
6809       int offset=(int)std::distance(connI,i);
6810       const int *j=std::find_if(i+1,connI+nbOfCells,ParaMEDMEMImpl::ConnReader(conn,(int)(*it)));
6811       int nbOfCellsOfCurType=(int)std::distance(i,j);
6812       if(code[3*kk+2]==-1)
6813         for(int k=0;k<nbOfCellsOfCurType;k++)
6814           *retPtr++=k+offset;
6815       else
6816         {
6817           int idInIdsPerType=code[3*kk+2];
6818           if(idInIdsPerType>=0 && idInIdsPerType<(int)idsPerType.size())
6819             {
6820               const DataArrayInt *zePfl=idsPerType[idInIdsPerType];
6821               if(zePfl)
6822                 {
6823                   zePfl->checkAllocated();
6824                   if(zePfl->getNumberOfComponents()==1)
6825                     {
6826                       for(const int *k=zePfl->begin();k!=zePfl->end();k++,retPtr++)
6827                         {
6828                           if(*k>=0 && *k<nbOfCellsOfCurType)
6829                             *retPtr=(*k)+offset;
6830                           else
6831                             {
6832                               std::ostringstream oss; oss << "MEDCouplingUMesh::checkTypeConsistencyAndContig : the section " << kk << " points to the profile #" << idInIdsPerType;
6833                               oss << ", and this profile contains a value " << *k << " should be in [0," << nbOfCellsOfCurType << ") !";
6834                               throw INTERP_KERNEL::Exception(oss.str().c_str());
6835                             }
6836                         }
6837                     }
6838                   else
6839                     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::checkTypeConsistencyAndContig : presence of a profile with nb of compo != 1 !");
6840                 }
6841               else
6842                 throw INTERP_KERNEL::Exception("MEDCouplingUMesh::checkTypeConsistencyAndContig : presence of null profile !");
6843             }
6844           else
6845             {
6846               std::ostringstream oss; oss << "MEDCouplingUMesh::checkTypeConsistencyAndContig : at section " << kk << " of code it points to the array #" << idInIdsPerType;
6847               oss << " should be in [0," << idsPerType.size() << ") !";
6848               throw INTERP_KERNEL::Exception(oss.str().c_str());
6849             }
6850         }
6851       i=j;
6852     }
6853   return ret.retn();
6854 }
6855
6856 /*!
6857  * This method makes the hypothesis that \at this is sorted by type. If not an exception will be thrown.
6858  * This method is the opposite of MEDCouplingUMesh::checkTypeConsistencyAndContig method. Given a list of cells in \a profile it returns a list of sub-profiles sorted by geo type.
6859  * The result is put in the array \a idsPerType. In the returned parameter \a code, foreach i \a code[3*i+2] refers (if different from -1) to a location into the \a idsPerType.
6860  * This method has 1 input \a profile and 3 outputs \a code \a idsInPflPerType and \a idsPerType.
6861  * 
6862  * \param [out] code is a vector of size 3*n where n is the number of different geometric type in \a this \b reduced to the profile \a profile. \a code has exactly the same semantic than in MEDCouplingUMesh::checkTypeConsistencyAndContig method.
6863  * \param [out] idsInPflPerType is a vector of size of different geometric type in the subpart defined by \a profile of \a this ( equal to \a code.size()/3). For each i,
6864  *              \a idsInPflPerType[i] stores the tuple ids in \a profile that correspond to the geometric type code[3*i+0]
6865  * \param [out] idsPerType is a vector of size of different sub profiles needed to be defined to represent the profile \a profile for a given geometric type.
6866  *              This vector can be empty in case of all geometric type cells are fully covered in ascending in the given input \a profile.
6867  * \throw if \a profile has not exactly one component. It throws too, if \a profile contains some values not in [0,getNumberOfCells()) or if \a this is not fully defined
6868  */
6869 void MEDCouplingUMesh::splitProfilePerType(const DataArrayInt *profile, std::vector<int>& code, std::vector<DataArrayInt *>& idsInPflPerType, std::vector<DataArrayInt *>& idsPerType) const
6870 {
6871   if(!profile)
6872     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::splitProfilePerType : input profile is NULL !");
6873   if(profile->getNumberOfComponents()!=1)
6874     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::splitProfilePerType : input profile should have exactly one component !");
6875   checkConnectivityFullyDefined();
6876   const int *conn=_nodal_connec->getConstPointer();
6877   const int *connI=_nodal_connec_index->getConstPointer();
6878   int nbOfCells=getNumberOfCells();
6879   std::vector<INTERP_KERNEL::NormalizedCellType> types;
6880   std::vector<int> typeRangeVals(1);
6881   for(const int *i=connI;i!=connI+nbOfCells;)
6882     {
6883       INTERP_KERNEL::NormalizedCellType curType=(INTERP_KERNEL::NormalizedCellType)conn[*i];
6884       if(std::find(types.begin(),types.end(),curType)!=types.end())
6885         {
6886           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::splitProfilePerType : current mesh is not sorted by type !");
6887         }
6888       types.push_back(curType);
6889       i=std::find_if(i+1,connI+nbOfCells,ParaMEDMEMImpl::ConnReader(conn,(int)curType));
6890       typeRangeVals.push_back((int)std::distance(connI,i));
6891     }
6892   //
6893   DataArrayInt *castArr=0,*rankInsideCast=0,*castsPresent=0;
6894   profile->splitByValueRange(&typeRangeVals[0],&typeRangeVals[0]+typeRangeVals.size(),castArr,rankInsideCast,castsPresent);
6895   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp0=castArr;
6896   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp1=rankInsideCast;
6897   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp2=castsPresent;
6898   //
6899   int nbOfCastsFinal=castsPresent->getNumberOfTuples();
6900   code.resize(3*nbOfCastsFinal);
6901   std::vector< MEDCouplingAutoRefCountObjectPtr<DataArrayInt> > idsInPflPerType2;
6902   std::vector< MEDCouplingAutoRefCountObjectPtr<DataArrayInt> > idsPerType2;
6903   for(int i=0;i<nbOfCastsFinal;i++)
6904     {
6905       int castId=castsPresent->getIJ(i,0);
6906       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp3=castArr->getIdsEqual(castId);
6907       idsInPflPerType2.push_back(tmp3);
6908       code[3*i]=(int)types[castId];
6909       code[3*i+1]=tmp3->getNumberOfTuples();
6910       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp4=rankInsideCast->selectByTupleId(tmp3->getConstPointer(),tmp3->getConstPointer()+tmp3->getNumberOfTuples());
6911       if(tmp4->getNumberOfTuples()!=typeRangeVals[castId+1]-typeRangeVals[castId] || !tmp4->isIdentity())
6912         {
6913           tmp4->copyStringInfoFrom(*profile);
6914           idsPerType2.push_back(tmp4);
6915           code[3*i+2]=(int)idsPerType2.size()-1;
6916         }
6917       else
6918         {
6919           code[3*i+2]=-1;
6920         }
6921     }
6922   std::size_t sz2=idsInPflPerType2.size();
6923   idsInPflPerType.resize(sz2);
6924   for(std::size_t i=0;i<sz2;i++)
6925     {
6926       DataArrayInt *locDa=idsInPflPerType2[i];
6927       locDa->incrRef();
6928       idsInPflPerType[i]=locDa;
6929     }
6930   std::size_t sz=idsPerType2.size();
6931   idsPerType.resize(sz);
6932   for(std::size_t i=0;i<sz;i++)
6933     {
6934       DataArrayInt *locDa=idsPerType2[i];
6935       locDa->incrRef();
6936       idsPerType[i]=locDa;
6937     }
6938 }
6939
6940 /*!
6941  * This method is here too emulate the MEDMEM behaviour on BDC (buildDescendingConnectivity). Hoping this method becomes deprecated very soon.
6942  * This method make the assumption that \a this and 'nM1LevMesh' mesh lyies on same coords (same pointer) as MED and MEDMEM does.
6943  * The following equality should be verified 'nM1LevMesh->getMeshDimension()==this->getMeshDimension()-1'
6944  * This method returns 5+2 elements. 'desc', 'descIndx', 'revDesc', 'revDescIndx' and 'meshnM1' behaves exactly as ParaMEDMEM::MEDCouplingUMesh::buildDescendingConnectivity except the content as described after. The returned array specifies the n-1 mesh reordered by type as MEDMEM does. 'nM1LevMeshIds' contains the ids in returned 'meshnM1'. Finally 'meshnM1Old2New' contains numbering old2new that is to say the cell #k in coarse 'nM1LevMesh' will have the number ret[k] in returned mesh 'nM1LevMesh' MEDMEM reordered.
6945  */
6946 MEDCouplingUMesh *MEDCouplingUMesh::emulateMEDMEMBDC(const MEDCouplingUMesh *nM1LevMesh, DataArrayInt *desc, DataArrayInt *descIndx, DataArrayInt *&revDesc, DataArrayInt *&revDescIndx, DataArrayInt *& nM1LevMeshIds, DataArrayInt *&meshnM1Old2New) const
6947 {
6948   checkFullyDefined();
6949   nM1LevMesh->checkFullyDefined();
6950   if(getMeshDimension()-1!=nM1LevMesh->getMeshDimension())
6951     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::emulateMEDMEMBDC : The mesh passed as first argument should have a meshDim equal to this->getMeshDimension()-1 !" );
6952   if(_coords!=nM1LevMesh->getCoords())
6953     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::emulateMEDMEMBDC : 'this' and mesh in first argument should share the same coords : Use tryToShareSameCoords method !");
6954   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp0=DataArrayInt::New();
6955   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp1=DataArrayInt::New();
6956   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret1=buildDescendingConnectivity(desc,descIndx,tmp0,tmp1);
6957   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret0=ret1->sortCellsInMEDFileFrmt();
6958   desc->transformWithIndArr(ret0->getConstPointer(),ret0->getConstPointer()+ret0->getNbOfElems());
6959   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> tmp=MEDCouplingUMesh::New();
6960   tmp->setConnectivity(tmp0,tmp1);
6961   tmp->renumberCells(ret0->getConstPointer(),false);
6962   revDesc=tmp->getNodalConnectivity();
6963   revDescIndx=tmp->getNodalConnectivityIndex();
6964   DataArrayInt *ret=0;
6965   if(!ret1->areCellsIncludedIn(nM1LevMesh,2,ret))
6966     {
6967       int tmp2;
6968       ret->getMaxValue(tmp2);
6969       ret->decrRef();
6970       std::ostringstream oss; oss << "MEDCouplingUMesh::emulateMEDMEMBDC : input N-1 mesh present a cell not in descending mesh ... Id of cell is " << tmp2 << " !";
6971       throw INTERP_KERNEL::Exception(oss.str().c_str());
6972     }
6973   nM1LevMeshIds=ret;
6974   //
6975   revDesc->incrRef();
6976   revDescIndx->incrRef();
6977   ret1->incrRef();
6978   ret0->incrRef();
6979   meshnM1Old2New=ret0;
6980   return ret1;
6981 }
6982
6983 /*!
6984  * Permutes the nodal connectivity arrays so that the cells are sorted by type, which is
6985  * necessary for writing the mesh to MED file. Additionally returns a permutation array
6986  * in "Old to New" mode.
6987  *  \return DataArrayInt * - a new instance of DataArrayInt. The caller is to delete
6988  *          this array using decrRef() as it is no more needed.
6989  *  \throw If the nodal connectivity of cells is not defined.
6990  */
6991 DataArrayInt *MEDCouplingUMesh::sortCellsInMEDFileFrmt()
6992 {
6993   checkConnectivityFullyDefined();
6994   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=getRenumArrForMEDFileFrmt();
6995   renumberCells(ret->getConstPointer(),false);
6996   return ret.retn();
6997 }
6998
6999 /*!
7000  * This methods checks that cells are sorted by their types.
7001  * This method makes asumption (no check) that connectivity is correctly set before calling.
7002  */
7003 bool MEDCouplingUMesh::checkConsecutiveCellTypes() const
7004 {
7005   checkFullyDefined();
7006   const int *conn=_nodal_connec->getConstPointer();
7007   const int *connI=_nodal_connec_index->getConstPointer();
7008   int nbOfCells=getNumberOfCells();
7009   std::set<INTERP_KERNEL::NormalizedCellType> types;
7010   for(const int *i=connI;i!=connI+nbOfCells;)
7011     {
7012       INTERP_KERNEL::NormalizedCellType curType=(INTERP_KERNEL::NormalizedCellType)conn[*i];
7013       if(types.find(curType)!=types.end())
7014         return false;
7015       types.insert(curType);
7016       i=std::find_if(i+1,connI+nbOfCells,ParaMEDMEMImpl::ConnReader(conn,(int)curType));
7017     }
7018   return true;
7019 }
7020
7021 /*!
7022  * This method is a specialization of MEDCouplingUMesh::checkConsecutiveCellTypesAndOrder method that is called here.
7023  * The geometric type order is specified by MED file.
7024  * 
7025  * \sa  MEDCouplingUMesh::checkConsecutiveCellTypesAndOrder
7026  */
7027 bool MEDCouplingUMesh::checkConsecutiveCellTypesForMEDFileFrmt() const
7028 {
7029   return checkConsecutiveCellTypesAndOrder(MEDMEM_ORDER,MEDMEM_ORDER+N_MEDMEM_ORDER);
7030 }
7031
7032 /*!
7033  * This method performs the same job as checkConsecutiveCellTypes except that the order of types sequence is analyzed to check
7034  * that the order is specified in array defined by [ \a orderBg , \a orderEnd ).
7035  * If there is some geo types in \a this \b NOT in [ \a orderBg, \a orderEnd ) it is OK (return true) if contiguous.
7036  * If there is some geo types in [ \a orderBg, \a orderEnd ) \b NOT in \a this it is OK too (return true) if contiguous.
7037  */
7038 bool MEDCouplingUMesh::checkConsecutiveCellTypesAndOrder(const INTERP_KERNEL::NormalizedCellType *orderBg, const INTERP_KERNEL::NormalizedCellType *orderEnd) const
7039 {
7040   checkFullyDefined();
7041   const int *conn=_nodal_connec->getConstPointer();
7042   const int *connI=_nodal_connec_index->getConstPointer();
7043   int nbOfCells=getNumberOfCells();
7044   if(nbOfCells==0)
7045     return true;
7046   int lastPos=-1;
7047   std::set<INTERP_KERNEL::NormalizedCellType> sg;
7048   for(const int *i=connI;i!=connI+nbOfCells;)
7049     {
7050       INTERP_KERNEL::NormalizedCellType curType=(INTERP_KERNEL::NormalizedCellType)conn[*i];
7051       const INTERP_KERNEL::NormalizedCellType *isTypeExists=std::find(orderBg,orderEnd,curType);
7052       if(isTypeExists!=orderEnd)
7053         {
7054           int pos=(int)std::distance(orderBg,isTypeExists);
7055           if(pos<=lastPos)
7056             return false;
7057           lastPos=pos;
7058           i=std::find_if(i+1,connI+nbOfCells,ParaMEDMEMImpl::ConnReader(conn,(int)curType));
7059         }
7060       else
7061         {
7062           if(sg.find(curType)==sg.end())
7063             {
7064               i=std::find_if(i+1,connI+nbOfCells,ParaMEDMEMImpl::ConnReader(conn,(int)curType));
7065               sg.insert(curType);
7066             }
7067           else
7068             return false;
7069         }
7070     }
7071   return true;
7072 }
7073
7074 /*!
7075  * This method returns 2 newly allocated DataArrayInt instances. The first is an array of size 'this->getNumberOfCells()' with one component,
7076  * that tells for each cell the pos of its type in the array on type given in input parameter. The 2nd output parameter is an array with the same
7077  * number of tuples than input type array and with one component. This 2nd output array gives type by type the number of occurence of type in 'this'.
7078  */
7079 DataArrayInt *MEDCouplingUMesh::getLevArrPerCellTypes(const INTERP_KERNEL::NormalizedCellType *orderBg, const INTERP_KERNEL::NormalizedCellType *orderEnd, DataArrayInt *&nbPerType) const
7080 {
7081   checkConnectivityFullyDefined();
7082   int nbOfCells=getNumberOfCells();
7083   const int *conn=_nodal_connec->getConstPointer();
7084   const int *connI=_nodal_connec_index->getConstPointer();
7085   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmpa=DataArrayInt::New();
7086   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmpb=DataArrayInt::New();
7087   tmpa->alloc(nbOfCells,1);
7088   tmpb->alloc((int)std::distance(orderBg,orderEnd),1);
7089   tmpb->fillWithZero();
7090   int *tmp=tmpa->getPointer();
7091   int *tmp2=tmpb->getPointer();
7092   for(const int *i=connI;i!=connI+nbOfCells;i++)
7093     {
7094       const INTERP_KERNEL::NormalizedCellType *where=std::find(orderBg,orderEnd,(INTERP_KERNEL::NormalizedCellType)conn[*i]);
7095       if(where!=orderEnd)
7096         {
7097           int pos=(int)std::distance(orderBg,where);
7098           tmp2[pos]++;
7099           tmp[std::distance(connI,i)]=pos;
7100         }
7101       else
7102         {
7103           const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[*i]);
7104           std::ostringstream oss; oss << "MEDCouplingUMesh::getLevArrPerCellTypes : Cell #" << std::distance(connI,i);
7105           oss << " has a type " << cm.getRepr() << " not in input array of type !";
7106           throw INTERP_KERNEL::Exception(oss.str().c_str());
7107         }
7108     }
7109   nbPerType=tmpb.retn();
7110   return tmpa.retn();
7111 }
7112
7113 /*!
7114  * This method behaves exactly as MEDCouplingUMesh::getRenumArrForConsecutiveCellTypesSpec but the order is those defined in MED file spec.
7115  *
7116  * \return a new object containing the old to new correspondance.
7117  *
7118  * \sa MEDCouplingUMesh::getRenumArrForConsecutiveCellTypesSpec, MEDCouplingUMesh::sortCellsInMEDFileFrmt.
7119  */
7120 DataArrayInt *MEDCouplingUMesh::getRenumArrForMEDFileFrmt() const
7121 {
7122   return getRenumArrForConsecutiveCellTypesSpec(MEDMEM_ORDER,MEDMEM_ORDER+N_MEDMEM_ORDER);
7123 }
7124
7125 /*!
7126  * This method is similar to method MEDCouplingUMesh::rearrange2ConsecutiveCellTypes except that the type order is specfied by [ \a orderBg , \a orderEnd ) (as MEDCouplingUMesh::checkConsecutiveCellTypesAndOrder method) and that this method is \b const and performs \b NO permutation in \a this.
7127  * This method returns an array of size getNumberOfCells() that gives a renumber array old2New that can be used as input of MEDCouplingMesh::renumberCells.
7128  * The mesh after this call to MEDCouplingMesh::renumberCells will pass the test of MEDCouplingUMesh::checkConsecutiveCellTypesAndOrder with the same inputs.
7129  * The returned array minimizes the permutations that is to say the order of cells inside same geometric type remains the same.
7130  */
7131 DataArrayInt *MEDCouplingUMesh::getRenumArrForConsecutiveCellTypesSpec(const INTERP_KERNEL::NormalizedCellType *orderBg, const INTERP_KERNEL::NormalizedCellType *orderEnd) const
7132 {
7133   DataArrayInt *nbPerType=0;
7134   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmpa=getLevArrPerCellTypes(orderBg,orderEnd,nbPerType);
7135   nbPerType->decrRef();
7136   return tmpa->buildPermArrPerLevel();
7137 }
7138
7139 /*!
7140  * This method reorganize the cells of \a this so that the cells with same geometric types are put together.
7141  * The number of cells remains unchanged after the call of this method.
7142  * This method tries to minimizes the number of needed permutations. So, this method behaves not exactly as
7143  * MEDCouplingUMesh::sortCellsInMEDFileFrmt.
7144  *
7145  * \return the array giving the correspondance old to new.
7146  */
7147 DataArrayInt *MEDCouplingUMesh::rearrange2ConsecutiveCellTypes()
7148 {
7149   checkFullyDefined();
7150   computeTypes();
7151   const int *conn=_nodal_connec->getConstPointer();
7152   const int *connI=_nodal_connec_index->getConstPointer();
7153   int nbOfCells=getNumberOfCells();
7154   std::vector<INTERP_KERNEL::NormalizedCellType> types;
7155   for(const int *i=connI;i!=connI+nbOfCells && (types.size()!=_types.size());)
7156     if(std::find(types.begin(),types.end(),(INTERP_KERNEL::NormalizedCellType)conn[*i])==types.end())
7157       {
7158         INTERP_KERNEL::NormalizedCellType curType=(INTERP_KERNEL::NormalizedCellType)conn[*i];
7159         types.push_back(curType);
7160         for(i++;i!=connI+nbOfCells && (INTERP_KERNEL::NormalizedCellType)conn[*i]==curType;i++);
7161       }
7162   DataArrayInt *ret=DataArrayInt::New();
7163   ret->alloc(nbOfCells,1);
7164   int *retPtr=ret->getPointer();
7165   std::fill(retPtr,retPtr+nbOfCells,-1);
7166   int newCellId=0;
7167   for(std::vector<INTERP_KERNEL::NormalizedCellType>::const_iterator iter=types.begin();iter!=types.end();iter++)
7168     {
7169       for(const int *i=connI;i!=connI+nbOfCells;i++)
7170         if((INTERP_KERNEL::NormalizedCellType)conn[*i]==(*iter))
7171           retPtr[std::distance(connI,i)]=newCellId++;
7172     }
7173   renumberCells(retPtr,false);
7174   return ret;
7175 }
7176
7177 /*!
7178  * This method splits \a this into as mush as untructured meshes that consecutive set of same type cells.
7179  * So this method has typically a sense if MEDCouplingUMesh::checkConsecutiveCellTypes has a sense.
7180  * This method makes asumption that connectivity is correctly set before calling.
7181  */
7182 std::vector<MEDCouplingUMesh *> MEDCouplingUMesh::splitByType() const
7183 {
7184   checkConnectivityFullyDefined();
7185   const int *conn=_nodal_connec->getConstPointer();
7186   const int *connI=_nodal_connec_index->getConstPointer();
7187   int nbOfCells=getNumberOfCells();
7188   std::vector<MEDCouplingUMesh *> ret;
7189   for(const int *i=connI;i!=connI+nbOfCells;)
7190     {
7191       INTERP_KERNEL::NormalizedCellType curType=(INTERP_KERNEL::NormalizedCellType)conn[*i];
7192       int beginCellId=(int)std::distance(connI,i);
7193       i=std::find_if(i+1,connI+nbOfCells,ParaMEDMEMImpl::ConnReader(conn,(int)curType));
7194       int endCellId=(int)std::distance(connI,i);
7195       int sz=endCellId-beginCellId;
7196       int *cells=new int[sz];
7197       for(int j=0;j<sz;j++)
7198         cells[j]=beginCellId+j;
7199       MEDCouplingUMesh *m=(MEDCouplingUMesh *)buildPartOfMySelf(cells,cells+sz,true);
7200       delete [] cells;
7201       ret.push_back(m);
7202     }
7203   return ret;
7204 }
7205
7206 /*!
7207  * This method performs the opposite operation than those in MEDCoupling1SGTUMesh::buildUnstructured.
7208  * If \a this is a single geometric type unstructured mesh, it will be converted into a more compact data structure,
7209  * MEDCoupling1GTUMesh instance. The returned instance will aggregate the same DataArrayDouble instance of coordinates than \a this.
7210  *
7211  * \return a newly allocated instance, that the caller must manage.
7212  * \throw If \a this contains more than one geometric type.
7213  * \throw If the nodal connectivity of \a this is not fully defined.
7214  * \throw If the internal data is not coherent.
7215  */
7216 MEDCoupling1GTUMesh *MEDCouplingUMesh::convertIntoSingleGeoTypeMesh() const
7217 {
7218   checkConnectivityFullyDefined();
7219   if(_types.size()!=1)
7220     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertIntoSingleGeoTypeMesh : current mesh does not contain exactly one geometric type !");
7221   INTERP_KERNEL::NormalizedCellType typ=*_types.begin();
7222   MEDCouplingAutoRefCountObjectPtr<MEDCoupling1GTUMesh> ret=MEDCoupling1GTUMesh::New(getName(),typ);
7223   ret->setCoords(getCoords());
7224   MEDCoupling1SGTUMesh *retC=dynamic_cast<MEDCoupling1SGTUMesh *>((MEDCoupling1GTUMesh*)ret);
7225   if(retC)
7226     {
7227       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> c=convertNodalConnectivityToStaticGeoTypeMesh();
7228       retC->setNodalConnectivity(c);
7229     }
7230   else
7231     {
7232       MEDCoupling1DGTUMesh *retD=dynamic_cast<MEDCoupling1DGTUMesh *>((MEDCoupling1GTUMesh*)ret);
7233       if(!retD)
7234         throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertIntoSingleGeoTypeMesh : Internal error !");
7235       DataArrayInt *c=0,*ci=0;
7236       convertNodalConnectivityToDynamicGeoTypeMesh(c,ci);
7237       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> cs(c),cis(ci);
7238       retD->setNodalConnectivity(cs,cis);
7239     }
7240   return ret.retn();
7241 }
7242
7243 DataArrayInt *MEDCouplingUMesh::convertNodalConnectivityToStaticGeoTypeMesh() const
7244 {
7245   checkConnectivityFullyDefined();
7246   if(_types.size()!=1)
7247     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertNodalConnectivityToStaticGeoTypeMesh : current mesh does not contain exactly one geometric type !");
7248   INTERP_KERNEL::NormalizedCellType typ=*_types.begin();
7249   const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(typ);
7250   if(cm.isDynamic())
7251     {
7252       std::ostringstream oss; oss << "MEDCouplingUMesh::convertNodalConnectivityToStaticGeoTypeMesh : this contains a single geo type (" << cm.getRepr() << ") but ";
7253       oss << "this type is dynamic ! Only static geometric type is possible for that type ! call convertNodalConnectivityToDynamicGeoTypeMesh instead !";
7254       throw INTERP_KERNEL::Exception(oss.str().c_str());
7255     }
7256   int nbCells=getNumberOfCells();
7257   int typi=(int)typ;
7258   int nbNodesPerCell=(int)cm.getNumberOfNodes();
7259   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> connOut=DataArrayInt::New(); connOut->alloc(nbCells*nbNodesPerCell,1);
7260   int *outPtr=connOut->getPointer();
7261   const int *conn=_nodal_connec->begin();
7262   const int *connI=_nodal_connec_index->begin();
7263   nbNodesPerCell++;
7264   for(int i=0;i<nbCells;i++,connI++)
7265     {
7266       if(conn[connI[0]]==typi && connI[1]-connI[0]==nbNodesPerCell)
7267         outPtr=std::copy(conn+connI[0]+1,conn+connI[1],outPtr);
7268       else
7269         {
7270           std::ostringstream oss; oss << "MEDCouplingUMesh::convertNodalConnectivityToStaticGeoTypeMesh : there something wrong in cell #" << i << " ! The type of cell is not those expected, or the length of nodal connectivity is not those expected (" << nbNodesPerCell-1 << ") !";
7271           throw INTERP_KERNEL::Exception(oss.str().c_str());
7272         }
7273     }
7274   return connOut.retn();
7275 }
7276
7277 void MEDCouplingUMesh::convertNodalConnectivityToDynamicGeoTypeMesh(DataArrayInt *&nodalConn, DataArrayInt *&nodalConnIndex) const
7278 {
7279   static const char msg0[]="MEDCouplingUMesh::convertNodalConnectivityToDynamicGeoTypeMesh : nodal connectivity in this are invalid ! Call checkCoherency2 !";
7280   checkConnectivityFullyDefined();
7281   if(_types.size()!=1)
7282     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertNodalConnectivityToDynamicGeoTypeMesh : current mesh does not contain exactly one geometric type !");
7283   int nbCells=getNumberOfCells(),lgth=_nodal_connec->getNumberOfTuples();
7284   if(lgth<nbCells)
7285     throw INTERP_KERNEL::Exception(msg0);
7286   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> c(DataArrayInt::New()),ci(DataArrayInt::New());
7287   c->alloc(lgth-nbCells,1); ci->alloc(nbCells+1,1);
7288   int *cp(c->getPointer()),*cip(ci->getPointer());
7289   const int *incp(_nodal_connec->begin()),*incip(_nodal_connec_index->begin());
7290   cip[0]=0;
7291   for(int i=0;i<nbCells;i++,cip++,incip++)
7292     {
7293       int strt(incip[0]+1),stop(incip[1]);//+1 to skip geo type
7294       int delta(stop-strt);
7295       if(delta>=1)
7296         {
7297           if((strt>=0 && strt<lgth) && (stop>=0 && stop<=lgth))
7298             cp=std::copy(incp+strt,incp+stop,cp);
7299           else
7300             throw INTERP_KERNEL::Exception(msg0);
7301         }
7302       else
7303         throw INTERP_KERNEL::Exception(msg0);
7304       cip[1]=cip[0]+delta;
7305     }
7306   nodalConn=c.retn(); nodalConnIndex=ci.retn();
7307 }
7308
7309 /*!
7310  * This method takes in input a vector of MEDCouplingUMesh instances lying on the same coordinates with same mesh dimensions.
7311  * Each mesh in \b ms must be sorted by type with the same order (typically using MEDCouplingUMesh::sortCellsInMEDFileFrmt).
7312  * This method is particulary useful for MED file interaction. It allows to aggregate several meshes and keeping the type sorting
7313  * and the track of the permutation by chunk of same geotype cells to retrieve it. The traditional formats old2new and new2old
7314  * are not used here to avoid the build of big permutation array.
7315  *
7316  * \param [in] ms meshes with same mesh dimension lying on the same coords and sorted by type following de the same geometric type order than
7317  *                those specified in MEDCouplingUMesh::sortCellsInMEDFileFrmt method.
7318  * \param [out] szOfCellGrpOfSameType is a newly allocated DataArrayInt instance whose number of tuples is equal to the number of chunks of same geotype
7319  *              in all meshes in \b ms. The accumulation of all values of this array is equal to the number of cells of returned mesh.
7320  * \param [out] idInMsOfCellGrpOfSameType is a newly allocated DataArrayInt instance having the same size than \b szOfCellGrpOfSameType. This
7321  *              output array gives for each chunck of same type the corresponding mesh id in \b ms.
7322  * \return A newly allocated unstructured mesh that is the result of the aggregation on same coords of all meshes in \b ms. This returned mesh
7323  *         is sorted by type following the geo cell types order of MEDCouplingUMesh::sortCellsInMEDFileFrmt method.
7324  */
7325 MEDCouplingUMesh *MEDCouplingUMesh::AggregateSortedByTypeMeshesOnSameCoords(const std::vector<const MEDCouplingUMesh *>& ms,
7326                                                                             DataArrayInt *&szOfCellGrpOfSameType,
7327                                                                             DataArrayInt *&idInMsOfCellGrpOfSameType)
7328 {
7329   std::vector<const MEDCouplingUMesh *> ms2;
7330   for(std::vector<const MEDCouplingUMesh *>::const_iterator it=ms.begin();it!=ms.end();it++)
7331     if(*it)
7332       {
7333         (*it)->checkConnectivityFullyDefined();
7334         ms2.push_back(*it);
7335       }
7336   if(ms2.empty())
7337     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::AggregateSortedByTypeMeshesOnSameCoords : input vector is empty !");
7338   const DataArrayDouble *refCoo=ms2[0]->getCoords();
7339   int meshDim=ms2[0]->getMeshDimension();
7340   std::vector<const MEDCouplingUMesh *> m1ssm;
7341   std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> > m1ssmAuto;
7342   //
7343   std::vector<const MEDCouplingUMesh *> m1ssmSingle;
7344   std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> > m1ssmSingleAuto;
7345   int fake=0,rk=0;
7346   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret1(DataArrayInt::New()),ret2(DataArrayInt::New());
7347   ret1->alloc(0,1); ret2->alloc(0,1);
7348   for(std::vector<const MEDCouplingUMesh *>::const_iterator it=ms2.begin();it!=ms2.end();it++,rk++)
7349     {
7350       if(meshDim!=(*it)->getMeshDimension())
7351         throw INTERP_KERNEL::Exception("MEDCouplingUMesh::AggregateSortedByTypeMeshesOnSameCoords : meshdims mismatch !");
7352       if(refCoo!=(*it)->getCoords())
7353         throw INTERP_KERNEL::Exception("MEDCouplingUMesh::AggregateSortedByTypeMeshesOnSameCoords : meshes are not shared by a single coordinates coords !");
7354       std::vector<MEDCouplingUMesh *> sp=(*it)->splitByType();
7355       std::copy(sp.begin(),sp.end(),std::back_insert_iterator< std::vector<const MEDCouplingUMesh *> >(m1ssm));
7356       std::copy(sp.begin(),sp.end(),std::back_insert_iterator< std::vector<MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> > >(m1ssmAuto));
7357       for(std::vector<MEDCouplingUMesh *>::const_iterator it2=sp.begin();it2!=sp.end();it2++)
7358         {
7359           MEDCouplingUMesh *singleCell=static_cast<MEDCouplingUMesh *>((*it2)->buildPartOfMySelf(&fake,&fake+1,true));
7360           m1ssmSingleAuto.push_back(singleCell);
7361           m1ssmSingle.push_back(singleCell);
7362           ret1->pushBackSilent((*it2)->getNumberOfCells()); ret2->pushBackSilent(rk);
7363         }
7364     }
7365   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m1ssmSingle2=MEDCouplingUMesh::MergeUMeshesOnSameCoords(m1ssmSingle);
7366   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> renum=m1ssmSingle2->sortCellsInMEDFileFrmt();
7367   std::vector<const MEDCouplingUMesh *> m1ssmfinal(m1ssm.size());
7368   for(std::size_t i=0;i<m1ssm.size();i++)
7369     m1ssmfinal[renum->getIJ(i,0)]=m1ssm[i];
7370   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret0=MEDCouplingUMesh::MergeUMeshesOnSameCoords(m1ssmfinal);
7371   szOfCellGrpOfSameType=ret1->renumber(renum->getConstPointer());
7372   idInMsOfCellGrpOfSameType=ret2->renumber(renum->getConstPointer());
7373   return ret0.retn();
7374 }
7375
7376 /*!
7377  * This method returns a newly created DataArrayInt instance.
7378  * This method retrieves cell ids in [ \a begin, \a end ) that have the type \a type.
7379  */
7380 DataArrayInt *MEDCouplingUMesh::keepCellIdsByType(INTERP_KERNEL::NormalizedCellType type, const int *begin, const int *end) const
7381 {
7382   checkFullyDefined();
7383   const int *conn=_nodal_connec->getConstPointer();
7384   const int *connIndex=_nodal_connec_index->getConstPointer();
7385   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret(DataArrayInt::New()); ret->alloc(0,1);
7386   for(const int *w=begin;w!=end;w++)
7387     if((INTERP_KERNEL::NormalizedCellType)conn[connIndex[*w]]==type)
7388       ret->pushBackSilent(*w);
7389   return ret.retn();
7390 }
7391
7392 /*!
7393  * This method makes the assumption that da->getNumberOfTuples()<this->getNumberOfCells(). This method makes the assumption that ids contained in 'da'
7394  * are in [0:getNumberOfCells())
7395  */
7396 DataArrayInt *MEDCouplingUMesh::convertCellArrayPerGeoType(const DataArrayInt *da) const
7397 {
7398   checkFullyDefined();
7399   const int *conn=_nodal_connec->getConstPointer();
7400   const int *connI=_nodal_connec_index->getConstPointer();
7401   int nbOfCells=getNumberOfCells();
7402   std::set<INTERP_KERNEL::NormalizedCellType> types(getAllGeoTypes());
7403   int *tmp=new int[nbOfCells];
7404   for(std::set<INTERP_KERNEL::NormalizedCellType>::const_iterator iter=types.begin();iter!=types.end();iter++)
7405     {
7406       int j=0;
7407       for(const int *i=connI;i!=connI+nbOfCells;i++)
7408         if((INTERP_KERNEL::NormalizedCellType)conn[*i]==(*iter))
7409           tmp[std::distance(connI,i)]=j++;
7410     }
7411   DataArrayInt *ret=DataArrayInt::New();
7412   ret->alloc(da->getNumberOfTuples(),da->getNumberOfComponents());
7413   ret->copyStringInfoFrom(*da);
7414   int *retPtr=ret->getPointer();
7415   const int *daPtr=da->getConstPointer();
7416   int nbOfElems=da->getNbOfElems();
7417   for(int k=0;k<nbOfElems;k++)
7418     retPtr[k]=tmp[daPtr[k]];
7419   delete [] tmp;
7420   return ret;
7421 }
7422
7423 /*!
7424  * This method reduced number of cells of this by keeping cells whose type is different from 'type' and if type=='type'
7425  * This method \b works \b for mesh sorted by type.
7426  * cells whose ids is in 'idsPerGeoType' array.
7427  * This method conserves coords and name of mesh.
7428  */
7429 MEDCouplingUMesh *MEDCouplingUMesh::keepSpecifiedCells(INTERP_KERNEL::NormalizedCellType type, const int *idsPerGeoTypeBg, const int *idsPerGeoTypeEnd) const
7430 {
7431   std::vector<int> code=getDistributionOfTypes();
7432   std::size_t nOfTypesInThis=code.size()/3;
7433   int sz=0,szOfType=0;
7434   for(std::size_t i=0;i<nOfTypesInThis;i++)
7435     {
7436       if(code[3*i]!=type)
7437         sz+=code[3*i+1];
7438       else
7439         szOfType=code[3*i+1];
7440     }
7441   for(const int *work=idsPerGeoTypeBg;work!=idsPerGeoTypeEnd;work++)
7442     if(*work<0 || *work>=szOfType)
7443       {
7444         std::ostringstream oss; oss << "MEDCouplingUMesh::keepSpecifiedCells : Request on type " << type << " at place #" << std::distance(idsPerGeoTypeBg,work) << " value " << *work;
7445         oss << ". It should be in [0," << szOfType << ") !";
7446         throw INTERP_KERNEL::Exception(oss.str().c_str());
7447       }
7448   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> idsTokeep=DataArrayInt::New(); idsTokeep->alloc(sz+(int)std::distance(idsPerGeoTypeBg,idsPerGeoTypeEnd),1);
7449   int *idsPtr=idsTokeep->getPointer();
7450   int offset=0;
7451   for(std::size_t i=0;i<nOfTypesInThis;i++)
7452     {
7453       if(code[3*i]!=type)
7454         for(int j=0;j<code[3*i+1];j++)
7455           *idsPtr++=offset+j;
7456       else
7457         idsPtr=std::transform(idsPerGeoTypeBg,idsPerGeoTypeEnd,idsPtr,std::bind2nd(std::plus<int>(),offset));
7458       offset+=code[3*i+1];
7459     }
7460   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret=static_cast<MEDCouplingUMesh *>(buildPartOfMySelf(idsTokeep->begin(),idsTokeep->end(),true));
7461   ret->copyTinyInfoFrom(this);
7462   return ret.retn();
7463 }
7464
7465 /*!
7466  * This method returns a vector of size 'this->getNumberOfCells()'.
7467  * This method retrieves for each cell in \a this if it is linear (false) or quadratic(true).
7468  */
7469 std::vector<bool> MEDCouplingUMesh::getQuadraticStatus() const
7470 {
7471   int ncell=getNumberOfCells();
7472   std::vector<bool> ret(ncell);
7473   const int *cI=getNodalConnectivityIndex()->getConstPointer();
7474   const int *c=getNodalConnectivity()->getConstPointer();
7475   for(int i=0;i<ncell;i++)
7476     {
7477       INTERP_KERNEL::NormalizedCellType typ=(INTERP_KERNEL::NormalizedCellType)c[cI[i]];
7478       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(typ);
7479       ret[i]=cm.isQuadratic();
7480     }
7481   return ret;
7482 }
7483
7484 /*!
7485  * Returns a newly created mesh (with ref count ==1) that contains merge of \a this and \a other.
7486  */
7487 MEDCouplingMesh *MEDCouplingUMesh::mergeMyselfWith(const MEDCouplingMesh *other) const
7488 {
7489   if(other->getType()!=UNSTRUCTURED)
7490     throw INTERP_KERNEL::Exception("Merge of umesh only available with umesh each other !");
7491   const MEDCouplingUMesh *otherC=static_cast<const MEDCouplingUMesh *>(other);
7492   return MergeUMeshes(this,otherC);
7493 }
7494
7495 /*!
7496  * Returns a new DataArrayDouble holding barycenters of all cells. The barycenter is
7497  * computed by averaging coordinates of cell nodes, so this method is not a right
7498  * choice for degnerated meshes (not well oriented, cells with measure close to zero).
7499  *  \return DataArrayDouble * - a new instance of DataArrayDouble, of size \a
7500  *          this->getNumberOfCells() tuples per \a this->getSpaceDimension()
7501  *          components. The caller is to delete this array using decrRef() as it is
7502  *          no more needed.
7503  *  \throw If the coordinates array is not set.
7504  *  \throw If the nodal connectivity of cells is not defined.
7505  *  \sa MEDCouplingUMesh::computeIsoBarycenterOfNodesPerCell
7506  */
7507 DataArrayDouble *MEDCouplingUMesh::getBarycenterAndOwner() const
7508 {
7509   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> ret=DataArrayDouble::New();
7510   int spaceDim=getSpaceDimension();
7511   int nbOfCells=getNumberOfCells();
7512   ret->alloc(nbOfCells,spaceDim);
7513   ret->copyStringInfoFrom(*getCoords());
7514   double *ptToFill=ret->getPointer();
7515   const int *nodal=_nodal_connec->getConstPointer();
7516   const int *nodalI=_nodal_connec_index->getConstPointer();
7517   const double *coor=_coords->getConstPointer();
7518   for(int i=0;i<nbOfCells;i++)
7519     {
7520       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)nodal[nodalI[i]];
7521       INTERP_KERNEL::computeBarycenter2<int,INTERP_KERNEL::ALL_C_MODE>(type,nodal+nodalI[i]+1,nodalI[i+1]-nodalI[i]-1,coor,spaceDim,ptToFill);
7522       ptToFill+=spaceDim;
7523     }
7524   return ret.retn();
7525 }
7526
7527 /*!
7528  * This method computes for each cell in \a this, the location of the iso barycenter of nodes constituting
7529  * the cell. Contrary to badly named MEDCouplingUMesh::getBarycenterAndOwner method that returns the center of inertia of the 
7530  * 
7531  * \return a newly allocated DataArrayDouble instance that the caller has to deal with. The returned 
7532  *          DataArrayDouble instance will have \c this->getNumberOfCells() tuples and \c this->getSpaceDimension() components.
7533  * 
7534  * \sa MEDCouplingUMesh::getBarycenterAndOwner
7535  * \throw If \a this is not fully defined (coordinates and connectivity)
7536  * \throw If there is presence in nodal connectivity in \a this of node ids not in [0, \c this->getNumberOfNodes() )
7537  */
7538 DataArrayDouble *MEDCouplingUMesh::computeIsoBarycenterOfNodesPerCell() const
7539 {
7540   checkFullyDefined();
7541   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> ret=DataArrayDouble::New();
7542   int spaceDim=getSpaceDimension();
7543   int nbOfCells=getNumberOfCells();
7544   int nbOfNodes=getNumberOfNodes();
7545   ret->alloc(nbOfCells,spaceDim);
7546   double *ptToFill=ret->getPointer();
7547   const int *nodal=_nodal_connec->getConstPointer();
7548   const int *nodalI=_nodal_connec_index->getConstPointer();
7549   const double *coor=_coords->getConstPointer();
7550   for(int i=0;i<nbOfCells;i++,ptToFill+=spaceDim)
7551     {
7552       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)nodal[nodalI[i]];
7553       std::fill(ptToFill,ptToFill+spaceDim,0.);
7554       if(type!=INTERP_KERNEL::NORM_POLYHED)
7555         {
7556           for(const int *conn=nodal+nodalI[i]+1;conn!=nodal+nodalI[i+1];conn++)
7557             {
7558               if(*conn>=0 && *conn<nbOfNodes)
7559                 std::transform(coor+spaceDim*conn[0],coor+spaceDim*(conn[0]+1),ptToFill,ptToFill,std::plus<double>());
7560               else
7561                 {
7562                   std::ostringstream oss; oss << "MEDCouplingUMesh::computeIsoBarycenterOfNodesPerCell : on cell #" << i << " presence of nodeId #" << *conn << " should be in [0," <<   nbOfNodes << ") !";
7563                   throw INTERP_KERNEL::Exception(oss.str().c_str());
7564                 }
7565             }
7566           int nbOfNodesInCell=nodalI[i+1]-nodalI[i]-1;
7567           if(nbOfNodesInCell>0)
7568             std::transform(ptToFill,ptToFill+spaceDim,ptToFill,std::bind2nd(std::multiplies<double>(),1./(double)nbOfNodesInCell));
7569           else
7570             {
7571               std::ostringstream oss; oss << "MEDCouplingUMesh::computeIsoBarycenterOfNodesPerCell : on cell #" << i << " presence of cell with no nodes !";
7572               throw INTERP_KERNEL::Exception(oss.str().c_str());
7573             }
7574         }
7575       else
7576         {
7577           std::set<int> s(nodal+nodalI[i]+1,nodal+nodalI[i+1]);
7578           s.erase(-1);
7579           for(std::set<int>::const_iterator it=s.begin();it!=s.end();it++)
7580             {
7581               if(*it>=0 && *it<nbOfNodes)
7582                 std::transform(coor+spaceDim*(*it),coor+spaceDim*((*it)+1),ptToFill,ptToFill,std::plus<double>());
7583               else
7584                 {
7585                   std::ostringstream oss; oss << "MEDCouplingUMesh::computeIsoBarycenterOfNodesPerCell : on cell polyhedron cell #" << i << " presence of nodeId #" << *it << " should be in [0," <<   nbOfNodes << ") !";
7586                   throw INTERP_KERNEL::Exception(oss.str().c_str());
7587                 }
7588             }
7589           if(!s.empty())
7590             std::transform(ptToFill,ptToFill+spaceDim,ptToFill,std::bind2nd(std::multiplies<double>(),1./(double)s.size()));
7591           else
7592             {
7593               std::ostringstream oss; oss << "MEDCouplingUMesh::computeIsoBarycenterOfNodesPerCell : on polyhedron cell #" << i << " there are no nodes !";
7594               throw INTERP_KERNEL::Exception(oss.str().c_str());
7595             }
7596         }
7597     }
7598   return ret.retn();
7599 }
7600
7601 /*!
7602  * Returns a new DataArrayDouble holding barycenters of specified cells. The
7603  * barycenter is computed by averaging coordinates of cell nodes. The cells to treat
7604  * are specified via an array of cell ids. 
7605  *  \warning Validity of the specified cell ids is not checked! 
7606  *           Valid range is [ 0, \a this->getNumberOfCells() ).
7607  *  \param [in] begin - an array of cell ids of interest.
7608  *  \param [in] end - the end of \a begin, i.e. a pointer to its (last+1)-th element.
7609  *  \return DataArrayDouble * - a new instance of DataArrayDouble, of size ( \a
7610  *          end - \a begin ) tuples per \a this->getSpaceDimension() components. The
7611  *          caller is to delete this array using decrRef() as it is no more needed. 
7612  *  \throw If the coordinates array is not set.
7613  *  \throw If the nodal connectivity of cells is not defined.
7614  *
7615  *  \if ENABLE_EXAMPLES
7616  *  \ref cpp_mcumesh_getPartBarycenterAndOwner "Here is a C++ example".<br>
7617  *  \ref  py_mcumesh_getPartBarycenterAndOwner "Here is a Python example".
7618  *  \endif
7619  */
7620 DataArrayDouble *MEDCouplingUMesh::getPartBarycenterAndOwner(const int *begin, const int *end) const
7621 {
7622   DataArrayDouble *ret=DataArrayDouble::New();
7623   int spaceDim=getSpaceDimension();
7624   int nbOfTuple=(int)std::distance(begin,end);
7625   ret->alloc(nbOfTuple,spaceDim);
7626   double *ptToFill=ret->getPointer();
7627   double *tmp=new double[spaceDim];
7628   const int *nodal=_nodal_connec->getConstPointer();
7629   const int *nodalI=_nodal_connec_index->getConstPointer();
7630   const double *coor=_coords->getConstPointer();
7631   for(const int *w=begin;w!=end;w++)
7632     {
7633       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)nodal[nodalI[*w]];
7634       INTERP_KERNEL::computeBarycenter2<int,INTERP_KERNEL::ALL_C_MODE>(type,nodal+nodalI[*w]+1,nodalI[*w+1]-nodalI[*w]-1,coor,spaceDim,ptToFill);
7635       ptToFill+=spaceDim;
7636     }
7637   delete [] tmp;
7638   return ret;
7639 }
7640
7641 /*!
7642  * Returns a DataArrayDouble instance giving for each cell in \a this the equation of plane given by "a*X+b*Y+c*Z+d=0".
7643  * So the returned instance will have 4 components and \c this->getNumberOfCells() tuples.
7644  * So this method expects that \a this has a spaceDimension equal to 3 and meshDimension equal to 2.
7645  * The computation of the plane equation is done using each time the 3 first nodes of 2D cells.
7646  * This method is useful to detect 2D cells in 3D space that are not coplanar.
7647  * 
7648  * \return DataArrayDouble * - a new instance of DataArrayDouble having 4 components and a number of tuples equal to number of cells in \a this.
7649  * \throw If spaceDim!=3 or meshDim!=2.
7650  * \throw If connectivity of \a this is invalid.
7651  * \throw If connectivity of a cell in \a this points to an invalid node.
7652  */
7653 DataArrayDouble *MEDCouplingUMesh::computePlaneEquationOf3DFaces() const
7654 {
7655   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> ret(DataArrayDouble::New());
7656   int nbOfCells(getNumberOfCells()),nbOfNodes(getNumberOfNodes());
7657   if(getSpaceDimension()!=3 || getMeshDimension()!=2)
7658     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::computePlaneEquationOf3DFaces : This method must be applied on a mesh having meshDimension equal 2 and a spaceDimension equal to 3 !");
7659   ret->alloc(nbOfCells,4);
7660   double *retPtr(ret->getPointer());
7661   const int *nodal(_nodal_connec->begin()),*nodalI(_nodal_connec_index->begin());
7662   const double *coor(_coords->begin());
7663   for(int i=0;i<nbOfCells;i++,nodalI++,retPtr+=4)
7664     {
7665       double matrix[16]={0,0,0,1,0,0,0,1,0,0,0,1,1,1,1,0},matrix2[16];
7666       if(nodalI[1]-nodalI[0]>=3)
7667         {
7668           for(int j=0;j<3;j++)
7669             {
7670               int nodeId(nodal[nodalI[0]+1+j]);
7671               if(nodeId>=0 && nodeId<nbOfNodes)
7672                 std::copy(coor+nodeId*3,coor+(nodeId+1)*3,matrix+4*j);
7673               else
7674                 {
7675                   std::ostringstream oss; oss << "MEDCouplingUMesh::computePlaneEquationOf3DFaces : invalid 2D cell #" << i << " ! This cell points to an invalid nodeId : " << nodeId << " !";
7676                   throw INTERP_KERNEL::Exception(oss.str().c_str());
7677                 }
7678             }
7679         }
7680       else
7681         {
7682           std::ostringstream oss; oss << "MEDCouplingUMesh::computePlaneEquationOf3DFaces : invalid 2D cell #" << i << " ! Must be constitued by more than 3 nodes !";
7683           throw INTERP_KERNEL::Exception(oss.str().c_str());
7684         }
7685       INTERP_KERNEL::inverseMatrix(matrix,4,matrix2);
7686       retPtr[0]=matrix2[3]; retPtr[1]=matrix2[7]; retPtr[2]=matrix2[11]; retPtr[3]=matrix2[15];
7687     }
7688   return ret.retn();
7689 }
7690
7691 /*!
7692  * This method expects as input a DataArrayDouble non nul instance 'da' that should be allocated. If not an exception is thrown.
7693  * 
7694  */
7695 MEDCouplingUMesh *MEDCouplingUMesh::Build0DMeshFromCoords(DataArrayDouble *da)
7696 {
7697   if(!da)
7698     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::Build0DMeshFromCoords : instance of DataArrayDouble must be not null !");
7699   da->checkAllocated();
7700   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret=MEDCouplingUMesh::New(da->getName(),0);
7701   ret->setCoords(da);
7702   int nbOfTuples=da->getNumberOfTuples();
7703   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> c=DataArrayInt::New();
7704   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> cI=DataArrayInt::New();
7705   c->alloc(2*nbOfTuples,1);
7706   cI->alloc(nbOfTuples+1,1);
7707   int *cp=c->getPointer();
7708   int *cip=cI->getPointer();
7709   *cip++=0;
7710   for(int i=0;i<nbOfTuples;i++)
7711     {
7712       *cp++=INTERP_KERNEL::NORM_POINT1;
7713       *cp++=i;
7714       *cip++=2*(i+1);
7715     }
7716   ret->setConnectivity(c,cI,true);
7717   return ret.retn();
7718 }
7719 /*!
7720  * Creates a new MEDCouplingUMesh by concatenating two given meshes of the same dimension.
7721  * Cells and nodes of
7722  * the first mesh precede cells and nodes of the second mesh within the result mesh.
7723  *  \param [in] mesh1 - the first mesh.
7724  *  \param [in] mesh2 - the second mesh.
7725  *  \return MEDCouplingUMesh * - the result mesh. It is a new instance of
7726  *          MEDCouplingUMesh. The caller is to delete this mesh using decrRef() as it
7727  *          is no more needed.
7728  *  \throw If \a mesh1 == NULL or \a mesh2 == NULL.
7729  *  \throw If the coordinates array is not set in none of the meshes.
7730  *  \throw If \a mesh1->getMeshDimension() < 0 or \a mesh2->getMeshDimension() < 0.
7731  *  \throw If \a mesh1->getMeshDimension() != \a mesh2->getMeshDimension().
7732  */
7733 MEDCouplingUMesh *MEDCouplingUMesh::MergeUMeshes(const MEDCouplingUMesh *mesh1, const MEDCouplingUMesh *mesh2)
7734 {
7735   std::vector<const MEDCouplingUMesh *> tmp(2);
7736   tmp[0]=const_cast<MEDCouplingUMesh *>(mesh1); tmp[1]=const_cast<MEDCouplingUMesh *>(mesh2);
7737   return MergeUMeshes(tmp);
7738 }
7739
7740 /*!
7741  * Creates a new MEDCouplingUMesh by concatenating all given meshes of the same dimension.
7742  * Cells and nodes of
7743  * the *i*-th mesh precede cells and nodes of the (*i*+1)-th mesh within the result mesh.
7744  *  \param [in] a - a vector of meshes (MEDCouplingUMesh) to concatenate.
7745  *  \return MEDCouplingUMesh * - the result mesh. It is a new instance of
7746  *          MEDCouplingUMesh. The caller is to delete this mesh using decrRef() as it
7747  *          is no more needed.
7748  *  \throw If \a a.size() == 0.
7749  *  \throw If \a a[ *i* ] == NULL.
7750  *  \throw If the coordinates array is not set in none of the meshes.
7751  *  \throw If \a a[ *i* ]->getMeshDimension() < 0.
7752  *  \throw If the meshes in \a a are of different dimension (getMeshDimension()).
7753  */
7754 MEDCouplingUMesh *MEDCouplingUMesh::MergeUMeshes(std::vector<const MEDCouplingUMesh *>& a)
7755 {
7756   std::size_t sz=a.size();
7757   if(sz==0)
7758     return MergeUMeshesLL(a);
7759   for(std::size_t ii=0;ii<sz;ii++)
7760     if(!a[ii])
7761       {
7762         std::ostringstream oss; oss << "MEDCouplingUMesh::MergeUMeshes : item #" << ii << " in input array of size "<< sz << " is empty !";
7763         throw INTERP_KERNEL::Exception(oss.str().c_str());
7764       }
7765   std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> > bb(sz);
7766   std::vector< const MEDCouplingUMesh * > aa(sz);
7767   int spaceDim=-3;
7768   for(std::size_t i=0;i<sz && spaceDim==-3;i++)
7769     {
7770       const MEDCouplingUMesh *cur=a[i];
7771       const DataArrayDouble *coo=cur->getCoords();
7772       if(coo)
7773         spaceDim=coo->getNumberOfComponents();
7774     }
7775   if(spaceDim==-3)
7776     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::MergeUMeshes : no spaceDim specified ! unable to perform merge !");
7777   for(std::size_t i=0;i<sz;i++)
7778     {
7779       bb[i]=a[i]->buildSetInstanceFromThis(spaceDim);
7780       aa[i]=bb[i];
7781     }
7782   return MergeUMeshesLL(aa);
7783 }
7784
7785 /// @cond INTERNAL
7786
7787 MEDCouplingUMesh *MEDCouplingUMesh::MergeUMeshesLL(std::vector<const MEDCouplingUMesh *>& a)
7788 {
7789   if(a.empty())
7790     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::MergeUMeshes : input array must be NON EMPTY !");
7791   std::vector<const MEDCouplingUMesh *>::const_iterator it=a.begin();
7792   int meshDim=(*it)->getMeshDimension();
7793   int nbOfCells=(*it)->getNumberOfCells();
7794   int meshLgth=(*it++)->getMeshLength();
7795   for(;it!=a.end();it++)
7796     {
7797       if(meshDim!=(*it)->getMeshDimension())
7798         throw INTERP_KERNEL::Exception("Mesh dimensions mismatches, MergeUMeshes impossible !");
7799       nbOfCells+=(*it)->getNumberOfCells();
7800       meshLgth+=(*it)->getMeshLength();
7801     }
7802   std::vector<const MEDCouplingPointSet *> aps(a.size());
7803   std::copy(a.begin(),a.end(),aps.begin());
7804   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> pts=MergeNodesArray(aps);
7805   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret=MEDCouplingUMesh::New("merge",meshDim);
7806   ret->setCoords(pts);
7807   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> c=DataArrayInt::New();
7808   c->alloc(meshLgth,1);
7809   int *cPtr=c->getPointer();
7810   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> cI=DataArrayInt::New();
7811   cI->alloc(nbOfCells+1,1);
7812   int *cIPtr=cI->getPointer();
7813   *cIPtr++=0;
7814   int offset=0;
7815   int offset2=0;
7816   for(it=a.begin();it!=a.end();it++)
7817     {
7818       int curNbOfCell=(*it)->getNumberOfCells();
7819       const int *curCI=(*it)->_nodal_connec_index->getConstPointer();
7820       const int *curC=(*it)->_nodal_connec->getConstPointer();
7821       cIPtr=std::transform(curCI+1,curCI+curNbOfCell+1,cIPtr,std::bind2nd(std::plus<int>(),offset));
7822       for(int j=0;j<curNbOfCell;j++)
7823         {
7824           const int *src=curC+curCI[j];
7825           *cPtr++=*src++;
7826           for(;src!=curC+curCI[j+1];src++,cPtr++)
7827             {
7828               if(*src!=-1)
7829                 *cPtr=*src+offset2;
7830               else
7831                 *cPtr=-1;
7832             }
7833         }
7834       offset+=curCI[curNbOfCell];
7835       offset2+=(*it)->getNumberOfNodes();
7836     }
7837   //
7838   ret->setConnectivity(c,cI,true);
7839   return ret.retn();
7840 }
7841
7842 /// @endcond
7843
7844 /*!
7845  * Creates a new MEDCouplingUMesh by concatenating cells of two given meshes of same
7846  * dimension and sharing the node coordinates array.
7847  * All cells of the first mesh precede all cells of the second mesh
7848  * within the result mesh. 
7849  *  \param [in] mesh1 - the first mesh.
7850  *  \param [in] mesh2 - the second mesh.
7851  *  \return MEDCouplingUMesh * - the result mesh. It is a new instance of
7852  *          MEDCouplingUMesh. The caller is to delete this mesh using decrRef() as it
7853  *          is no more needed.
7854  *  \throw If \a mesh1 == NULL or \a mesh2 == NULL.
7855  *  \throw If the meshes do not share the node coordinates array.
7856  *  \throw If \a mesh1->getMeshDimension() < 0 or \a mesh2->getMeshDimension() < 0.
7857  *  \throw If \a mesh1->getMeshDimension() != \a mesh2->getMeshDimension().
7858  */
7859 MEDCouplingUMesh *MEDCouplingUMesh::MergeUMeshesOnSameCoords(const MEDCouplingUMesh *mesh1, const MEDCouplingUMesh *mesh2)
7860 {
7861   std::vector<const MEDCouplingUMesh *> tmp(2);
7862   tmp[0]=mesh1; tmp[1]=mesh2;
7863   return MergeUMeshesOnSameCoords(tmp);
7864 }
7865
7866 /*!
7867  * Creates a new MEDCouplingUMesh by concatenating cells of all given meshes of same
7868  * dimension and sharing the node coordinates array.
7869  * All cells of the *i*-th mesh precede all cells of the
7870  * (*i*+1)-th mesh within the result mesh.
7871  *  \param [in] a - a vector of meshes (MEDCouplingUMesh) to concatenate.
7872  *  \return MEDCouplingUMesh * - the result mesh. It is a new instance of
7873  *          MEDCouplingUMesh. The caller is to delete this mesh using decrRef() as it
7874  *          is no more needed.
7875  *  \throw If \a a.size() == 0.
7876  *  \throw If \a a[ *i* ] == NULL.
7877  *  \throw If the meshes do not share the node coordinates array.
7878  *  \throw If \a a[ *i* ]->getMeshDimension() < 0.
7879  *  \throw If the meshes in \a a are of different dimension (getMeshDimension()).
7880  */
7881 MEDCouplingUMesh *MEDCouplingUMesh::MergeUMeshesOnSameCoords(const std::vector<const MEDCouplingUMesh *>& meshes)
7882 {
7883   if(meshes.empty())
7884     throw INTERP_KERNEL::Exception("meshes input parameter is expected to be non empty.");
7885   for(std::size_t ii=0;ii<meshes.size();ii++)
7886     if(!meshes[ii])
7887       {
7888         std::ostringstream oss; oss << "MEDCouplingUMesh::MergeUMeshesOnSameCoords : item #" << ii << " in input array of size "<< meshes.size() << " is empty !";
7889         throw INTERP_KERNEL::Exception(oss.str().c_str());
7890       }
7891   const DataArrayDouble *coords=meshes.front()->getCoords();
7892   int meshDim=meshes.front()->getMeshDimension();
7893   std::vector<const MEDCouplingUMesh *>::const_iterator iter=meshes.begin();
7894   int meshLgth=0;
7895   int meshIndexLgth=0;
7896   for(;iter!=meshes.end();iter++)
7897     {
7898       if(coords!=(*iter)->getCoords())
7899         throw INTERP_KERNEL::Exception("meshes does not share the same coords ! Try using tryToShareSameCoords method !");
7900       if(meshDim!=(*iter)->getMeshDimension())
7901         throw INTERP_KERNEL::Exception("Mesh dimensions mismatches, FuseUMeshesOnSameCoords impossible !");
7902       meshLgth+=(*iter)->getMeshLength();
7903       meshIndexLgth+=(*iter)->getNumberOfCells();
7904     }
7905   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> nodal=DataArrayInt::New();
7906   nodal->alloc(meshLgth,1);
7907   int *nodalPtr=nodal->getPointer();
7908   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> nodalIndex=DataArrayInt::New();
7909   nodalIndex->alloc(meshIndexLgth+1,1);
7910   int *nodalIndexPtr=nodalIndex->getPointer();
7911   int offset=0;
7912   for(iter=meshes.begin();iter!=meshes.end();iter++)
7913     {
7914       const int *nod=(*iter)->getNodalConnectivity()->getConstPointer();
7915       const int *index=(*iter)->getNodalConnectivityIndex()->getConstPointer();
7916       int nbOfCells=(*iter)->getNumberOfCells();
7917       int meshLgth2=(*iter)->getMeshLength();
7918       nodalPtr=std::copy(nod,nod+meshLgth2,nodalPtr);
7919       if(iter!=meshes.begin())
7920         nodalIndexPtr=std::transform(index+1,index+nbOfCells+1,nodalIndexPtr,std::bind2nd(std::plus<int>(),offset));
7921       else
7922         nodalIndexPtr=std::copy(index,index+nbOfCells+1,nodalIndexPtr);
7923       offset+=meshLgth2;
7924     }
7925   MEDCouplingUMesh *ret=MEDCouplingUMesh::New();
7926   ret->setName("merge");
7927   ret->setMeshDimension(meshDim);
7928   ret->setConnectivity(nodal,nodalIndex,true);
7929   ret->setCoords(coords);
7930   return ret;
7931 }
7932
7933 /*!
7934  * Creates a new MEDCouplingUMesh by concatenating cells of all given meshes of same
7935  * dimension and sharing the node coordinates array. Cells of the *i*-th mesh precede
7936  * cells of the (*i*+1)-th mesh within the result mesh. Duplicates of cells are
7937  * removed from \a this mesh and arrays mapping between new and old cell ids in "Old to
7938  * New" mode are returned for each input mesh.
7939  *  \param [in] meshes - a vector of meshes (MEDCouplingUMesh) to concatenate.
7940  *  \param [in] compType - specifies a cell comparison technique. For meaning of its
7941  *          valid values [0,1,2], see zipConnectivityTraducer().
7942  *  \param [in,out] corr - an array of DataArrayInt, of the same size as \a
7943  *          meshes. The *i*-th array describes cell ids mapping for \a meshes[ *i* ]
7944  *          mesh. The caller is to delete each of the arrays using decrRef() as it is
7945  *          no more needed.
7946  *  \return MEDCouplingUMesh * - the result mesh. It is a new instance of
7947  *          MEDCouplingUMesh. The caller is to delete this mesh using decrRef() as it
7948  *          is no more needed.
7949  *  \throw If \a meshes.size() == 0.
7950  *  \throw If \a meshes[ *i* ] == NULL.
7951  *  \throw If the meshes do not share the node coordinates array.
7952  *  \throw If \a meshes[ *i* ]->getMeshDimension() < 0.
7953  *  \throw If the \a meshes are of different dimension (getMeshDimension()).
7954  *  \throw If the nodal connectivity of cells of any of \a meshes is not defined.
7955  *  \throw If the nodal connectivity any of \a meshes includes an invalid id.
7956  */
7957 MEDCouplingUMesh *MEDCouplingUMesh::FuseUMeshesOnSameCoords(const std::vector<const MEDCouplingUMesh *>& meshes, int compType, std::vector<DataArrayInt *>& corr)
7958 {
7959   //All checks are delegated to MergeUMeshesOnSameCoords
7960   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret=MergeUMeshesOnSameCoords(meshes);
7961   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> o2n=ret->zipConnectivityTraducer(compType);
7962   corr.resize(meshes.size());
7963   std::size_t nbOfMeshes=meshes.size();
7964   int offset=0;
7965   const int *o2nPtr=o2n->getConstPointer();
7966   for(std::size_t i=0;i<nbOfMeshes;i++)
7967     {
7968       DataArrayInt *tmp=DataArrayInt::New();
7969       int curNbOfCells=meshes[i]->getNumberOfCells();
7970       tmp->alloc(curNbOfCells,1);
7971       std::copy(o2nPtr+offset,o2nPtr+offset+curNbOfCells,tmp->getPointer());
7972       offset+=curNbOfCells;
7973       tmp->setName(meshes[i]->getName());
7974       corr[i]=tmp;
7975     }
7976   return ret.retn();
7977 }
7978
7979 /*!
7980  * Makes all given meshes share the nodal connectivity array. The common connectivity
7981  * array is created by concatenating the connectivity arrays of all given meshes. All
7982  * the given meshes must be of the same space dimension but dimension of cells **can
7983  * differ**. This method is particulary useful in MEDLoader context to build a \ref
7984  * ParaMEDMEM::MEDFileUMesh "MEDFileUMesh" instance that expects that underlying
7985  * MEDCouplingUMesh'es of different dimension share the same nodal connectivity array.
7986  *  \param [in,out] meshes - a vector of meshes to update.
7987  *  \throw If any of \a meshes is NULL.
7988  *  \throw If the coordinates array is not set in any of \a meshes.
7989  *  \throw If the nodal connectivity of cells is not defined in any of \a meshes.
7990  *  \throw If \a meshes are of different space dimension.
7991  */
7992 void MEDCouplingUMesh::PutUMeshesOnSameAggregatedCoords(const std::vector<MEDCouplingUMesh *>& meshes)
7993 {
7994   std::size_t sz=meshes.size();
7995   if(sz==0 || sz==1)
7996     return;
7997   std::vector< const DataArrayDouble * > coords(meshes.size());
7998   std::vector< const DataArrayDouble * >::iterator it2=coords.begin();
7999   for(std::vector<MEDCouplingUMesh *>::const_iterator it=meshes.begin();it!=meshes.end();it++,it2++)
8000     {
8001       if((*it))
8002         {
8003           (*it)->checkConnectivityFullyDefined();
8004           const DataArrayDouble *coo=(*it)->getCoords();
8005           if(coo)
8006             *it2=coo;
8007           else
8008             {
8009               std::ostringstream oss; oss << " MEDCouplingUMesh::PutUMeshesOnSameAggregatedCoords : Item #" << std::distance(meshes.begin(),it) << " inside the vector of length " << meshes.size();
8010               oss << " has no coordinate array defined !";
8011               throw INTERP_KERNEL::Exception(oss.str().c_str());
8012             }
8013         }
8014       else
8015         {
8016           std::ostringstream oss; oss << " MEDCouplingUMesh::PutUMeshesOnSameAggregatedCoords : Item #" << std::distance(meshes.begin(),it) << " inside the vector of length " << meshes.size();
8017           oss << " is null !";
8018           throw INTERP_KERNEL::Exception(oss.str().c_str());
8019         }
8020     }
8021   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> res=DataArrayDouble::Aggregate(coords);
8022   std::vector<MEDCouplingUMesh *>::const_iterator it=meshes.begin();
8023   int offset=(*it)->getNumberOfNodes();
8024   (*it++)->setCoords(res);
8025   for(;it!=meshes.end();it++)
8026     {
8027       int oldNumberOfNodes=(*it)->getNumberOfNodes();
8028       (*it)->setCoords(res);
8029       (*it)->shiftNodeNumbersInConn(offset);
8030       offset+=oldNumberOfNodes;
8031     }
8032 }
8033
8034 /*!
8035  * Merges nodes coincident with a given precision within all given meshes that share
8036  * the nodal connectivity array. The given meshes **can be of different** mesh
8037  * dimension. This method is particulary useful in MEDLoader context to build a \ref
8038  * ParaMEDMEM::MEDFileUMesh "MEDFileUMesh" instance that expects that underlying
8039  * MEDCouplingUMesh'es of different dimension share the same nodal connectivity array. 
8040  *  \param [in,out] meshes - a vector of meshes to update.
8041  *  \param [in] eps - the precision used to detect coincident nodes (infinite norm).
8042  *  \throw If any of \a meshes is NULL.
8043  *  \throw If the \a meshes do not share the same node coordinates array.
8044  *  \throw If the nodal connectivity of cells is not defined in any of \a meshes.
8045  */
8046 void MEDCouplingUMesh::MergeNodesOnUMeshesSharingSameCoords(const std::vector<MEDCouplingUMesh *>& meshes, double eps)
8047 {
8048   if(meshes.empty())
8049     return ;
8050   std::set<const DataArrayDouble *> s;
8051   for(std::vector<MEDCouplingUMesh *>::const_iterator it=meshes.begin();it!=meshes.end();it++)
8052     {
8053       if(*it)
8054         s.insert((*it)->getCoords());
8055       else
8056         {
8057           std::ostringstream oss; oss << "MEDCouplingUMesh::MergeNodesOnUMeshesSharingSameCoords : In input vector of unstructured meshes of size " << meshes.size() << " the element #" << std::distance(meshes.begin(),it) << " is null !";
8058           throw INTERP_KERNEL::Exception(oss.str().c_str());
8059         }
8060     }
8061   if(s.size()!=1)
8062     {
8063       std::ostringstream oss; oss << "MEDCouplingUMesh::MergeNodesOnUMeshesSharingSameCoords : In input vector of unstructured meshes of size " << meshes.size() << ", it appears that they do not share the same instance of DataArrayDouble for coordiantes ! tryToShareSameCoordsPermute method can help to reach that !";
8064       throw INTERP_KERNEL::Exception(oss.str().c_str());
8065     }
8066   const DataArrayDouble *coo=*(s.begin());
8067   if(!coo)
8068     return;
8069   //
8070   DataArrayInt *comm,*commI;
8071   coo->findCommonTuples(eps,-1,comm,commI);
8072   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp1(comm),tmp2(commI);
8073   int oldNbOfNodes=coo->getNumberOfTuples();
8074   int newNbOfNodes;
8075   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> o2n=DataArrayInt::BuildOld2NewArrayFromSurjectiveFormat2(oldNbOfNodes,comm->begin(),commI->begin(),commI->end(),newNbOfNodes);
8076   if(oldNbOfNodes==newNbOfNodes)
8077     return ;
8078   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> newCoords=coo->renumberAndReduce(o2n->getConstPointer(),newNbOfNodes);
8079   for(std::vector<MEDCouplingUMesh *>::const_iterator it=meshes.begin();it!=meshes.end();it++)
8080     {
8081       (*it)->renumberNodesInConn(o2n->getConstPointer());
8082       (*it)->setCoords(newCoords);
8083     } 
8084 }
8085
8086 /*!
8087  * This method takes in input a cell defined by its MEDcouplingUMesh connectivity [ \a connBg , \a connEnd ) and returns its extruded cell by inserting the result at the end of ret.
8088  * \param nbOfNodesPerLev in parameter that specifies the number of nodes of one slice of global dataset
8089  * \param isQuad specifies the policy of connectivity.
8090  * @ret in/out parameter in which the result will be append
8091  */
8092 void MEDCouplingUMesh::AppendExtrudedCell(const int *connBg, const int *connEnd, int nbOfNodesPerLev, bool isQuad, std::vector<int>& ret)
8093 {
8094   INTERP_KERNEL::NormalizedCellType flatType=(INTERP_KERNEL::NormalizedCellType)connBg[0];
8095   const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(flatType);
8096   ret.push_back(cm.getExtrudedType());
8097   int deltaz=isQuad?2*nbOfNodesPerLev:nbOfNodesPerLev;
8098   switch(flatType)
8099   {
8100     case INTERP_KERNEL::NORM_POINT1:
8101       {
8102         ret.push_back(connBg[1]);
8103         ret.push_back(connBg[1]+nbOfNodesPerLev);
8104         break;
8105       }
8106     case INTERP_KERNEL::NORM_SEG2:
8107       {
8108         int conn[4]={connBg[1],connBg[2],connBg[2]+deltaz,connBg[1]+deltaz};
8109         ret.insert(ret.end(),conn,conn+4);
8110         break;
8111       }
8112     case INTERP_KERNEL::NORM_SEG3:
8113       {
8114         int conn[8]={connBg[1],connBg[3],connBg[3]+deltaz,connBg[1]+deltaz,connBg[2],connBg[3]+nbOfNodesPerLev,connBg[2]+deltaz,connBg[1]+nbOfNodesPerLev};
8115         ret.insert(ret.end(),conn,conn+8);
8116         break;
8117       }
8118     case INTERP_KERNEL::NORM_QUAD4:
8119       {
8120         int conn[8]={connBg[1],connBg[2],connBg[3],connBg[4],connBg[1]+deltaz,connBg[2]+deltaz,connBg[3]+deltaz,connBg[4]+deltaz};
8121         ret.insert(ret.end(),conn,conn+8);
8122         break;
8123       }
8124     case INTERP_KERNEL::NORM_TRI3:
8125       {
8126         int conn[6]={connBg[1],connBg[2],connBg[3],connBg[1]+deltaz,connBg[2]+deltaz,connBg[3]+deltaz};
8127         ret.insert(ret.end(),conn,conn+6);
8128         break;
8129       }
8130     case INTERP_KERNEL::NORM_TRI6:
8131       {
8132         int conn[15]={connBg[1],connBg[2],connBg[3],connBg[1]+deltaz,connBg[2]+deltaz,connBg[3]+deltaz,connBg[4],connBg[5],connBg[6],connBg[4]+deltaz,connBg[5]+deltaz,connBg[6]+deltaz,
8133           connBg[1]+nbOfNodesPerLev,connBg[2]+nbOfNodesPerLev,connBg[3]+nbOfNodesPerLev};
8134         ret.insert(ret.end(),conn,conn+15);
8135         break;
8136       }
8137     case INTERP_KERNEL::NORM_QUAD8:
8138       {
8139         int conn[20]={
8140           connBg[1],connBg[2],connBg[3],connBg[4],connBg[1]+deltaz,connBg[2]+deltaz,connBg[3]+deltaz,connBg[4]+deltaz,
8141           connBg[5],connBg[6],connBg[7],connBg[8],connBg[5]+deltaz,connBg[6]+deltaz,connBg[7]+deltaz,connBg[8]+deltaz,
8142           connBg[1]+nbOfNodesPerLev,connBg[2]+nbOfNodesPerLev,connBg[3]+nbOfNodesPerLev,connBg[4]+nbOfNodesPerLev
8143         };
8144         ret.insert(ret.end(),conn,conn+20);
8145         break;
8146       }
8147     case INTERP_KERNEL::NORM_POLYGON:
8148       {
8149         std::back_insert_iterator< std::vector<int> > ii(ret);
8150         std::copy(connBg+1,connEnd,ii);
8151         *ii++=-1;
8152         std::reverse_iterator<const int *> rConnBg(connEnd);
8153         std::reverse_iterator<const int *> rConnEnd(connBg+1);
8154         std::transform(rConnBg,rConnEnd,ii,std::bind2nd(std::plus<int>(),deltaz));
8155         std::size_t nbOfRadFaces=std::distance(connBg+1,connEnd);
8156         for(std::size_t i=0;i<nbOfRadFaces;i++)
8157           {
8158             *ii++=-1;
8159             int conn[4]={connBg[(i+1)%nbOfRadFaces+1],connBg[i+1],connBg[i+1]+deltaz,connBg[(i+1)%nbOfRadFaces+1]+deltaz};
8160             std::copy(conn,conn+4,ii);
8161           }
8162         break;
8163       }
8164     default:
8165       throw INTERP_KERNEL::Exception("A flat type has been detected that has not its extruded representation !");
8166   }
8167 }
8168
8169 /*!
8170  * This static operates only for coords in 3D. The polygon is specfied by its connectivity nodes in [ \a begin , \a end ).
8171  */
8172 bool MEDCouplingUMesh::IsPolygonWellOriented(bool isQuadratic, const double *vec, const int *begin, const int *end, const double *coords)
8173 {
8174   std::size_t i, ip1;
8175   double v[3]={0.,0.,0.};
8176   std::size_t sz=std::distance(begin,end);
8177   if(isQuadratic)
8178     sz/=2;
8179   for(i=0;i<sz;i++)
8180     {
8181       v[0]+=coords[3*begin[i]+1]*coords[3*begin[(i+1)%sz]+2]-coords[3*begin[i]+2]*coords[3*begin[(i+1)%sz]+1];
8182       v[1]+=coords[3*begin[i]+2]*coords[3*begin[(i+1)%sz]]-coords[3*begin[i]]*coords[3*begin[(i+1)%sz]+2];
8183       v[2]+=coords[3*begin[i]]*coords[3*begin[(i+1)%sz]+1]-coords[3*begin[i]+1]*coords[3*begin[(i+1)%sz]];
8184     }
8185   double ret = vec[0]*v[0]+vec[1]*v[1]+vec[2]*v[2];
8186
8187   // Try using quadratic points if standard points are degenerated (for example a QPOLYG with two
8188   // SEG3 forming a circle):
8189   if (fabs(ret) < INTERP_KERNEL::DEFAULT_ABS_TOL && isQuadratic)
8190     {
8191       v[0] = 0.0; v[1] = 0.0; v[2] = 0.0;
8192       for(std::size_t j=0;j<sz;j++)
8193         {
8194           if (j%2)  // current point i is quadratic, next point i+1 is standard
8195             {
8196               i = sz+j;
8197               ip1 = (j+1)%sz; // ip1 = "i+1"
8198             }
8199           else      // current point i is standard, next point i+1 is quadratic
8200             {
8201               i = j;
8202               ip1 = j+sz;
8203             }
8204           v[0]+=coords[3*begin[i]+1]*coords[3*begin[ip1]+2]-coords[3*begin[i]+2]*coords[3*begin[ip1]+1];
8205           v[1]+=coords[3*begin[i]+2]*coords[3*begin[ip1]]-coords[3*begin[i]]*coords[3*begin[ip1]+2];
8206           v[2]+=coords[3*begin[i]]*coords[3*begin[ip1]+1]-coords[3*begin[i]+1]*coords[3*begin[ip1]];
8207         }
8208       ret = vec[0]*v[0]+vec[1]*v[1]+vec[2]*v[2];
8209     }
8210   return (ret>0.);
8211 }
8212
8213 /*!
8214  * The polyhedron is specfied by its connectivity nodes in [ \a begin , \a end ).
8215  */
8216 bool MEDCouplingUMesh::IsPolyhedronWellOriented(const int *begin, const int *end, const double *coords)
8217 {
8218   std::vector<std::pair<int,int> > edges;
8219   std::size_t nbOfFaces=std::count(begin,end,-1)+1;
8220   const int *bgFace=begin;
8221   for(std::size_t i=0;i<nbOfFaces;i++)
8222     {
8223       const int *endFace=std::find(bgFace+1,end,-1);
8224       std::size_t nbOfEdgesInFace=std::distance(bgFace,endFace);
8225       for(std::size_t j=0;j<nbOfEdgesInFace;j++)
8226         {
8227           std::pair<int,int> p1(bgFace[j],bgFace[(j+1)%nbOfEdgesInFace]);
8228           if(std::find(edges.begin(),edges.end(),p1)!=edges.end())
8229             return false;
8230           edges.push_back(p1);
8231         }
8232       bgFace=endFace+1;
8233     }
8234   return INTERP_KERNEL::calculateVolumeForPolyh2<int,INTERP_KERNEL::ALL_C_MODE>(begin,(int)std::distance(begin,end),coords)>-EPS_FOR_POLYH_ORIENTATION;
8235 }
8236
8237 /*!
8238  * The 3D extruded static cell (PENTA6,HEXA8,HEXAGP12...) its connectivity nodes in [ \a begin , \a end ).
8239  */
8240 bool MEDCouplingUMesh::Is3DExtrudedStaticCellWellOriented(const int *begin, const int *end, const double *coords)
8241 {
8242   double vec0[3],vec1[3];
8243   std::size_t sz=std::distance(begin,end);
8244   if(sz%2!=0)
8245     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::Is3DExtrudedStaticCellWellOriented : the length of nodal connectivity of extruded cell is not even !");
8246   int nbOfNodes=(int)sz/2;
8247   INTERP_KERNEL::areaVectorOfPolygon<int,INTERP_KERNEL::ALL_C_MODE>(begin,nbOfNodes,coords,vec0);
8248   const double *pt0=coords+3*begin[0];
8249   const double *pt1=coords+3*begin[nbOfNodes];
8250   vec1[0]=pt1[0]-pt0[0]; vec1[1]=pt1[1]-pt0[1]; vec1[2]=pt1[2]-pt0[2];
8251   return (vec0[0]*vec1[0]+vec0[1]*vec1[1]+vec0[2]*vec1[2])<0.;
8252 }
8253
8254 void MEDCouplingUMesh::CorrectExtrudedStaticCell(int *begin, int *end)
8255 {
8256   std::size_t sz=std::distance(begin,end);
8257   INTERP_KERNEL::AutoPtr<int> tmp=new int[sz];
8258   std::size_t nbOfNodes(sz/2);
8259   std::copy(begin,end,(int *)tmp);
8260   for(std::size_t j=1;j<nbOfNodes;j++)
8261     {
8262       begin[j]=tmp[nbOfNodes-j];
8263       begin[j+nbOfNodes]=tmp[nbOfNodes+nbOfNodes-j];
8264     }
8265 }
8266
8267 bool MEDCouplingUMesh::IsTetra4WellOriented(const int *begin, const int *end, const double *coords)
8268 {
8269   std::size_t sz=std::distance(begin,end);
8270   if(sz!=4)
8271     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::IsTetra4WellOriented : Tetra4 cell with not 4 nodes ! Call checkCoherency2 !");
8272   double vec0[3],vec1[3];
8273   const double *pt0=coords+3*begin[0],*pt1=coords+3*begin[1],*pt2=coords+3*begin[2],*pt3=coords+3*begin[3];
8274   vec0[0]=pt1[0]-pt0[0]; vec0[1]=pt1[1]-pt0[1]; vec0[2]=pt1[2]-pt0[2]; vec1[0]=pt2[0]-pt0[0]; vec1[1]=pt2[1]-pt0[1]; vec1[2]=pt2[2]-pt0[2]; 
8275   return ((vec0[1]*vec1[2]-vec0[2]*vec1[1])*(pt3[0]-pt0[0])+(vec0[2]*vec1[0]-vec0[0]*vec1[2])*(pt3[1]-pt0[1])+(vec0[0]*vec1[1]-vec0[1]*vec1[0])*(pt3[2]-pt0[2]))<0;
8276 }
8277
8278 bool MEDCouplingUMesh::IsPyra5WellOriented(const int *begin, const int *end, const double *coords)
8279 {
8280   std::size_t sz=std::distance(begin,end);
8281   if(sz!=5)
8282     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::IsPyra5WellOriented : Pyra5 cell with not 5 nodes ! Call checkCoherency2 !");
8283   double vec0[3];
8284   INTERP_KERNEL::areaVectorOfPolygon<int,INTERP_KERNEL::ALL_C_MODE>(begin,4,coords,vec0);
8285   const double *pt0=coords+3*begin[0],*pt1=coords+3*begin[4];
8286   return (vec0[0]*(pt1[0]-pt0[0])+vec0[1]*(pt1[1]-pt0[1])+vec0[2]*(pt1[2]-pt0[2]))<0.;
8287 }
8288
8289 /*!
8290  * This method performs a simplyfication of a single polyedron cell. To do that each face of cell whose connectivity is defined by [ \b begin , \b end ) 
8291  * is compared with the others in order to find faces in the same plane (with approx of eps). If any, the cells are grouped together and projected to
8292  * a 2D space.
8293  *
8294  * \param [in] eps is a relative precision that allows to establish if some 3D plane are coplanar or not.
8295  * \param [in] coords the coordinates with nb of components exactly equal to 3
8296  * \param [in] begin begin of the nodal connectivity (geometric type included) of a single polyhedron cell
8297  * \param [in] end end of nodal connectivity of a single polyhedron cell (excluded)
8298  * \param [out] res the result is put at the end of the vector without any alteration of the data.
8299  */
8300 void MEDCouplingUMesh::SimplifyPolyhedronCell(double eps, const DataArrayDouble *coords, const int *begin, const int *end, DataArrayInt *res)
8301 {
8302   int nbFaces=std::count(begin+1,end,-1)+1;
8303   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> v=DataArrayDouble::New(); v->alloc(nbFaces,3);
8304   double *vPtr=v->getPointer();
8305   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> p=DataArrayDouble::New(); p->alloc(nbFaces,1);
8306   double *pPtr=p->getPointer();
8307   const int *stFaceConn=begin+1;
8308   for(int i=0;i<nbFaces;i++,vPtr+=3,pPtr++)
8309     {
8310       const int *endFaceConn=std::find(stFaceConn,end,-1);
8311       ComputeVecAndPtOfFace(eps,coords->getConstPointer(),stFaceConn,endFaceConn,vPtr,pPtr);
8312       stFaceConn=endFaceConn+1;
8313     }
8314   pPtr=p->getPointer(); vPtr=v->getPointer();
8315   DataArrayInt *comm1=0,*commI1=0;
8316   v->findCommonTuples(eps,-1,comm1,commI1);
8317   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> comm1Auto(comm1),commI1Auto(commI1);
8318   const int *comm1Ptr=comm1->getConstPointer();
8319   const int *commI1Ptr=commI1->getConstPointer();
8320   int nbOfGrps1=commI1Auto->getNumberOfTuples()-1;
8321   res->pushBackSilent((int)INTERP_KERNEL::NORM_POLYHED);
8322   //
8323   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> mm=MEDCouplingUMesh::New("",3);
8324   mm->setCoords(const_cast<DataArrayDouble *>(coords)); mm->allocateCells(1); mm->insertNextCell(INTERP_KERNEL::NORM_POLYHED,(int)std::distance(begin+1,end),begin+1);
8325   mm->finishInsertingCells();
8326   //
8327   for(int i=0;i<nbOfGrps1;i++)
8328     {
8329       int vecId=comm1Ptr[commI1Ptr[i]];
8330       MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> tmpgrp2=p->selectByTupleId(comm1Ptr+commI1Ptr[i],comm1Ptr+commI1Ptr[i+1]);
8331       DataArrayInt *comm2=0,*commI2=0;
8332       tmpgrp2->findCommonTuples(eps,-1,comm2,commI2);
8333       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> comm2Auto(comm2),commI2Auto(commI2);
8334       const int *comm2Ptr=comm2->getConstPointer();
8335       const int *commI2Ptr=commI2->getConstPointer();
8336       int nbOfGrps2=commI2Auto->getNumberOfTuples()-1;
8337       for(int j=0;j<nbOfGrps2;j++)
8338         {
8339           if(commI2Ptr[j+1]-commI2Ptr[j]<=1)
8340             {
8341               res->insertAtTheEnd(begin,end);
8342               res->pushBackSilent(-1);
8343             }
8344           else
8345             {
8346               int pointId=comm1Ptr[commI1Ptr[i]+comm2Ptr[commI2Ptr[j]]];
8347               MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ids2=comm2->selectByTupleId2(commI2Ptr[j],commI2Ptr[j+1],1);
8348               ids2->transformWithIndArr(comm1Ptr+commI1Ptr[i],comm1Ptr+commI1Ptr[i+1]);
8349               DataArrayInt *tmp0=DataArrayInt::New(),*tmp1=DataArrayInt::New(),*tmp2=DataArrayInt::New(),*tmp3=DataArrayInt::New();
8350               MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> mm2=mm->buildDescendingConnectivity(tmp0,tmp1,tmp2,tmp3); tmp0->decrRef(); tmp1->decrRef(); tmp2->decrRef(); tmp3->decrRef();
8351               MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> mm3=static_cast<MEDCouplingUMesh *>(mm2->buildPartOfMySelf(ids2->begin(),ids2->end(),true));
8352               MEDCouplingAutoRefCountObjectPtr<DataArrayInt> idsNodeTmp=mm3->zipCoordsTraducer();
8353               MEDCouplingAutoRefCountObjectPtr<DataArrayInt> idsNode=idsNodeTmp->invertArrayO2N2N2O(mm3->getNumberOfNodes());
8354               const int *idsNodePtr=idsNode->getConstPointer();
8355               double center[3]; center[0]=pPtr[pointId]*vPtr[3*vecId]; center[1]=pPtr[pointId]*vPtr[3*vecId+1]; center[2]=pPtr[pointId]*vPtr[3*vecId+2];
8356               double vec[3]; vec[0]=vPtr[3*vecId+1]; vec[1]=-vPtr[3*vecId]; vec[2]=0.;
8357               double norm=vec[0]*vec[0]+vec[1]*vec[1]+vec[2]*vec[2];
8358               if(std::abs(norm)>eps)
8359                 {
8360                   double angle=INTERP_KERNEL::EdgeArcCircle::SafeAsin(norm);
8361                   mm3->rotate(center,vec,angle);
8362                 }
8363               mm3->changeSpaceDimension(2);
8364               MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> mm4=mm3->buildSpreadZonesWithPoly();
8365               const int *conn4=mm4->getNodalConnectivity()->getConstPointer();
8366               const int *connI4=mm4->getNodalConnectivityIndex()->getConstPointer();
8367               int nbOfCells=mm4->getNumberOfCells();
8368               for(int k=0;k<nbOfCells;k++)
8369                 {
8370                   int l=0;
8371                   for(const int *work=conn4+connI4[k]+1;work!=conn4+connI4[k+1];work++,l++)
8372                     res->pushBackSilent(idsNodePtr[*work]);
8373                   res->pushBackSilent(-1);
8374                 }
8375             }
8376         }
8377     }
8378   res->popBackSilent();
8379 }
8380
8381 /*!
8382  * This method computes the normalized vector of the plane and the pos of the point belonging to the plane and the line defined by the vector going
8383  * through origin. The plane is defined by its nodal connectivity [ \b begin, \b end ).
8384  * 
8385  * \param [in] eps below that value the dot product of 2 vectors is considered as colinears
8386  * \param [in] coords coordinates expected to have 3 components.
8387  * \param [in] begin start of the nodal connectivity of the face.
8388  * \param [in] end end of the nodal connectivity (excluded) of the face.
8389  * \param [out] v the normalized vector of size 3
8390  * \param [out] p the pos of plane
8391  */
8392 void MEDCouplingUMesh::ComputeVecAndPtOfFace(double eps, const double *coords, const int *begin, const int *end, double *v, double *p)
8393 {
8394   std::size_t nbPoints=std::distance(begin,end);
8395   if(nbPoints<3)
8396     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ComputeVecAndPtOfFace : < of 3 points in face ! not able to find a plane on that face !");
8397   double vec[3]={0.,0.,0.};
8398   std::size_t j=0;
8399   bool refFound=false;
8400   for(;j<nbPoints-1 && !refFound;j++)
8401     {
8402       vec[0]=coords[3*begin[j+1]]-coords[3*begin[j]];
8403       vec[1]=coords[3*begin[j+1]+1]-coords[3*begin[j]+1];
8404       vec[2]=coords[3*begin[j+1]+2]-coords[3*begin[j]+2];
8405       double norm=sqrt(vec[0]*vec[0]+vec[1]*vec[1]+vec[2]*vec[2]);
8406       if(norm>eps)
8407         {
8408           refFound=true;
8409           vec[0]/=norm; vec[1]/=norm; vec[2]/=norm;
8410         }
8411     }
8412   for(std::size_t i=j;i<nbPoints-1;i++)
8413     {
8414       double curVec[3];
8415       curVec[0]=coords[3*begin[i+1]]-coords[3*begin[i]];
8416       curVec[1]=coords[3*begin[i+1]+1]-coords[3*begin[i]+1];
8417       curVec[2]=coords[3*begin[i+1]+2]-coords[3*begin[i]+2];
8418       double norm=sqrt(curVec[0]*curVec[0]+curVec[1]*curVec[1]+curVec[2]*curVec[2]);
8419       if(norm<eps)
8420         continue;
8421       curVec[0]/=norm; curVec[1]/=norm; curVec[2]/=norm;
8422       v[0]=vec[1]*curVec[2]-vec[2]*curVec[1]; v[1]=vec[2]*curVec[0]-vec[0]*curVec[2]; v[2]=vec[0]*curVec[1]-vec[1]*curVec[0];
8423       norm=sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
8424       if(norm>eps)
8425         {
8426           v[0]/=norm; v[1]/=norm; v[2]/=norm;
8427           *p=v[0]*coords[3*begin[i]]+v[1]*coords[3*begin[i]+1]+v[2]*coords[3*begin[i]+2];
8428           return ;
8429         }
8430     }
8431   throw INTERP_KERNEL::Exception("Not able to find a normal vector of that 3D face !");
8432 }
8433
8434 /*!
8435  * This method tries to obtain a well oriented polyhedron.
8436  * If the algorithm fails, an exception will be thrown.
8437  */
8438 void MEDCouplingUMesh::TryToCorrectPolyhedronOrientation(int *begin, int *end, const double *coords)
8439 {
8440   std::list< std::pair<int,int> > edgesOK,edgesFinished;
8441   std::size_t nbOfFaces=std::count(begin,end,-1)+1;
8442   std::vector<bool> isPerm(nbOfFaces,false);//field on faces False: I don't know, True : oriented
8443   isPerm[0]=true;
8444   int *bgFace=begin,*endFace=std::find(begin+1,end,-1);
8445   std::size_t nbOfEdgesInFace=std::distance(bgFace,endFace);
8446   for(std::size_t l=0;l<nbOfEdgesInFace;l++) { std::pair<int,int> p1(bgFace[l],bgFace[(l+1)%nbOfEdgesInFace]); edgesOK.push_back(p1); }
8447   //
8448   while(std::find(isPerm.begin(),isPerm.end(),false)!=isPerm.end())
8449     {
8450       bgFace=begin;
8451       std::size_t smthChanged=0;
8452       for(std::size_t i=0;i<nbOfFaces;i++)
8453         {
8454           endFace=std::find(bgFace+1,end,-1);
8455           nbOfEdgesInFace=std::distance(bgFace,endFace);
8456           if(!isPerm[i])
8457             {
8458               bool b;
8459               for(std::size_t j=0;j<nbOfEdgesInFace;j++)
8460                 {
8461                   std::pair<int,int> p1(bgFace[j],bgFace[(j+1)%nbOfEdgesInFace]);
8462                   std::pair<int,int> p2(p1.second,p1.first);
8463                   bool b1=std::find(edgesOK.begin(),edgesOK.end(),p1)!=edgesOK.end();
8464                   bool b2=std::find(edgesOK.begin(),edgesOK.end(),p2)!=edgesOK.end();
8465                   if(b1 || b2) { b=b2; isPerm[i]=true; smthChanged++; break; }
8466                 }
8467               if(isPerm[i])
8468                 { 
8469                   if(!b)
8470                     std::reverse(bgFace+1,endFace);
8471                   for(std::size_t j=0;j<nbOfEdgesInFace;j++)
8472                     {
8473                       std::pair<int,int> p1(bgFace[j],bgFace[(j+1)%nbOfEdgesInFace]);
8474                       std::pair<int,int> p2(p1.second,p1.first);
8475                       if(std::find(edgesOK.begin(),edgesOK.end(),p1)!=edgesOK.end())
8476                         { std::ostringstream oss; oss << "Face #" << j << " of polyhedron looks bad !"; throw INTERP_KERNEL::Exception(oss.str().c_str()); }
8477                       if(std::find(edgesFinished.begin(),edgesFinished.end(),p1)!=edgesFinished.end() || std::find(edgesFinished.begin(),edgesFinished.end(),p2)!=edgesFinished.end())
8478                         { std::ostringstream oss; oss << "Face #" << j << " of polyhedron looks bad !"; throw INTERP_KERNEL::Exception(oss.str().c_str()); }
8479                       std::list< std::pair<int,int> >::iterator it=std::find(edgesOK.begin(),edgesOK.end(),p2);
8480                       if(it!=edgesOK.end())
8481                         {
8482                           edgesOK.erase(it);
8483                           edgesFinished.push_back(p1);
8484                         }
8485                       else
8486                         edgesOK.push_back(p1);
8487                     }
8488                 }
8489             }
8490           bgFace=endFace+1;
8491         }
8492       if(smthChanged==0)
8493         { throw INTERP_KERNEL::Exception("The polyhedron looks too bad to be repaired !"); }
8494     }
8495   if(!edgesOK.empty())
8496     { throw INTERP_KERNEL::Exception("The polyhedron looks too bad to be repaired : Some edges are shared only once !"); }
8497   if(INTERP_KERNEL::calculateVolumeForPolyh2<int,INTERP_KERNEL::ALL_C_MODE>(begin,(int)std::distance(begin,end),coords)<-EPS_FOR_POLYH_ORIENTATION)
8498     {//not lucky ! The first face was not correctly oriented : reorient all faces...
8499       bgFace=begin;
8500       for(std::size_t i=0;i<nbOfFaces;i++)
8501         {
8502           endFace=std::find(bgFace+1,end,-1);
8503           std::reverse(bgFace+1,endFace);
8504           bgFace=endFace+1;
8505         }
8506     }
8507 }
8508
8509 DataArrayInt *MEDCouplingUMesh::buildUnionOf2DMeshLinear(const MEDCouplingUMesh *skin, const DataArrayInt *n2o) const
8510 {
8511   int nbOfNodesExpected(skin->getNumberOfNodes());
8512   const int *n2oPtr(n2o->getConstPointer());
8513   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revNodal(DataArrayInt::New()),revNodalI(DataArrayInt::New());
8514   skin->getReverseNodalConnectivity(revNodal,revNodalI);
8515   const int *revNodalPtr(revNodal->getConstPointer()),*revNodalIPtr(revNodalI->getConstPointer());
8516   const int *nodalPtr(skin->getNodalConnectivity()->getConstPointer());
8517   const int *nodalIPtr(skin->getNodalConnectivityIndex()->getConstPointer());
8518   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret(DataArrayInt::New()); ret->alloc(nbOfNodesExpected+1,1);
8519   int *work(ret->getPointer());  *work++=INTERP_KERNEL::NORM_POLYGON;
8520   if(nbOfNodesExpected<1)
8521     return ret.retn();
8522   int prevCell(0),prevNode(nodalPtr[nodalIPtr[0]+1]);
8523   *work++=n2oPtr[prevNode];
8524   for(int i=1;i<nbOfNodesExpected;i++)
8525     {
8526       if(nodalIPtr[prevCell+1]-nodalIPtr[prevCell]==3)
8527         {
8528           std::set<int> conn(nodalPtr+nodalIPtr[prevCell]+1,nodalPtr+nodalIPtr[prevCell]+3);
8529           conn.erase(prevNode);
8530           if(conn.size()==1)
8531             {
8532               int curNode(*(conn.begin()));
8533               *work++=n2oPtr[curNode];
8534               std::set<int> shar(revNodalPtr+revNodalIPtr[curNode],revNodalPtr+revNodalIPtr[curNode+1]);
8535               shar.erase(prevCell);
8536               if(shar.size()==1)
8537                 {
8538                   prevCell=*(shar.begin());
8539                   prevNode=curNode;
8540                 }
8541               else
8542                 throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildUnionOf2DMeshLinear : presence of unexpected 2 !");
8543             }
8544           else
8545             throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildUnionOf2DMeshLinear : presence of unexpected 1 !");
8546         }
8547       else
8548         throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildUnionOf2DMeshLinear : presence of unexpected cell !");
8549     }
8550   return ret.retn();
8551 }
8552
8553 DataArrayInt *MEDCouplingUMesh::buildUnionOf2DMeshQuadratic(const MEDCouplingUMesh *skin, const DataArrayInt *n2o) const
8554 {
8555   int nbOfNodesExpected(skin->getNumberOfNodes());
8556   int nbOfTurn(nbOfNodesExpected/2);
8557   const int *n2oPtr(n2o->getConstPointer());
8558   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> revNodal(DataArrayInt::New()),revNodalI(DataArrayInt::New());
8559   skin->getReverseNodalConnectivity(revNodal,revNodalI);
8560   const int *revNodalPtr(revNodal->getConstPointer()),*revNodalIPtr(revNodalI->getConstPointer());
8561   const int *nodalPtr(skin->getNodalConnectivity()->getConstPointer());
8562   const int *nodalIPtr(skin->getNodalConnectivityIndex()->getConstPointer());
8563   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret(DataArrayInt::New()); ret->alloc(nbOfNodesExpected+1,1);
8564   int *work(ret->getPointer());  *work++=INTERP_KERNEL::NORM_QPOLYG;
8565   if(nbOfNodesExpected<1)
8566     return ret.retn();
8567   int prevCell(0),prevNode(nodalPtr[nodalIPtr[0]+1]);
8568   *work=n2oPtr[prevNode]; work[nbOfTurn]=n2oPtr[nodalPtr[nodalIPtr[0]+3]]; work++;
8569   for(int i=1;i<nbOfTurn;i++)
8570     {
8571       if(nodalIPtr[prevCell+1]-nodalIPtr[prevCell]==4)
8572         {
8573           std::set<int> conn(nodalPtr+nodalIPtr[prevCell]+1,nodalPtr+nodalIPtr[prevCell]+3);
8574           conn.erase(prevNode);
8575           if(conn.size()==1)
8576             {
8577               int curNode(*(conn.begin()));
8578               *work=n2oPtr[curNode];
8579               std::set<int> shar(revNodalPtr+revNodalIPtr[curNode],revNodalPtr+revNodalIPtr[curNode+1]);
8580               shar.erase(prevCell);
8581               if(shar.size()==1)
8582                 {
8583                   int curCell(*(shar.begin()));
8584                   work[nbOfTurn]=n2oPtr[nodalPtr[nodalIPtr[curCell]+3]];
8585                   prevCell=curCell;
8586                   prevNode=curNode;
8587                   work++;
8588                 }
8589               else
8590                 throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildUnionOf2DMeshQuadratic : presence of unexpected 2 !");
8591             }
8592           else
8593             throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildUnionOf2DMeshQuadratic : presence of unexpected 1 !");
8594         }
8595       else
8596         throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildUnionOf2DMeshQuadratic : presence of unexpected cell !");
8597     }
8598   return ret.retn();
8599 }
8600
8601 /*!
8602  * This method makes the assumption spacedimension == meshdimension == 2.
8603  * This method works only for linear cells.
8604  * 
8605  * \return a newly allocated array containing the connectivity of a polygon type enum included (NORM_POLYGON in pos#0)
8606  */
8607 DataArrayInt *MEDCouplingUMesh::buildUnionOf2DMesh() const
8608 {
8609   if(getMeshDimension()!=2 || getSpaceDimension()!=2)
8610     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildUnionOf2DMesh : meshdimension, spacedimension must be equal to 2 !");
8611   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> skin(computeSkin());
8612   int oldNbOfNodes(skin->getNumberOfNodes());
8613   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> o2n(skin->zipCoordsTraducer());
8614   int nbOfNodesExpected(skin->getNumberOfNodes());
8615   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> n2o(o2n->invertArrayO2N2N2O(oldNbOfNodes));
8616   int nbCells(skin->getNumberOfCells());
8617   if(nbCells==nbOfNodesExpected)
8618     return buildUnionOf2DMeshLinear(skin,n2o);
8619   else if(2*nbCells==nbOfNodesExpected)
8620     return buildUnionOf2DMeshQuadratic(skin,n2o);
8621   else
8622     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildUnionOf2DMesh : the mesh 2D in input appears to be not in a single part of a 2D mesh !");
8623 }
8624
8625 /*!
8626  * This method makes the assumption spacedimension == meshdimension == 3.
8627  * This method works only for linear cells.
8628  * 
8629  * \return a newly allocated array containing the connectivity of a polygon type enum included (NORM_POLYHED in pos#0)
8630  */
8631 DataArrayInt *MEDCouplingUMesh::buildUnionOf3DMesh() const
8632 {
8633   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
8634     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildUnionOf3DMesh : meshdimension, spacedimension must be equal to 2 !");
8635   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m=computeSkin();
8636   const int *conn=m->getNodalConnectivity()->getConstPointer();
8637   const int *connI=m->getNodalConnectivityIndex()->getConstPointer();
8638   int nbOfCells=m->getNumberOfCells();
8639   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New(); ret->alloc(m->getNodalConnectivity()->getNumberOfTuples(),1);
8640   int *work=ret->getPointer();  *work++=INTERP_KERNEL::NORM_POLYHED;
8641   if(nbOfCells<1)
8642     return ret.retn();
8643   work=std::copy(conn+connI[0]+1,conn+connI[1],work);
8644   for(int i=1;i<nbOfCells;i++)
8645     {
8646       *work++=-1;
8647       work=std::copy(conn+connI[i]+1,conn+connI[i+1],work);
8648     }
8649   return ret.retn();
8650 }
8651
8652 /*!
8653  * This method put in zip format into parameter 'zipFrmt' in full interlace mode.
8654  * This format is often asked by INTERP_KERNEL algorithms to avoid many indirections into coordinates array.
8655  */
8656 void MEDCouplingUMesh::FillInCompact3DMode(int spaceDim, int nbOfNodesInCell, const int *conn, const double *coo, double *zipFrmt)
8657 {
8658   double *w=zipFrmt;
8659   if(spaceDim==3)
8660     for(int i=0;i<nbOfNodesInCell;i++)
8661       w=std::copy(coo+3*conn[i],coo+3*conn[i]+3,w);
8662   else if(spaceDim==2)
8663     {
8664       for(int i=0;i<nbOfNodesInCell;i++)
8665         {
8666           w=std::copy(coo+2*conn[i],coo+2*conn[i]+2,w);
8667           *w++=0.;
8668         }
8669     }
8670   else
8671     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::FillInCompact3DMode : Invalid spaceDim specified : must be 2 or 3 !");
8672 }
8673
8674 void MEDCouplingUMesh::writeVTKLL(std::ostream& ofs, const std::string& cellData, const std::string& pointData, DataArrayByte *byteData) const
8675 {
8676   int nbOfCells=getNumberOfCells();
8677   if(nbOfCells<=0)
8678     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::writeVTK : the unstructured mesh has no cells !");
8679   static const int PARAMEDMEM2VTKTYPETRADUCER[INTERP_KERNEL::NORM_MAXTYPE+1]={1,3,21,5,9,7,22,34,23,28,-1,-1,-1,-1,10,14,13,-1,12,-1,24,-1,16,27,-1,26,-1,29,-1,-1,25,42,36,4};
8680   ofs << "  <" << getVTKDataSetType() << ">\n";
8681   ofs << "    <Piece NumberOfPoints=\"" << getNumberOfNodes() << "\" NumberOfCells=\"" << nbOfCells << "\">\n";
8682   ofs << "      <PointData>\n" << pointData << std::endl;
8683   ofs << "      </PointData>\n";
8684   ofs << "      <CellData>\n" << cellData << std::endl;
8685   ofs << "      </CellData>\n";
8686   ofs << "      <Points>\n";
8687   if(getSpaceDimension()==3)
8688     _coords->writeVTK(ofs,8,"Points",byteData);
8689   else
8690     {
8691       MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> coo=_coords->changeNbOfComponents(3,0.);
8692       coo->writeVTK(ofs,8,"Points",byteData);
8693     }
8694   ofs << "      </Points>\n";
8695   ofs << "      <Cells>\n";
8696   const int *cPtr=_nodal_connec->getConstPointer();
8697   const int *cIPtr=_nodal_connec_index->getConstPointer();
8698   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> faceoffsets=DataArrayInt::New(); faceoffsets->alloc(nbOfCells,1);
8699   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> types=DataArrayInt::New(); types->alloc(nbOfCells,1);
8700   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> offsets=DataArrayInt::New(); offsets->alloc(nbOfCells,1);
8701   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> connectivity=DataArrayInt::New(); connectivity->alloc(_nodal_connec->getNumberOfTuples()-nbOfCells,1);
8702   int *w1=faceoffsets->getPointer(),*w2=types->getPointer(),*w3=offsets->getPointer(),*w4=connectivity->getPointer();
8703   int szFaceOffsets=0,szConn=0;
8704   for(int i=0;i<nbOfCells;i++,w1++,w2++,w3++)
8705     {
8706       *w2=cPtr[cIPtr[i]];
8707       if((INTERP_KERNEL::NormalizedCellType)cPtr[cIPtr[i]]!=INTERP_KERNEL::NORM_POLYHED)
8708         {
8709           *w1=-1;
8710           *w3=szConn+cIPtr[i+1]-cIPtr[i]-1; szConn+=cIPtr[i+1]-cIPtr[i]-1;
8711           w4=std::copy(cPtr+cIPtr[i]+1,cPtr+cIPtr[i+1],w4);
8712         }
8713       else
8714         {
8715           int deltaFaceOffset=cIPtr[i+1]-cIPtr[i]+1;
8716           *w1=szFaceOffsets+deltaFaceOffset; szFaceOffsets+=deltaFaceOffset;
8717           std::set<int> c(cPtr+cIPtr[i]+1,cPtr+cIPtr[i+1]); c.erase(-1);
8718           *w3=szConn+(int)c.size(); szConn+=(int)c.size();
8719           w4=std::copy(c.begin(),c.end(),w4);
8720         }
8721     }
8722   types->transformWithIndArr(PARAMEDMEM2VTKTYPETRADUCER,PARAMEDMEM2VTKTYPETRADUCER+INTERP_KERNEL::NORM_MAXTYPE+1);
8723   types->writeVTK(ofs,8,"UInt8","types",byteData);
8724   offsets->writeVTK(ofs,8,"Int32","offsets",byteData);
8725   if(szFaceOffsets!=0)
8726     {//presence of Polyhedra
8727       connectivity->reAlloc(szConn);
8728       faceoffsets->writeVTK(ofs,8,"Int32","faceoffsets",byteData);
8729       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> faces=DataArrayInt::New(); faces->alloc(szFaceOffsets,1);
8730       w1=faces->getPointer();
8731       for(int i=0;i<nbOfCells;i++)
8732         if((INTERP_KERNEL::NormalizedCellType)cPtr[cIPtr[i]]==INTERP_KERNEL::NORM_POLYHED)
8733           {
8734             int nbFaces=std::count(cPtr+cIPtr[i]+1,cPtr+cIPtr[i+1],-1)+1;
8735             *w1++=nbFaces;
8736             const int *w6=cPtr+cIPtr[i]+1,*w5=0;
8737             for(int j=0;j<nbFaces;j++)
8738               {
8739                 w5=std::find(w6,cPtr+cIPtr[i+1],-1);
8740                 *w1++=(int)std::distance(w6,w5);
8741                 w1=std::copy(w6,w5,w1);
8742                 w6=w5+1;
8743               }
8744           }
8745       faces->writeVTK(ofs,8,"Int32","faces",byteData);
8746     }
8747   connectivity->writeVTK(ofs,8,"Int32","connectivity",byteData);
8748   ofs << "      </Cells>\n";
8749   ofs << "    </Piece>\n";
8750   ofs << "  </" << getVTKDataSetType() << ">\n";
8751 }
8752
8753 void MEDCouplingUMesh::reprQuickOverview(std::ostream& stream) const
8754 {
8755   stream << "MEDCouplingUMesh C++ instance at " << this << ". Name : \"" << getName() << "\".";
8756   if(_mesh_dim==-2)
8757     { stream << " Not set !"; return ; }
8758   stream << " Mesh dimension : " << _mesh_dim << ".";
8759   if(_mesh_dim==-1)
8760     return ;
8761   if(!_coords)
8762     { stream << " No coordinates set !"; return ; }
8763   if(!_coords->isAllocated())
8764     { stream << " Coordinates set but not allocated !"; return ; }
8765   stream << " Space dimension : " << _coords->getNumberOfComponents() << "." << std::endl;
8766   stream << "Number of nodes : " << _coords->getNumberOfTuples() << ".";
8767   if(!_nodal_connec_index)
8768     { stream << std::endl << "Nodal connectivity NOT set !"; return ; }
8769   if(!_nodal_connec_index->isAllocated())
8770     { stream << std::endl << "Nodal connectivity set but not allocated !"; return ; }
8771   int lgth=_nodal_connec_index->getNumberOfTuples();
8772   int cpt=_nodal_connec_index->getNumberOfComponents();
8773   if(cpt!=1 || lgth<1)
8774     return ;
8775   stream << std::endl << "Number of cells : " << lgth-1 << ".";
8776 }
8777
8778 std::string MEDCouplingUMesh::getVTKDataSetType() const
8779 {
8780   return std::string("UnstructuredGrid");
8781 }
8782
8783 std::string MEDCouplingUMesh::getVTKFileExtension() const
8784 {
8785   return std::string("vtu");
8786 }
8787
8788 /*!
8789  * Partitions the first given 2D mesh using the second given 2D mesh as a tool, and
8790  * returns a result mesh constituted by polygons.
8791  * Thus the final result contains all nodes from m1 plus new nodes. However it doesn't necessarily contains
8792  * all nodes from m2.
8793  * The meshes should be in 2D space. In
8794  * addition, returns two arrays mapping cells of the result mesh to cells of the input
8795  * meshes.
8796  *  \param [in] m1 - the first input mesh which is a partitioned object. The mesh must be so that each point in the space covered by \a m1
8797  *                      must be covered exactly by one entity, \b no \b more. If it is not the case, some tools are available to heal the mesh (conformize2D, mergeNodes)
8798  *  \param [in] m2 - the second input mesh which is a partition tool. The mesh must be so that each point in the space covered by \a m2
8799  *                      must be covered exactly by one entity, \b no \b more. If it is not the case, some tools are available to heal the mesh (conformize2D, mergeNodes)
8800  *  \param [in] eps - precision used to detect coincident mesh entities.
8801  *  \param [out] cellNb1 - a new instance of DataArrayInt holding for each result
8802  *         cell an id of the cell of \a m1 it comes from. The caller is to delete
8803  *         this array using decrRef() as it is no more needed.
8804  *  \param [out] cellNb2 - a new instance of DataArrayInt holding for each result
8805  *         cell an id of the cell of \a m2 it comes from. -1 value means that a
8806  *         result cell comes from a cell (or part of cell) of \a m1 not overlapped by
8807  *         any cell of \a m2. The caller is to delete this array using decrRef() as
8808  *         it is no more needed.  
8809  *  \return MEDCouplingUMesh * - the result 2D mesh which is a new instance of
8810  *         MEDCouplingUMesh. The caller is to delete this mesh using decrRef() as it
8811  *         is no more needed.  
8812  *  \throw If the coordinates array is not set in any of the meshes.
8813  *  \throw If the nodal connectivity of cells is not defined in any of the meshes.
8814  *  \throw If any of the meshes is not a 2D mesh in 2D space.
8815  *
8816  *  \sa conformize2D, mergeNodes
8817  */
8818 MEDCouplingUMesh *MEDCouplingUMesh::Intersect2DMeshes(const MEDCouplingUMesh *m1, const MEDCouplingUMesh *m2,
8819                                                       double eps, DataArrayInt *&cellNb1, DataArrayInt *&cellNb2)
8820 {
8821   if(!m1 || !m2)
8822     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::Intersect2DMeshes : input meshes must be not NULL !");
8823   m1->checkFullyDefined();
8824   m2->checkFullyDefined();
8825   if(m1->getMeshDimension()!=2 || m1->getSpaceDimension()!=2 || m2->getMeshDimension()!=2 || m2->getSpaceDimension()!=2)
8826     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::Intersect2DMeshes works on umeshes m1 AND m2  with meshdim equal to 2 and spaceDim equal to 2 too!");
8827
8828   // Step 1: compute all edge intersections (new nodes)
8829   std::vector< std::vector<int> > intersectEdge1, colinear2, subDiv2;
8830   MEDCouplingUMesh *m1Desc=0,*m2Desc=0; // descending connec. meshes
8831   DataArrayInt *desc1=0,*descIndx1=0,*revDesc1=0,*revDescIndx1=0,*desc2=0,*descIndx2=0,*revDesc2=0,*revDescIndx2=0;
8832   std::vector<double> addCoo,addCoordsQuadratic;  // coordinates of newly created nodes
8833   IntersectDescending2DMeshes(m1,m2,eps,intersectEdge1,colinear2, subDiv2,
8834                               m1Desc,desc1,descIndx1,revDesc1,revDescIndx1,
8835                               addCoo, m2Desc,desc2,descIndx2,revDesc2,revDescIndx2);
8836   revDesc1->decrRef(); revDescIndx1->decrRef(); revDesc2->decrRef(); revDescIndx2->decrRef();
8837   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> dd1(desc1),dd2(descIndx1),dd3(desc2),dd4(descIndx2);
8838   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> dd5(m1Desc),dd6(m2Desc);
8839
8840   // Step 2: re-order newly created nodes according to the ordering found in m2
8841   std::vector< std::vector<int> > intersectEdge2;
8842   BuildIntersectEdges(m1Desc,m2Desc,addCoo,subDiv2,intersectEdge2);
8843   subDiv2.clear(); dd5=0; dd6=0;
8844
8845   // Step 3:
8846   std::vector<int> cr,crI; //no DataArrayInt because interface with Geometric2D
8847   std::vector<int> cNb1,cNb2; //no DataArrayInt because interface with Geometric2D
8848   BuildIntersecting2DCellsFromEdges(eps,m1,desc1->getConstPointer(),descIndx1->getConstPointer(),intersectEdge1,colinear2,m2,desc2->getConstPointer(),descIndx2->getConstPointer(),intersectEdge2,addCoo,
8849                                     /* outputs -> */addCoordsQuadratic,cr,crI,cNb1,cNb2);
8850
8851   // Step 4: Prepare final result:
8852   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> addCooDa(DataArrayDouble::New());
8853   addCooDa->alloc((int)(addCoo.size())/2,2);
8854   std::copy(addCoo.begin(),addCoo.end(),addCooDa->getPointer());
8855   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> addCoordsQuadraticDa(DataArrayDouble::New());
8856   addCoordsQuadraticDa->alloc((int)(addCoordsQuadratic.size())/2,2);
8857   std::copy(addCoordsQuadratic.begin(),addCoordsQuadratic.end(),addCoordsQuadraticDa->getPointer());
8858   std::vector<const DataArrayDouble *> coordss(4);
8859   coordss[0]=m1->getCoords(); coordss[1]=m2->getCoords(); coordss[2]=addCooDa; coordss[3]=addCoordsQuadraticDa;
8860   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> coo(DataArrayDouble::Aggregate(coordss));
8861   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret(MEDCouplingUMesh::New("Intersect2D",2));
8862   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn(DataArrayInt::New()); conn->alloc((int)cr.size(),1); std::copy(cr.begin(),cr.end(),conn->getPointer());
8863   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> connI(DataArrayInt::New()); connI->alloc((int)crI.size(),1); std::copy(crI.begin(),crI.end(),connI->getPointer());
8864   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> c1(DataArrayInt::New()); c1->alloc((int)cNb1.size(),1); std::copy(cNb1.begin(),cNb1.end(),c1->getPointer());
8865   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> c2(DataArrayInt::New()); c2->alloc((int)cNb2.size(),1); std::copy(cNb2.begin(),cNb2.end(),c2->getPointer());
8866   ret->setConnectivity(conn,connI,true);
8867   ret->setCoords(coo);
8868   cellNb1=c1.retn(); cellNb2=c2.retn();
8869   return ret.retn();
8870 }
8871
8872 /// @cond INTERNAL
8873
8874 bool IsColinearOfACellOf(const std::vector< std::vector<int> >& intersectEdge1, const std::vector<int>& candidates, int start, int stop, int& retVal)
8875 {
8876   if(candidates.empty())
8877     return false;
8878   for(std::vector<int>::const_iterator it=candidates.begin();it!=candidates.end();it++)
8879     {
8880       const std::vector<int>& pool(intersectEdge1[*it]);
8881       int tmp[2]; tmp[0]=start; tmp[1]=stop;
8882       if(std::search(pool.begin(),pool.end(),tmp,tmp+2)!=pool.end())
8883         {
8884           retVal=*it+1;
8885           return true;
8886         }
8887       tmp[0]=stop; tmp[1]=start;
8888       if(std::search(pool.begin(),pool.end(),tmp,tmp+2)!=pool.end())
8889         {
8890           retVal=-*it-1;
8891           return true;
8892         }
8893     }
8894   return false;
8895 }
8896
8897 MEDCouplingUMesh *BuildMesh1DCutFrom(const MEDCouplingUMesh *mesh1D, const std::vector< std::vector<int> >& intersectEdge2, const DataArrayDouble *coords1, const std::vector<double>& addCoo, const std::map<int,int>& mergedNodes, const std::vector< std::vector<int> >& colinear2, const std::vector< std::vector<int> >& intersectEdge1,
8898                                      MEDCouplingAutoRefCountObjectPtr<DataArrayInt>& idsInRetColinear, MEDCouplingAutoRefCountObjectPtr<DataArrayInt>& idsInMesh1DForIdsInRetColinear)
8899 {
8900   idsInRetColinear=DataArrayInt::New(); idsInRetColinear->alloc(0,1);
8901   idsInMesh1DForIdsInRetColinear=DataArrayInt::New(); idsInMesh1DForIdsInRetColinear->alloc(0,1);
8902   int nCells(mesh1D->getNumberOfCells());
8903   if(nCells!=(int)intersectEdge2.size())
8904     throw INTERP_KERNEL::Exception("BuildMesh1DCutFrom : internal error # 1 !");
8905   const DataArrayDouble *coo2(mesh1D->getCoords());
8906   const int *c(mesh1D->getNodalConnectivity()->begin()),*ci(mesh1D->getNodalConnectivityIndex()->begin());
8907   const double *coo2Ptr(coo2->begin());
8908   int offset1(coords1->getNumberOfTuples());
8909   int offset2(offset1+coo2->getNumberOfTuples());
8910   int offset3(offset2+addCoo.size()/2);
8911   std::vector<double> addCooQuad;
8912   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> cOut(DataArrayInt::New()),ciOut(DataArrayInt::New()); cOut->alloc(0,1); ciOut->alloc(1,1); ciOut->setIJ(0,0,0);
8913   int tmp[4],cicnt(0),kk(0);
8914   for(int i=0;i<nCells;i++)
8915     {
8916       std::map<MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Node>,int> m;
8917       INTERP_KERNEL::Edge *e(MEDCouplingUMeshBuildQPFromEdge2((INTERP_KERNEL::NormalizedCellType)c[ci[i]],c+ci[i]+1,coo2Ptr,m));
8918       const std::vector<int>& subEdges(intersectEdge2[i]);
8919       int nbSubEdge(subEdges.size()/2);
8920       for(int j=0;j<nbSubEdge;j++,kk++)
8921         {
8922           MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Node> n1(MEDCouplingUMeshBuildQPNode(subEdges[2*j],coords1->begin(),offset1,coo2Ptr,offset2,addCoo)),n2(MEDCouplingUMeshBuildQPNode(subEdges[2*j+1],coords1->begin(),offset1,coo2Ptr,offset2,addCoo));
8923           MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> e2(e->buildEdgeLyingOnMe(n1,n2));
8924           INTERP_KERNEL::Edge *e2Ptr(e2);
8925           std::map<int,int>::const_iterator itm;
8926           if(dynamic_cast<INTERP_KERNEL::EdgeArcCircle *>(e2Ptr))
8927             {
8928               tmp[0]=INTERP_KERNEL::NORM_SEG3;
8929               itm=mergedNodes.find(subEdges[2*j]);
8930               tmp[1]=itm!=mergedNodes.end()?(*itm).second:subEdges[2*j];
8931               itm=mergedNodes.find(subEdges[2*j+1]);
8932               tmp[2]=itm!=mergedNodes.end()?(*itm).second:subEdges[2*j+1];
8933               tmp[3]=offset3+(int)addCooQuad.size()/2;
8934               double tmp2[2];
8935               e2->getBarycenter(tmp2); addCooQuad.insert(addCooQuad.end(),tmp2,tmp2+2);
8936               cicnt+=4;
8937               cOut->insertAtTheEnd(tmp,tmp+4);
8938               ciOut->pushBackSilent(cicnt);
8939             }
8940           else
8941             {
8942               tmp[0]=INTERP_KERNEL::NORM_SEG2;
8943               itm=mergedNodes.find(subEdges[2*j]);
8944               tmp[1]=itm!=mergedNodes.end()?(*itm).second:subEdges[2*j];
8945               itm=mergedNodes.find(subEdges[2*j+1]);
8946               tmp[2]=itm!=mergedNodes.end()?(*itm).second:subEdges[2*j+1];
8947               cicnt+=3;
8948               cOut->insertAtTheEnd(tmp,tmp+3);
8949               ciOut->pushBackSilent(cicnt);
8950             }
8951           int tmp00;
8952           if(IsColinearOfACellOf(intersectEdge1,colinear2[i],tmp[1],tmp[2],tmp00))
8953             {
8954               idsInRetColinear->pushBackSilent(kk);
8955               idsInMesh1DForIdsInRetColinear->pushBackSilent(tmp00);
8956             }
8957         }
8958       e->decrRef();
8959     }
8960   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret(MEDCouplingUMesh::New(mesh1D->getName(),1));
8961   ret->setConnectivity(cOut,ciOut,true);
8962   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> arr3(DataArrayDouble::New());
8963   arr3->useArray(&addCoo[0],false,C_DEALLOC,(int)addCoo.size()/2,2);
8964   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> arr4(DataArrayDouble::New()); arr4->useArray(&addCooQuad[0],false,C_DEALLOC,(int)addCooQuad.size()/2,2);
8965   std::vector<const DataArrayDouble *> coordss(4);
8966   coordss[0]=coords1; coordss[1]=mesh1D->getCoords(); coordss[2]=arr3; coordss[3]=arr4;
8967   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> arr(DataArrayDouble::Aggregate(coordss));
8968   ret->setCoords(arr);
8969   return ret.retn();
8970 }
8971
8972 MEDCouplingUMesh *BuildRefined2DCellLinear(const DataArrayDouble *coords, const int *descBg, const int *descEnd, const std::vector< std::vector<int> >& intersectEdge1)
8973 {
8974   std::vector<int> allEdges;
8975   for(const int *it2(descBg);it2!=descEnd;it2++)
8976     {
8977       const std::vector<int>& edge1(intersectEdge1[std::abs(*it2)-1]);
8978       if(*it2>0)
8979         allEdges.insert(allEdges.end(),edge1.begin(),edge1.end());
8980       else
8981         allEdges.insert(allEdges.end(),edge1.rbegin(),edge1.rend());
8982     }
8983   std::size_t nb(allEdges.size());
8984   if(nb%2!=0)
8985     throw INTERP_KERNEL::Exception("BuildRefined2DCellLinear : internal error 1 !");
8986   std::size_t nbOfEdgesOf2DCellSplit(nb/2);
8987   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret(MEDCouplingUMesh::New("",2));
8988   ret->setCoords(coords);
8989   ret->allocateCells(1);
8990   std::vector<int> connOut(nbOfEdgesOf2DCellSplit);
8991   for(std::size_t kk=0;kk<nbOfEdgesOf2DCellSplit;kk++)
8992     connOut[kk]=allEdges[2*kk];
8993   ret->insertNextCell(INTERP_KERNEL::NORM_POLYGON,connOut.size(),&connOut[0]);
8994   return ret.retn();
8995 }
8996
8997 MEDCouplingUMesh *BuildRefined2DCellQuadratic(const DataArrayDouble *coords, const MEDCouplingUMesh *mesh2D, int cellIdInMesh2D, const int *descBg, const int *descEnd, const std::vector< std::vector<int> >& intersectEdge1)
8998 {
8999   const int *c(mesh2D->getNodalConnectivity()->begin()),*ci(mesh2D->getNodalConnectivityIndex()->begin());
9000   const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)c[ci[cellIdInMesh2D]]));
9001   std::size_t ii(0);
9002   unsigned sz(cm.getNumberOfSons2(c+ci[cellIdInMesh2D]+1,ci[cellIdInMesh2D+1]-ci[cellIdInMesh2D]-1));
9003   if(sz!=std::distance(descBg,descEnd))
9004     throw INTERP_KERNEL::Exception("BuildRefined2DCellQuadratic : internal error 1 !");
9005   INTERP_KERNEL::AutoPtr<int> tmpPtr(new int[ci[cellIdInMesh2D+1]-ci[cellIdInMesh2D]]);
9006   std::vector<int> allEdges,centers;
9007   const double *coordsPtr(coords->begin());
9008   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> addCoo(DataArrayDouble::New()); addCoo->alloc(0,1);
9009   int offset(coords->getNumberOfTuples());
9010   for(const int *it2(descBg);it2!=descEnd;it2++,ii++)
9011     {
9012       INTERP_KERNEL::NormalizedCellType typeOfSon;
9013       cm.fillSonCellNodalConnectivity2(ii,c+ci[cellIdInMesh2D]+1,ci[cellIdInMesh2D+1]-ci[cellIdInMesh2D]-1,tmpPtr,typeOfSon);
9014       const std::vector<int>& edge1(intersectEdge1[std::abs(*it2)-1]);
9015       if(*it2>0)
9016         allEdges.insert(allEdges.end(),edge1.begin(),edge1.end());
9017       else
9018         allEdges.insert(allEdges.end(),edge1.rbegin(),edge1.rend());
9019       if(edge1.size()==2)
9020         centers.push_back(tmpPtr[2]);//special case where no subsplit of edge -> reuse the original center.
9021       else
9022         {//the current edge has been subsplit -> create corresponding centers.
9023           std::size_t nbOfCentersToAppend(edge1.size()/2);
9024           std::map< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Node>,int> m;
9025           MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> ee(MEDCouplingUMeshBuildQPFromEdge2(typeOfSon,tmpPtr,coordsPtr,m));
9026           std::vector<int>::const_iterator it3(allEdges.end()-edge1.size());
9027           for(std::size_t k=0;k<nbOfCentersToAppend;k++)
9028             {
9029               double tmpp[2];
9030               const double *aa(coordsPtr+2*(*it3++));
9031               const double *bb(coordsPtr+2*(*it3++));
9032               ee->getMiddleOfPoints(aa,bb,tmpp);
9033               addCoo->insertAtTheEnd(tmpp,tmpp+2);
9034               centers.push_back(offset+k);
9035             }
9036         }
9037     }
9038   std::size_t nb(allEdges.size());
9039   if(nb%2!=0)
9040     throw INTERP_KERNEL::Exception("BuildRefined2DCellQuadratic : internal error 2 !");
9041   std::size_t nbOfEdgesOf2DCellSplit(nb/2);
9042   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret(MEDCouplingUMesh::New("",2));
9043   if(addCoo->empty())
9044     ret->setCoords(coords);
9045   else
9046     {
9047       addCoo->rearrange(2);
9048       addCoo=DataArrayDouble::Aggregate(coords,addCoo);
9049       ret->setCoords(addCoo);
9050     }
9051   ret->allocateCells(1);
9052   std::vector<int> connOut(nbOfEdgesOf2DCellSplit);
9053   for(std::size_t kk=0;kk<nbOfEdgesOf2DCellSplit;kk++)
9054     connOut[kk]=allEdges[2*kk];
9055   connOut.insert(connOut.end(),centers.begin(),centers.end());
9056   ret->insertNextCell(INTERP_KERNEL::NORM_QPOLYG,connOut.size(),&connOut[0]);
9057   return ret.retn();
9058 }
9059
9060 /*!
9061  * This method creates a refinement of a cell in \a mesh2D. Those cell is defined by descending connectivity and the sorted subdivided nodal connectivity
9062  * of those edges.
9063  *
9064  * \param [in] mesh2D - The origin 2D mesh. \b Warning \b coords are not those of \a mesh2D. But mesh2D->getCoords()==coords[:mesh2D->getNumberOfNodes()]
9065  */
9066 MEDCouplingUMesh *BuildRefined2DCell(const DataArrayDouble *coords, const MEDCouplingUMesh *mesh2D, int cellIdInMesh2D, const int *descBg, const int *descEnd, const std::vector< std::vector<int> >& intersectEdge1)
9067 {
9068   const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(mesh2D->getTypeOfCell(cellIdInMesh2D)));
9069   if(!cm.isQuadratic())
9070     return BuildRefined2DCellLinear(coords,descBg,descEnd,intersectEdge1);
9071   else
9072     return BuildRefined2DCellQuadratic(coords,mesh2D,cellIdInMesh2D,descBg,descEnd,intersectEdge1);
9073 }
9074
9075 void AddCellInMesh2D(MEDCouplingUMesh *mesh2D, const std::vector<int>& conn, const std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& edges)
9076 {
9077   bool isQuad(false);
9078   for(std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >::const_iterator it=edges.begin();it!=edges.end();it++)
9079     {
9080       const INTERP_KERNEL::Edge *ee(*it);
9081       if(dynamic_cast<const INTERP_KERNEL::EdgeArcCircle *>(ee))
9082         isQuad=true;
9083     }
9084   if(!isQuad)
9085     mesh2D->insertNextCell(INTERP_KERNEL::NORM_POLYGON,conn.size(),&conn[0]);
9086   else
9087     {
9088       const double *coo(mesh2D->getCoords()->begin());
9089       std::size_t sz(conn.size());
9090       std::vector<double> addCoo;
9091       std::vector<int> conn2(conn);
9092       int offset(mesh2D->getNumberOfNodes());
9093       for(std::size_t i=0;i<sz;i++)
9094         {
9095           double tmp[2];
9096           edges[(i+1)%sz]->getMiddleOfPoints(coo+2*conn[i],coo+2*conn[(i+1)%sz],tmp);// tony a chier i+1 -> i
9097           addCoo.insert(addCoo.end(),tmp,tmp+2);
9098           conn2.push_back(offset+(int)i);
9099         }
9100       mesh2D->getCoords()->rearrange(1);
9101       mesh2D->getCoords()->pushBackValsSilent(&addCoo[0],&addCoo[0]+addCoo.size());
9102       mesh2D->getCoords()->rearrange(2);
9103       mesh2D->insertNextCell(INTERP_KERNEL::NORM_QPOLYG,conn2.size(),&conn2[0]);
9104     }
9105 }
9106
9107 /*!
9108  * \b WARNING edges in out1 coming from \a splitMesh1D are \b NOT oriented because only used for equation of curve.
9109  *
9110  * This method cuts in 2 parts the input 2D cell given using boundaries description (\a edge1Bis and \a edge1BisPtr) using
9111  * a set of edges defined in \a splitMesh1D.
9112  */
9113 void BuildMesh2DCutInternal2(const MEDCouplingUMesh *splitMesh1D, const std::vector<int>& edge1Bis, const std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& edge1BisPtr,
9114                              std::vector< std::vector<int> >& out0, std::vector< std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> > >& out1)
9115 {
9116   std::size_t nb(edge1Bis.size()/2);
9117   std::size_t nbOfEdgesOf2DCellSplit(nb/2);
9118   int iEnd(splitMesh1D->getNumberOfCells());
9119   if(iEnd==0)
9120     throw INTERP_KERNEL::Exception("BuildMesh2DCutInternal2 : internal error ! input 1D mesh must have at least one cell !");
9121   std::size_t ii,jj;
9122   const int *cSplitPtr(splitMesh1D->getNodalConnectivity()->begin()),*ciSplitPtr(splitMesh1D->getNodalConnectivityIndex()->begin());
9123   for(ii=0;ii<nb && edge1Bis[2*ii]!=cSplitPtr[ciSplitPtr[0]+1];ii++);
9124   for(jj=ii;jj<nb && edge1Bis[2*jj+1]!=cSplitPtr[ciSplitPtr[iEnd-1]+2];jj++);
9125   //
9126   if(jj==nb)
9127     {//the edges splitMesh1D[iStart:iEnd] does not fully cut the current 2D cell -> single output cell
9128       out0.resize(1); out1.resize(1);
9129       std::vector<int>& connOut(out0[0]);
9130       connOut.resize(nbOfEdgesOf2DCellSplit);
9131       std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& edgesPtr(out1[0]);
9132       edgesPtr.resize(nbOfEdgesOf2DCellSplit);
9133       for(std::size_t kk=0;kk<nbOfEdgesOf2DCellSplit;kk++)
9134         {
9135           connOut[kk]=edge1Bis[2*kk];
9136           edgesPtr[kk]=edge1BisPtr[2*kk];
9137         }
9138     }
9139   else
9140     {
9141       // [i,iEnd[ contains the
9142       out0.resize(2); out1.resize(2);
9143       std::vector<int>& connOutLeft(out0[0]);
9144       std::vector<int>& connOutRight(out0[1]);//connOutLeft should end with edge1Bis[2*ii] and connOutRight should end with edge1Bis[2*jj+1]
9145       std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& eleft(out1[0]);
9146       std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& eright(out1[1]);
9147       for(std::size_t k=ii;k<jj+1;k++)
9148         { connOutLeft.push_back(edge1Bis[2*k+1]); eleft.push_back(edge1BisPtr[2*k+1]); }
9149       std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> > ees(iEnd);
9150       for(int ik=0;ik<iEnd;ik++)
9151         {
9152           std::map< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Node>,int> m;
9153           MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> ee(MEDCouplingUMeshBuildQPFromEdge2((INTERP_KERNEL::NormalizedCellType)cSplitPtr[ciSplitPtr[ik]],cSplitPtr+ciSplitPtr[ik]+1,splitMesh1D->getCoords()->begin(),m));
9154           ees[ik]=ee;
9155         }
9156       for(int ik=iEnd-1;ik>=0;ik--)
9157         connOutLeft.push_back(cSplitPtr[ciSplitPtr[ik]+1]);
9158       for(std::size_t k=jj+1;k<nbOfEdgesOf2DCellSplit+ii;k++)
9159         { connOutRight.push_back(edge1Bis[2*k+1]); eright.push_back(edge1BisPtr[2*k+1]); }
9160       eleft.insert(eleft.end(),ees.rbegin(),ees.rend());
9161       for(int ik=0;ik<iEnd;ik++)
9162         connOutRight.push_back(cSplitPtr[ciSplitPtr[ik]+2]);
9163       eright.insert(eright.end(),ees.begin(),ees.end());
9164     }
9165 }
9166
9167 /// @endcond
9168
9169 /// @cond INTERNAL
9170
9171 struct CellInfo
9172 {
9173 public:
9174   CellInfo() { }
9175   CellInfo(const std::vector<int>& edges, const std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& edgesPtr);
9176 public:
9177   std::vector<int> _edges;
9178   std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> > _edges_ptr;
9179 };
9180
9181 CellInfo::CellInfo(const std::vector<int>& edges, const std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& edgesPtr)
9182 {
9183   std::size_t nbe(edges.size());
9184   std::vector<int> edges2(2*nbe); std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> > edgesPtr2(2*nbe);
9185   for(std::size_t i=0;i<nbe;i++)
9186     {
9187       edges2[2*i]=edges[i]; edges2[2*i+1]=edges[(i+1)%nbe];
9188       edgesPtr2[2*i]=edgesPtr[(i+1)%nbe]; edgesPtr2[2*i+1]=edgesPtr[(i+1)%nbe];//tony a chier
9189     }
9190   _edges.resize(4*nbe); _edges_ptr.resize(4*nbe);
9191   std::copy(edges2.begin(),edges2.end(),_edges.begin()); std::copy(edges2.begin(),edges2.end(),_edges.begin()+2*nbe);
9192   std::copy(edgesPtr2.begin(),edgesPtr2.end(),_edges_ptr.begin()); std::copy(edgesPtr2.begin(),edgesPtr2.end(),_edges_ptr.begin()+2*nbe);
9193 }
9194
9195 class EdgeInfo
9196 {
9197 public:
9198   EdgeInfo(int istart, int iend, const MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh>& mesh):_istart(istart),_iend(iend),_mesh(mesh),_left(-7),_right(-7) { }
9199   EdgeInfo(int istart, int iend, int pos, const MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge>& edge):_istart(istart),_iend(iend),_edge(edge),_left(pos),_right(pos+1) { }
9200   bool isInMyRange(int pos) const { return pos>=_istart && pos<_iend; }
9201   void somethingHappendAt(int pos, const std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& newLeft, const std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& newRight);
9202   void feedEdgeInfoAt(double eps, const MEDCouplingUMesh *mesh2D, int offset, int neighbors[2]) const;
9203 private:
9204   int _istart;
9205   int _iend;
9206   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> _mesh;
9207   MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> _edge;
9208   int _left;
9209   int _right;
9210 };
9211
9212 void EdgeInfo::somethingHappendAt(int pos, const std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& newLeft, const std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& newRight)
9213 {
9214   const MEDCouplingUMesh *mesh(_mesh);
9215   if(mesh)
9216     return ;
9217   if(_right<pos)
9218     return ;
9219   if(_left>pos)
9220     { _left++; _right++; return ; }
9221   if(_right==pos)
9222     {
9223       bool isLeft(std::find(newLeft.begin(),newLeft.end(),_edge)!=newLeft.end()),isRight(std::find(newRight.begin(),newRight.end(),_edge)!=newRight.end());
9224       if((isLeft && isRight) || (!isLeft && !isRight))
9225         throw INTERP_KERNEL::Exception("EdgeInfo::somethingHappendAt : internal error # 1 !");
9226       if(isLeft)
9227         return ;
9228       if(isRight)
9229         {
9230           _right++;
9231           return ;
9232         }
9233     }
9234   if(_left==pos)
9235     {
9236       bool isLeft(std::find(newLeft.begin(),newLeft.end(),_edge)!=newLeft.end()),isRight(std::find(newRight.begin(),newRight.end(),_edge)!=newRight.end());
9237       if((isLeft && isRight) || (!isLeft && !isRight))
9238         throw INTERP_KERNEL::Exception("EdgeInfo::somethingHappendAt : internal error # 2 !");
9239       if(isLeft)
9240         {
9241           _right++;
9242           return ;
9243         }
9244       if(isRight)
9245         {
9246           _left++;
9247           _right++;
9248           return ;
9249         }
9250     }
9251 }
9252
9253 void EdgeInfo::feedEdgeInfoAt(double eps, const MEDCouplingUMesh *mesh2D, int offset, int neighbors[2]) const
9254 {
9255   const MEDCouplingUMesh *mesh(_mesh);
9256   if(!mesh)
9257     {
9258       neighbors[0]=offset+_left; neighbors[1]=offset+_right;
9259     }
9260   else
9261     {// not fully splitting cell case
9262       if(mesh2D->getNumberOfCells()==1)
9263         {//little optimization. 1 cell no need to find in which cell mesh is !
9264           neighbors[0]=offset; neighbors[1]=offset;
9265           return;
9266         }
9267       else
9268         {
9269           MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> barys(mesh->getBarycenterAndOwner());
9270           int cellId(mesh2D->getCellContainingPoint(barys->begin(),eps));
9271           if(cellId==-1)
9272             throw INTERP_KERNEL::Exception("EdgeInfo::feedEdgeInfoAt : internal error !");
9273           neighbors[0]=offset+cellId; neighbors[1]=offset+cellId;
9274         }
9275     }
9276 }
9277
9278 class VectorOfCellInfo
9279 {
9280 public:
9281   VectorOfCellInfo(const std::vector<int>& edges, const std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& edgesPtr);
9282   std::size_t size() const { return _pool.size(); }
9283   int getPositionOf(double eps, const MEDCouplingUMesh *mesh) const;
9284   void setMeshAt(int pos, const MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh>& mesh, int istart, int iend, const MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh>& mesh1DInCase, const std::vector< std::vector<int> >& edges, const std::vector< std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> > >& edgePtrs);
9285   const std::vector<int>& getConnOf(int pos) const { return get(pos)._edges; }
9286   const std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& getEdgePtrOf(int pos) const { return get(pos)._edges_ptr; }
9287   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> getZeMesh() const { return _ze_mesh; }
9288   void feedEdgeInfoAt(double eps, int pos, int offset, int neighbors[2]) const;
9289 private:
9290   int getZePosOfEdgeGivenItsGlobalId(int pos) const;
9291   void updateEdgeInfo(int pos, const std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& newLeft, const std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& newRight);
9292   const CellInfo& get(int pos) const;
9293   CellInfo& get(int pos);
9294 private:
9295   std::vector<CellInfo> _pool;
9296   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> _ze_mesh;
9297   std::vector<EdgeInfo> _edge_info;
9298 };
9299
9300 VectorOfCellInfo::VectorOfCellInfo(const std::vector<int>& edges, const std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& edgesPtr):_pool(1)
9301 {
9302   _pool[0]._edges=edges;
9303   _pool[0]._edges_ptr=edgesPtr;
9304 }
9305
9306 int VectorOfCellInfo::getPositionOf(double eps, const MEDCouplingUMesh *mesh) const
9307 {
9308   if(_pool.empty())
9309     throw INTERP_KERNEL::Exception("VectorOfCellSplitter::getPositionOf : empty !");
9310   if(_pool.size()==1)
9311     return 0;
9312   const MEDCouplingUMesh *zeMesh(_ze_mesh);
9313   if(!zeMesh)
9314     throw INTERP_KERNEL::Exception("VectorOfCellSplitter::getPositionOf : null aggregated mesh !");
9315   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> barys(mesh->getBarycenterAndOwner());
9316   return zeMesh->getCellContainingPoint(barys->begin(),eps);
9317 }
9318
9319 void VectorOfCellInfo::setMeshAt(int pos, const MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh>& mesh, int istart, int iend, const MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh>& mesh1DInCase, const std::vector< std::vector<int> >& edges, const std::vector< std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> > >& edgePtrs)
9320 {
9321   get(pos);//to check pos
9322   bool isFast(pos==0 && _pool.size()==1);
9323   std::size_t sz(edges.size());
9324   // dealing with edges
9325   if(sz==1)
9326     _edge_info.push_back(EdgeInfo(istart,iend,mesh1DInCase));
9327   else
9328     _edge_info.push_back(EdgeInfo(istart,iend,pos,edgePtrs[0].back()));
9329   //
9330   std::vector<CellInfo> pool(_pool.size()-1+sz);
9331   for(int i=0;i<pos;i++)
9332     pool[i]=_pool[i];
9333   for(std::size_t j=0;j<sz;j++)
9334     pool[pos+j]=CellInfo(edges[j],edgePtrs[j]);
9335   for(int i=pos+1;i<(int)_pool.size();i++)
9336     pool[i+sz-1]=_pool[i];
9337   _pool=pool;
9338   //
9339   if(sz==2)
9340     updateEdgeInfo(pos,edgePtrs[0],edgePtrs[1]);
9341   //
9342   if(isFast)
9343     {
9344       _ze_mesh=mesh;
9345       return ;
9346     }
9347   //
9348   std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> > ms;
9349   if(pos>0)
9350     {
9351       MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> elt(static_cast<MEDCouplingUMesh *>(_ze_mesh->buildPartOfMySelf2(0,pos,true)));
9352       ms.push_back(elt);
9353     }
9354   ms.push_back(mesh);
9355   if(pos<_ze_mesh->getNumberOfCells()-1)
9356   {
9357     MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> elt(static_cast<MEDCouplingUMesh *>(_ze_mesh->buildPartOfMySelf2(pos+1,_ze_mesh->getNumberOfCells(),true)));
9358     ms.push_back(elt);
9359   }
9360   std::vector< const MEDCouplingUMesh *> ms2(ms.size());
9361   for(std::size_t j=0;j<ms2.size();j++)
9362     ms2[j]=ms[j];
9363   _ze_mesh=MEDCouplingUMesh::MergeUMeshesOnSameCoords(ms2);
9364 }
9365
9366 void VectorOfCellInfo::feedEdgeInfoAt(double eps, int pos, int offset, int neighbors[2]) const
9367 {
9368   _edge_info[getZePosOfEdgeGivenItsGlobalId(pos)].feedEdgeInfoAt(eps,_ze_mesh,offset,neighbors);
9369 }
9370
9371 int VectorOfCellInfo::getZePosOfEdgeGivenItsGlobalId(int pos) const
9372 {
9373   if(pos<0)
9374     throw INTERP_KERNEL::Exception("VectorOfCellInfo::getZePosOfEdgeGivenItsGlobalId : invalid id ! Must be >=0 !");
9375   int ret(0);
9376   for(std::vector<EdgeInfo>::const_iterator it=_edge_info.begin();it!=_edge_info.end();it++,ret++)
9377     {
9378       if((*it).isInMyRange(pos))
9379         return ret;
9380     }
9381   throw INTERP_KERNEL::Exception("VectorOfCellInfo::getZePosOfEdgeGivenItsGlobalId : invalid id !");
9382 }
9383
9384 void VectorOfCellInfo::updateEdgeInfo(int pos, const std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& newLeft, const std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& newRight)
9385 {
9386   get(pos);//to check;
9387   if(_edge_info.empty())
9388     return ;
9389   std::size_t sz(_edge_info.size()-1);
9390   for(std::size_t i=0;i<sz;i++)
9391     _edge_info[i].somethingHappendAt(pos,newLeft,newRight);
9392 }
9393
9394 const CellInfo& VectorOfCellInfo::get(int pos) const
9395 {
9396   if(pos<0 || pos>=(int)_pool.size())
9397     throw INTERP_KERNEL::Exception("VectorOfCellSplitter::get const : invalid pos !");
9398   return _pool[pos];
9399 }
9400
9401 CellInfo& VectorOfCellInfo::get(int pos)
9402 {
9403   if(pos<0 || pos>=(int)_pool.size())
9404     throw INTERP_KERNEL::Exception("VectorOfCellSplitter::get : invalid pos !");
9405   return _pool[pos];
9406 }
9407
9408 /*!
9409  * Given :
9410  * - a \b closed set of edges ( \a allEdges and \a allEdgesPtr ) that defines the split descending 2D cell.
9411  * - \a splitMesh1D a split 2D curve mesh contained into 2D cell defined above.
9412  *
9413  * This method returns the 2D mesh and feeds \a idsLeftRight using offset.
9414  *
9415  * Algorithm : \a splitMesh1D is cut into contiguous parts. Each contiguous parts will build incrementally the output 2D cells.
9416  *
9417  * \param [in] allEdges a list of pairs (beginNode, endNode). Linked with \a allEdgesPtr to get the equation of edge.
9418  */
9419 MEDCouplingUMesh *BuildMesh2DCutInternal(double eps, const MEDCouplingUMesh *splitMesh1D, const std::vector<int>& allEdges, const std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> >& allEdgesPtr, int offset,
9420                                          MEDCouplingAutoRefCountObjectPtr<DataArrayInt>& idsLeftRight)
9421 {
9422   int nbCellsInSplitMesh1D(splitMesh1D->getNumberOfCells());
9423   if(nbCellsInSplitMesh1D==0)
9424     throw INTERP_KERNEL::Exception("BuildMesh2DCutInternal : internal error ! input 1D mesh must have at least one cell !");
9425   const int *cSplitPtr(splitMesh1D->getNodalConnectivity()->begin()),*ciSplitPtr(splitMesh1D->getNodalConnectivityIndex()->begin());
9426   std::size_t nb(allEdges.size()),jj;
9427   if(nb%2!=0)
9428     throw INTERP_KERNEL::Exception("BuildMesh2DCutFrom : internal error 2 !");
9429   std::vector<int> edge1Bis(nb*2);
9430   std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> > edge1BisPtr(nb*2);
9431   std::copy(allEdges.begin(),allEdges.end(),edge1Bis.begin());
9432   std::copy(allEdges.begin(),allEdges.end(),edge1Bis.begin()+nb);
9433   std::copy(allEdgesPtr.begin(),allEdgesPtr.end(),edge1BisPtr.begin());
9434   std::copy(allEdgesPtr.begin(),allEdgesPtr.end(),edge1BisPtr.begin()+nb);
9435   //
9436   idsLeftRight=DataArrayInt::New(); idsLeftRight->alloc(nbCellsInSplitMesh1D*2); idsLeftRight->fillWithValue(-2); idsLeftRight->rearrange(2);
9437   int *idsLeftRightPtr(idsLeftRight->getPointer());
9438   VectorOfCellInfo pool(edge1Bis,edge1BisPtr);
9439   for(int iStart=0;iStart<nbCellsInSplitMesh1D;)
9440     {// split [0:nbCellsInSplitMesh1D) in contiguous parts [iStart:iEnd)
9441       int iEnd(iStart);
9442       for(;iEnd<nbCellsInSplitMesh1D;)
9443         {
9444           for(jj=0;jj<nb && edge1Bis[2*jj+1]!=cSplitPtr[ciSplitPtr[iEnd]+2];jj++);
9445           if(jj!=nb)
9446             break;
9447           else
9448             iEnd++;
9449         }
9450       if(iEnd<nbCellsInSplitMesh1D)
9451         iEnd++;
9452       //
9453       MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> partOfSplitMesh1D(static_cast<MEDCouplingUMesh *>(splitMesh1D->buildPartOfMySelf2(iStart,iEnd,1,true)));
9454       int pos(pool.getPositionOf(eps,partOfSplitMesh1D));
9455       //
9456       MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh>retTmp(MEDCouplingUMesh::New("",2));
9457       retTmp->setCoords(splitMesh1D->getCoords());
9458       retTmp->allocateCells();
9459
9460       std::vector< std::vector<int> > out0;
9461       std::vector< std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> > > out1;
9462
9463       BuildMesh2DCutInternal2(partOfSplitMesh1D,pool.getConnOf(pos),pool.getEdgePtrOf(pos),out0,out1);
9464       for(std::size_t cnt=0;cnt<out0.size();cnt++)
9465         AddCellInMesh2D(retTmp,out0[cnt],out1[cnt]);
9466       pool.setMeshAt(pos,retTmp,iStart,iEnd,partOfSplitMesh1D,out0,out1);
9467       //
9468       iStart=iEnd;
9469     }
9470   for(int mm=0;mm<nbCellsInSplitMesh1D;mm++)
9471     pool.feedEdgeInfoAt(eps,mm,offset,idsLeftRightPtr+2*mm);
9472   return pool.getZeMesh().retn();
9473 }
9474
9475 MEDCouplingUMesh *BuildMesh2DCutFrom(double eps, int cellIdInMesh2D, const MEDCouplingUMesh *mesh2DDesc, const MEDCouplingUMesh *splitMesh1D,
9476                                      const int *descBg, const int *descEnd, const std::vector< std::vector<int> >& intersectEdge1, int offset,
9477                                      MEDCouplingAutoRefCountObjectPtr<DataArrayInt>& idsLeftRight)
9478 {
9479   const int *cdescPtr(mesh2DDesc->getNodalConnectivity()->begin()),*cidescPtr(mesh2DDesc->getNodalConnectivityIndex()->begin());
9480   //
9481   std::vector<int> allEdges;
9482   std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> > allEdgesPtr; // for each sub edge in splitMesh2D the uncut Edge object of the original mesh2D
9483   for(const int *it(descBg);it!=descEnd;it++) // for all edges in the descending connectivity of the 2D mesh in relative Fortran mode
9484     {
9485       int edgeId(std::abs(*it)-1);
9486       std::map< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Node>,int> m;
9487       MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> ee(MEDCouplingUMeshBuildQPFromEdge2((INTERP_KERNEL::NormalizedCellType)cdescPtr[cidescPtr[edgeId]],cdescPtr+cidescPtr[edgeId]+1,mesh2DDesc->getCoords()->begin(),m));
9488       const std::vector<int>& edge1(intersectEdge1[edgeId]);
9489       if(*it>0)
9490         allEdges.insert(allEdges.end(),edge1.begin(),edge1.end());
9491       else
9492         allEdges.insert(allEdges.end(),edge1.rbegin(),edge1.rend());
9493       std::size_t sz(edge1.size());
9494       for(std::size_t cnt=0;cnt<sz;cnt++)
9495         allEdgesPtr.push_back(ee);
9496     }
9497   //
9498   return BuildMesh2DCutInternal(eps,splitMesh1D,allEdges,allEdgesPtr,offset,idsLeftRight);
9499 }
9500
9501 bool AreEdgeEqual(const double *coo2D, const INTERP_KERNEL::CellModel& typ1, const int *conn1, const INTERP_KERNEL::CellModel& typ2, const int *conn2, double eps)
9502 {
9503   if(!typ1.isQuadratic() && !typ2.isQuadratic())
9504     {//easy case comparison not
9505       return conn1[0]==conn2[0] && conn1[1]==conn2[1];
9506     }
9507   else if(typ1.isQuadratic() && typ2.isQuadratic())
9508     {
9509       bool status0(conn1[0]==conn2[0] && conn1[1]==conn2[1]);
9510       if(!status0)
9511         return false;
9512       if(conn1[2]==conn2[2])
9513         return true;
9514       const double *a(coo2D+2*conn1[2]),*b(coo2D+2*conn2[2]);
9515       double dist(sqrt((a[0]-b[0])*(a[0]-b[0])+(a[1]-b[1])*(a[1]-b[1])));
9516       return dist<eps;
9517     }
9518   else
9519     {//only one is quadratic
9520       bool status0(conn1[0]==conn2[0] && conn1[1]==conn2[1]);
9521       if(!status0)
9522         return false;
9523       const double *a(0),*bb(0),*be(0);
9524       if(typ1.isQuadratic())
9525         {
9526           a=coo2D+2*conn1[2]; bb=coo2D+2*conn2[0]; be=coo2D+2*conn2[1];
9527         }
9528       else
9529         {
9530           a=coo2D+2*conn2[2]; bb=coo2D+2*conn1[0]; be=coo2D+2*conn1[1];
9531         }
9532       double b[2]; b[0]=(be[0]+bb[0])/2.; b[1]=(be[1]+bb[1])/2.;
9533       double dist(sqrt((a[0]-b[0])*(a[0]-b[0])+(a[1]-b[1])*(a[1]-b[1])));
9534       return dist<eps;
9535     }
9536 }
9537
9538 /*!
9539  * This method returns among the cellIds [ \a candidatesIn2DBg , \a candidatesIn2DEnd ) in \a mesh2DSplit those exactly sharing \a cellIdInMesh1DSplitRelative in \a mesh1DSplit.
9540  * \a mesh2DSplit and \a mesh1DSplit are expected to share the coordinates array.
9541  *
9542  * \param [in] cellIdInMesh1DSplitRelative is in Fortran mode using sign to specify direction.
9543  */
9544 int FindRightCandidateAmong(const MEDCouplingUMesh *mesh2DSplit, const int *candidatesIn2DBg, const int *candidatesIn2DEnd, const MEDCouplingUMesh *mesh1DSplit, int cellIdInMesh1DSplitRelative, double eps)
9545 {
9546   if(candidatesIn2DEnd==candidatesIn2DBg)
9547     throw INTERP_KERNEL::Exception("FindRightCandidateAmong : internal error 1 !");
9548   const double *coo(mesh2DSplit->getCoords()->begin());
9549   if(std::distance(candidatesIn2DBg,candidatesIn2DEnd)==1)
9550     return *candidatesIn2DBg;
9551   int edgeId(std::abs(cellIdInMesh1DSplitRelative)-1);
9552   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> cur1D(static_cast<MEDCouplingUMesh *>(mesh1DSplit->buildPartOfMySelf(&edgeId,&edgeId+1,true)));
9553   if(cellIdInMesh1DSplitRelative<0)
9554     cur1D->changeOrientationOfCells();
9555   const int *c1D(cur1D->getNodalConnectivity()->begin());
9556   const INTERP_KERNEL::CellModel& ref1DType(INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)c1D[0]));
9557   for(const int *it=candidatesIn2DBg;it!=candidatesIn2DEnd;it++)
9558     {
9559       MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> cur2D(static_cast<MEDCouplingUMesh *>(mesh2DSplit->buildPartOfMySelf(it,it+1,true)));
9560       const int *c(cur2D->getNodalConnectivity()->begin()),*ci(cur2D->getNodalConnectivityIndex()->begin());
9561       const INTERP_KERNEL::CellModel &cm(INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)c[ci[0]]));
9562       unsigned sz(cm.getNumberOfSons2(c+ci[0]+1,ci[1]-ci[0]-1));
9563       INTERP_KERNEL::AutoPtr<int> tmpPtr(new int[ci[1]-ci[0]]);
9564       for(unsigned it2=0;it2<sz;it2++)
9565         {
9566           INTERP_KERNEL::NormalizedCellType typeOfSon;
9567           cm.fillSonCellNodalConnectivity2(it2,c+ci[0]+1,ci[1]-ci[0]-1,tmpPtr,typeOfSon);
9568           const INTERP_KERNEL::CellModel &curCM(INTERP_KERNEL::CellModel::GetCellModel(typeOfSon));
9569           if(AreEdgeEqual(coo,ref1DType,c1D+1,curCM,tmpPtr,eps))
9570             return *it;
9571         }
9572     }
9573   throw INTERP_KERNEL::Exception("FindRightCandidateAmong : internal error 2 ! Unable to find the edge among split cell !");
9574 }
9575
9576 /// @endcond
9577
9578 /*!
9579  * Partitions the first given 2D mesh using the second given 1D mesh as a tool.
9580  * Thus the final result contains the aggregation of nodes of \a mesh2D, then nodes of \a mesh1D, then new nodes that are the result of the intersection
9581  * and finaly, in case of quadratic polygon the centers of edges new nodes.
9582  * The meshes should be in 2D space. In addition, returns two arrays mapping cells of the resulting mesh to cells of the input.
9583  *
9584  * \param [in] mesh2D - the 2D mesh (spacedim=meshdim=2) to be intersected using \a mesh1D tool. The mesh must be so that each point in the space covered by \a mesh2D
9585  *                      must be covered exactly by one entity, \b no \b more. If it is not the case, some tools are available to heal the mesh (conformize2D, mergeNodes)
9586  * \param [in] mesh1D - the 1D mesh (spacedim=2 meshdim=1) the is the tool that will be used to intersect \a mesh2D. \a mesh1D must be ordered consecutively. If it is not the case
9587  *                      you can invoke orderConsecutiveCells1D on \a mesh1D.
9588  * \param [in] eps - precision used to perform intersections and localization operations.
9589  * \param [out] splitMesh2D - the result of the split of \a mesh2D mesh.
9590  * \param [out] splitMesh1D - the result of the split of \a mesh1D mesh.
9591  * \param [out] cellIdInMesh2D - the array that gives for each cell id \a i in \a splitMesh2D the id in \a mesh2D it comes from.
9592  *                               So this array has a number of tuples equal to the number of cells of \a splitMesh2D and a number of component equal to 1.
9593  * \param [out] cellIdInMesh1D - the array of pair that gives for each cell id \a i in \a splitMesh1D the cell in \a splitMesh2D on the left for the 1st component
9594  *                               and the cell in \a splitMesh2D on the right for the 2nt component. -1 means no cell.
9595  *                               So this array has a number of tuples equal to the number of cells of \a splitMesh1D and a number of components equal to 2.
9596  *
9597  * \sa Intersect2DMeshes, orderConsecutiveCells1D, conformize2D, mergeNodes
9598  */
9599 void MEDCouplingUMesh::Intersect2DMeshWith1DLine(const MEDCouplingUMesh *mesh2D, const MEDCouplingUMesh *mesh1D, double eps, MEDCouplingUMesh *&splitMesh2D, MEDCouplingUMesh *&splitMesh1D, DataArrayInt *&cellIdInMesh2D, DataArrayInt *&cellIdInMesh1D)
9600 {
9601   if(!mesh2D || !mesh1D)
9602     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::Intersect2DMeshWith1DLine : input meshes must be not NULL !");
9603   mesh2D->checkFullyDefined();
9604   mesh1D->checkFullyDefined();
9605   const std::vector<std::string>& compNames(mesh2D->getCoords()->getInfoOnComponents());
9606   if(mesh2D->getMeshDimension()!=2 || mesh2D->getSpaceDimension()!=2 || mesh1D->getMeshDimension()!=1 || mesh1D->getSpaceDimension()!=2)
9607     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::Intersect2DMeshWith1DLine works with mesh2D with spacedim=meshdim=2 and mesh1D with meshdim=1 spaceDim=2 !");
9608   // Step 1: compute all edge intersections (new nodes)
9609   std::vector< std::vector<int> > intersectEdge1, colinear2, subDiv2;
9610   std::vector<double> addCoo,addCoordsQuadratic;  // coordinates of newly created nodes
9611   INTERP_KERNEL::QUADRATIC_PLANAR::_precision=eps;
9612   INTERP_KERNEL::QUADRATIC_PLANAR::_arc_detection_precision=eps;
9613   //
9614   // Build desc connectivity
9615   DataArrayInt *desc1(DataArrayInt::New()),*descIndx1(DataArrayInt::New()),*revDesc1(DataArrayInt::New()),*revDescIndx1(DataArrayInt::New());
9616   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> dd1(desc1),dd2(descIndx1),dd3(revDesc1),dd4(revDescIndx1);
9617   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m1Desc(mesh2D->buildDescendingConnectivity2(desc1,descIndx1,revDesc1,revDescIndx1));
9618   std::map<int,int> mergedNodes;
9619   Intersect1DMeshes(m1Desc,mesh1D,eps,intersectEdge1,colinear2,subDiv2,addCoo,mergedNodes);
9620   // use mergeNodes to fix intersectEdge1
9621   for(std::vector< std::vector<int> >::iterator it0=intersectEdge1.begin();it0!=intersectEdge1.end();it0++)
9622     {
9623       std::size_t n((*it0).size()/2);
9624       int eltStart((*it0)[0]),eltEnd((*it0)[2*n-1]);
9625       std::map<int,int>::const_iterator it1;
9626       it1=mergedNodes.find(eltStart);
9627       if(it1!=mergedNodes.end())
9628         (*it0)[0]=(*it1).second;
9629       it1=mergedNodes.find(eltEnd);
9630       if(it1!=mergedNodes.end())
9631         (*it0)[2*n-1]=(*it1).second;
9632     }
9633   //
9634   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> addCooDa(DataArrayDouble::New());
9635   addCooDa->useArray(&addCoo[0],false,C_DEALLOC,(int)addCoo.size()/2,2);
9636   // Step 2: re-order newly created nodes according to the ordering found in m2
9637   std::vector< std::vector<int> > intersectEdge2;
9638   BuildIntersectEdges(m1Desc,mesh1D,addCoo,subDiv2,intersectEdge2);
9639   subDiv2.clear();
9640   // Step 3: compute splitMesh1D
9641   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> idsInRet1Colinear,idsInDescMesh2DForIdsInRetColinear;
9642   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret2(DataArrayInt::New()); ret2->alloc(0,1);
9643   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret1(BuildMesh1DCutFrom(mesh1D,intersectEdge2,mesh2D->getCoords(),addCoo,mergedNodes,colinear2,intersectEdge1,
9644       idsInRet1Colinear,idsInDescMesh2DForIdsInRetColinear));
9645   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret3(DataArrayInt::New()); ret3->alloc(ret1->getNumberOfCells()*2,1); ret3->fillWithValue(std::numeric_limits<int>::max()); ret3->rearrange(2);
9646   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> idsInRet1NotColinear(idsInRet1Colinear->buildComplement(ret1->getNumberOfCells()));
9647   // deal with cells in mesh2D that are not cut but only some of their edges are
9648   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> idsInDesc2DToBeRefined(idsInDescMesh2DForIdsInRetColinear->deepCpy());
9649   idsInDesc2DToBeRefined->abs(); idsInDesc2DToBeRefined->applyLin(1,-1);
9650   idsInDesc2DToBeRefined=idsInDesc2DToBeRefined->buildUnique();
9651   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> out0s;//ids in mesh2D that are impacted by the fact that some edges of \a mesh1D are part of the edges of those cells
9652   if(!idsInDesc2DToBeRefined->empty())
9653     {
9654       DataArrayInt *out0(0),*outi0(0);
9655       MEDCouplingUMesh::ExtractFromIndexedArrays(idsInDesc2DToBeRefined->begin(),idsInDesc2DToBeRefined->end(),dd3,dd4,out0,outi0);
9656       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> outi0s(outi0);
9657       out0s=out0;
9658       out0s=out0s->buildUnique();
9659       out0s->sort(true);
9660     }
9661   //
9662   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret1NonCol(static_cast<MEDCouplingUMesh *>(ret1->buildPartOfMySelf(idsInRet1NotColinear->begin(),idsInRet1NotColinear->end())));
9663   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> baryRet1(ret1NonCol->getBarycenterAndOwner());
9664   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> elts,eltsIndex;
9665   mesh2D->getCellsContainingPoints(baryRet1->begin(),baryRet1->getNumberOfTuples(),eps,elts,eltsIndex);
9666   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> eltsIndex2(eltsIndex->deltaShiftIndex());
9667   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> eltsIndex3(eltsIndex2->getIdsEqual(1));
9668   if(eltsIndex2->count(0)+eltsIndex3->getNumberOfTuples()!=ret1NonCol->getNumberOfCells())
9669     throw INTERP_KERNEL::Exception("Intersect2DMeshWith1DLine : internal error 1 !");
9670   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> cellsToBeModified(elts->buildUnique());
9671   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> untouchedCells(cellsToBeModified->buildComplement(mesh2D->getNumberOfCells()));
9672   if((DataArrayInt *)out0s)
9673     untouchedCells=untouchedCells->buildSubstraction(out0s);//if some edges in ret1 are colinear to descending mesh of mesh2D remove cells from untouched one
9674   std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> > outMesh2DSplit;
9675   // OK all is ready to insert in ret2 mesh
9676   if(!untouchedCells->empty())
9677     {// the most easy part, cells in mesh2D not impacted at all
9678       outMesh2DSplit.push_back(static_cast<MEDCouplingUMesh *>(mesh2D->buildPartOfMySelf(untouchedCells->begin(),untouchedCells->end())));
9679       outMesh2DSplit.back()->setCoords(ret1->getCoords());
9680       ret2->pushBackValsSilent(untouchedCells->begin(),untouchedCells->end());
9681     }
9682   if((DataArrayInt *)out0s)
9683     {// here dealing with cells in out0s but not in cellsToBeModified
9684       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> fewModifiedCells(out0s->buildSubstraction(cellsToBeModified));
9685       const int *rdptr(dd3->begin()),*rdiptr(dd4->begin()),*dptr(dd1->begin()),*diptr(dd2->begin());
9686       for(const int *it=fewModifiedCells->begin();it!=fewModifiedCells->end();it++)
9687         {
9688           outMesh2DSplit.push_back(BuildRefined2DCell(ret1->getCoords(),mesh2D,*it,dptr+diptr[*it],dptr+diptr[*it+1],intersectEdge1));
9689           ret1->setCoords(outMesh2DSplit.back()->getCoords());
9690         }
9691       int offset(ret2->getNumberOfTuples());
9692       ret2->pushBackValsSilent(fewModifiedCells->begin(),fewModifiedCells->end());
9693       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> partOfRet3(DataArrayInt::New()); partOfRet3->alloc(2*idsInRet1Colinear->getNumberOfTuples(),1);
9694       partOfRet3->fillWithValue(std::numeric_limits<int>::max()); partOfRet3->rearrange(2);
9695       int kk(0),*ret3ptr(partOfRet3->getPointer());
9696       for(const int *it=idsInDescMesh2DForIdsInRetColinear->begin();it!=idsInDescMesh2DForIdsInRetColinear->end();it++,kk++)
9697         {
9698           int faceId(std::abs(*it)-1);
9699           for(const int *it2=rdptr+rdiptr[faceId];it2!=rdptr+rdiptr[faceId+1];it2++)
9700             {
9701               int tmp(fewModifiedCells->locateValue(*it2));
9702               if(tmp!=-1)
9703                 {
9704                   if(std::find(dptr+diptr[*it2],dptr+diptr[*it2+1],-(*it))!=dptr+diptr[*it2+1])
9705                     ret3ptr[2*kk]=tmp+offset;
9706                   if(std::find(dptr+diptr[*it2],dptr+diptr[*it2+1],(*it))!=dptr+diptr[*it2+1])
9707                     ret3ptr[2*kk+1]=tmp+offset;
9708                 }
9709               else
9710                 {//the current edge is shared by a 2D cell that will be split just after
9711                   if(std::find(dptr+diptr[*it2],dptr+diptr[*it2+1],-(*it))!=dptr+diptr[*it2+1])
9712                     ret3ptr[2*kk]=-(*it2+1);
9713                   if(std::find(dptr+diptr[*it2],dptr+diptr[*it2+1],(*it))!=dptr+diptr[*it2+1])
9714                     ret3ptr[2*kk+1]=-(*it2+1);
9715                 }
9716             }
9717         }
9718       m1Desc->setCoords(ret1->getCoords());
9719       ret1NonCol->setCoords(ret1->getCoords());
9720       ret3->setPartOfValues3(partOfRet3,idsInRet1Colinear->begin(),idsInRet1Colinear->end(),0,2,1,true);
9721       if(!outMesh2DSplit.empty())
9722         {
9723           DataArrayDouble *da(outMesh2DSplit.back()->getCoords());
9724           for(std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> >::iterator itt=outMesh2DSplit.begin();itt!=outMesh2DSplit.end();itt++)
9725             (*itt)->setCoords(da);
9726         }
9727     }
9728   cellsToBeModified=cellsToBeModified->buildUniqueNotSorted();
9729   for(const int *it=cellsToBeModified->begin();it!=cellsToBeModified->end();it++)
9730     {
9731       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> idsNonColPerCell(elts->getIdsEqual(*it));
9732       idsNonColPerCell->transformWithIndArr(eltsIndex3->begin(),eltsIndex3->end());
9733       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> idsNonColPerCell2(idsInRet1NotColinear->selectByTupleId(idsNonColPerCell->begin(),idsNonColPerCell->end()));
9734       MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> partOfMesh1CuttingCur2DCell(static_cast<MEDCouplingUMesh *>(ret1NonCol->buildPartOfMySelf(idsNonColPerCell->begin(),idsNonColPerCell->end())));
9735       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> partOfRet3;
9736       MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> splitOfOneCell(BuildMesh2DCutFrom(eps,*it,m1Desc,partOfMesh1CuttingCur2DCell,dd1->begin()+dd2->getIJ(*it,0),dd1->begin()+dd2->getIJ((*it)+1,0),intersectEdge1,ret2->getNumberOfTuples(),partOfRet3));
9737       ret3->setPartOfValues3(partOfRet3,idsNonColPerCell2->begin(),idsNonColPerCell2->end(),0,2,1,true);
9738       outMesh2DSplit.push_back(splitOfOneCell);
9739       for(int i=0;i<splitOfOneCell->getNumberOfCells();i++)
9740         ret2->pushBackSilent(*it);
9741     }
9742   //
9743   std::size_t nbOfMeshes(outMesh2DSplit.size());
9744   std::vector<const MEDCouplingUMesh *> tmp(nbOfMeshes);
9745   for(std::size_t i=0;i<nbOfMeshes;i++)
9746     tmp[i]=outMesh2DSplit[i];
9747   //
9748   ret1->getCoords()->setInfoOnComponents(compNames);
9749   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret2D(MEDCouplingUMesh::MergeUMeshesOnSameCoords(tmp));
9750   // To finish - filter ret3 - std::numeric_limits<int>::max() -> -1 - negate values must be resolved.
9751   ret3->rearrange(1);
9752   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> edgesToDealWith(ret3->getIdsStrictlyNegative());
9753   for(const int *it=edgesToDealWith->begin();it!=edgesToDealWith->end();it++)
9754     {
9755       int old2DCellId(-ret3->getIJ(*it,0)-1);
9756       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> candidates(ret2->getIdsEqual(old2DCellId));
9757       ret3->setIJ(*it,0,FindRightCandidateAmong(ret2D,candidates->begin(),candidates->end(),ret1,*it%2==0?-((*it)/2+1):(*it)/2+1,eps));// div by 2 because 2 components natively in ret3
9758     }
9759   ret3->replaceOneValByInThis(std::numeric_limits<int>::max(),-1);
9760   ret3->rearrange(2);
9761   //
9762   splitMesh1D=ret1.retn();
9763   splitMesh2D=ret2D.retn();
9764   cellIdInMesh2D=ret2.retn();
9765   cellIdInMesh1D=ret3.retn();
9766 }
9767
9768 /**
9769  * Private. Third step of the partitioning algorithm (Intersect2DMeshes): reconstruct full 2D cells from the
9770  * (newly created) nodes corresponding to the edge intersections.
9771  * Output params:
9772  * @param[out] cr, crI connectivity of the resulting mesh
9773  * @param[out] cNb1, cNb2 correspondance arrays giving for the merged mesh the initial cells IDs in m1 / m2
9774  * TODO: describe input parameters
9775  */
9776 void MEDCouplingUMesh::BuildIntersecting2DCellsFromEdges(double eps, const MEDCouplingUMesh *m1, const int *desc1, const int *descIndx1,
9777                                                          const std::vector<std::vector<int> >& intesctEdges1, const std::vector< std::vector<int> >& colinear2,
9778                                                          const MEDCouplingUMesh *m2, const int *desc2, const int *descIndx2, const std::vector<std::vector<int> >& intesctEdges2,
9779                                                          const std::vector<double>& addCoords,
9780                                                          std::vector<double>& addCoordsQuadratic, std::vector<int>& cr, std::vector<int>& crI, std::vector<int>& cNb1, std::vector<int>& cNb2)
9781 {
9782   static const int SPACEDIM=2;
9783   const double *coo1(m1->getCoords()->getConstPointer());
9784   const int *conn1(m1->getNodalConnectivity()->getConstPointer()),*connI1(m1->getNodalConnectivityIndex()->getConstPointer());
9785   int offset1(m1->getNumberOfNodes());
9786   const double *coo2(m2->getCoords()->getConstPointer());
9787   const int *conn2(m2->getNodalConnectivity()->getConstPointer()),*connI2(m2->getNodalConnectivityIndex()->getConstPointer());
9788   int offset2(offset1+m2->getNumberOfNodes());
9789   int offset3(offset2+((int)addCoords.size())/2);
9790   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> bbox1Arr(m1->getBoundingBoxForBBTree()),bbox2Arr(m2->getBoundingBoxForBBTree());
9791   const double *bbox1(bbox1Arr->begin()),*bbox2(bbox2Arr->begin());
9792   // Here a BBTree on 2D-cells, not on segments:
9793   BBTree<SPACEDIM,int> myTree(bbox2,0,0,m2->getNumberOfCells(),eps);
9794   int ncell1(m1->getNumberOfCells());
9795   crI.push_back(0);
9796   for(int i=0;i<ncell1;i++)
9797     {
9798       std::vector<int> candidates2;
9799       myTree.getIntersectingElems(bbox1+i*2*SPACEDIM,candidates2);
9800       std::map<INTERP_KERNEL::Node *,int> mapp;
9801       std::map<int,INTERP_KERNEL::Node *> mappRev;
9802       INTERP_KERNEL::QuadraticPolygon pol1;
9803       INTERP_KERNEL::NormalizedCellType typ=(INTERP_KERNEL::NormalizedCellType)conn1[connI1[i]];
9804       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(typ);
9805       // Populate mapp and mappRev with nodes from the current cell (i) from mesh1 - this also builds the Node* objects:
9806       MEDCouplingUMeshBuildQPFromMesh3(coo1,offset1,coo2,offset2,addCoords,desc1+descIndx1[i],desc1+descIndx1[i+1],intesctEdges1,/* output */mapp,mappRev);
9807       // pol1 is the full cell from mesh2, in QP format, with all the additional intersecting nodes.
9808       pol1.buildFromCrudeDataArray(mappRev,cm.isQuadratic(),conn1+connI1[i]+1,coo1,
9809           desc1+descIndx1[i],desc1+descIndx1[i+1],intesctEdges1);
9810       //
9811       std::set<INTERP_KERNEL::Edge *> edges1;// store all edges of pol1 that are NOT consumed by intersect cells. If any after iteration over candidates2 -> a part of pol1 should appear in result
9812       std::set<INTERP_KERNEL::Edge *> edgesBoundary2;// store all edges that are on boundary of (pol2 intersect pol1) minus edges on pol1.
9813       INTERP_KERNEL::IteratorOnComposedEdge it1(&pol1);
9814       for(it1.first();!it1.finished();it1.next())
9815         edges1.insert(it1.current()->getPtr());
9816       //
9817       std::map<int,std::vector<INTERP_KERNEL::ElementaryEdge *> > edgesIn2ForShare; // common edges
9818       std::vector<INTERP_KERNEL::QuadraticPolygon> pol2s(candidates2.size());
9819       int ii=0;
9820       for(std::vector<int>::const_iterator it2=candidates2.begin();it2!=candidates2.end();it2++,ii++)
9821         {
9822           INTERP_KERNEL::NormalizedCellType typ2=(INTERP_KERNEL::NormalizedCellType)conn2[connI2[*it2]];
9823           const INTERP_KERNEL::CellModel& cm2=INTERP_KERNEL::CellModel::GetCellModel(typ2);
9824           // Complete mapping with elements coming from the current cell it2 in mesh2:
9825           MEDCouplingUMeshBuildQPFromMesh3(coo1,offset1,coo2,offset2,addCoords,desc2+descIndx2[*it2],desc2+descIndx2[*it2+1],intesctEdges2,/* output */mapp,mappRev);
9826           // pol2 is the new QP in the final merged result.
9827           pol2s[ii].buildFromCrudeDataArray2(mappRev,cm2.isQuadratic(),conn2+connI2[*it2]+1,coo2,desc2+descIndx2[*it2],desc2+descIndx2[*it2+1],intesctEdges2,
9828               pol1,desc1+descIndx1[i],desc1+descIndx1[i+1],intesctEdges1,colinear2, /* output */ edgesIn2ForShare);
9829         }
9830       ii=0;
9831       for(std::vector<int>::const_iterator it2=candidates2.begin();it2!=candidates2.end();it2++,ii++)
9832         {
9833           INTERP_KERNEL::ComposedEdge::InitLocationsWithOther(pol1,pol2s[ii]);
9834           pol2s[ii].updateLocOfEdgeFromCrudeDataArray2(desc2+descIndx2[*it2],desc2+descIndx2[*it2+1],intesctEdges2,pol1,desc1+descIndx1[i],desc1+descIndx1[i+1],intesctEdges1,colinear2);
9835           //MEDCouplingUMeshAssignOnLoc(pol1,pol2,desc1+descIndx1[i],desc1+descIndx1[i+1],intesctEdges1,desc2+descIndx2[*it2],desc2+descIndx2[*it2+1],intesctEdges2,colinear2);
9836           pol1.buildPartitionsAbs(pol2s[ii],edges1,edgesBoundary2,mapp,i,*it2,offset3,addCoordsQuadratic,cr,crI,cNb1,cNb2);
9837         }
9838       // Deals with remaining (non-consumed) edges from m1: these are the edges that were never touched
9839       // by m2 but that we still want to keep in the final result.
9840       if(!edges1.empty())
9841         {
9842           try
9843           {
9844               INTERP_KERNEL::QuadraticPolygon::ComputeResidual(pol1,edges1,edgesBoundary2,mapp,offset3,i,addCoordsQuadratic,cr,crI,cNb1,cNb2);
9845           }
9846           catch(INTERP_KERNEL::Exception& e)
9847           {
9848               std::ostringstream oss; oss << "Error when computing residual of cell #" << i << " in source/m1 mesh ! Maybe the neighbours of this cell in mesh are not well connected !\n" << "The deep reason is the following : " << e.what();
9849               throw INTERP_KERNEL::Exception(oss.str().c_str());
9850           }
9851         }
9852       for(std::map<int,INTERP_KERNEL::Node *>::const_iterator it=mappRev.begin();it!=mappRev.end();it++)
9853         (*it).second->decrRef();
9854     }
9855 }
9856
9857 /**
9858  * Provides a renumbering of the cells of this (which has to be a piecewise connected 1D line), so that
9859  * the segments of the line are indexed in consecutive order (i.e. cells \a i and \a i+1 are neighbors).
9860  * This doesn't modify the mesh. This method only works using nodal connectivity consideration. Coordinates of nodes are ignored here.
9861  * The caller is to deal with the resulting DataArrayInt.
9862  *  \throw If the coordinate array is not set.
9863  *  \throw If the nodal connectivity of the cells is not defined.
9864  *  \throw If m1 is not a mesh of dimension 2, or m1 is not a mesh of dimension 1
9865  *  \throw If m2 is not a (piecewise) line (i.e. if a point has more than 2 adjacent segments)
9866  *
9867  * \sa DataArrayInt::sortEachPairToMakeALinkedList
9868  */
9869 DataArrayInt *MEDCouplingUMesh::orderConsecutiveCells1D() const
9870 {
9871   checkFullyDefined();
9872   if(getMeshDimension()!=1)
9873     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::orderConsecutiveCells1D works on unstructured mesh with meshdim = 1 !");
9874
9875   // Check that this is a line (and not a more complex 1D mesh) - each point is used at most by 2 segments:
9876   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> _d(DataArrayInt::New()),_dI(DataArrayInt::New());
9877   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> _rD(DataArrayInt::New()),_rDI(DataArrayInt::New());
9878   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> m_points(buildDescendingConnectivity(_d, _dI, _rD, _rDI));
9879   const int *d(_d->getConstPointer()), *dI(_dI->getConstPointer());
9880   const int *rD(_rD->getConstPointer()), *rDI(_rDI->getConstPointer());
9881   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> _dsi(_rDI->deltaShiftIndex());
9882   const int * dsi(_dsi->getConstPointer());
9883   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> dsii = _dsi->getIdsNotInRange(0,3);
9884   m_points=0;
9885   if (dsii->getNumberOfTuples())
9886     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::orderConsecutiveCells1D only work with a mesh being a (piecewise) connected line!");
9887
9888   int nc(getNumberOfCells());
9889   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> result(DataArrayInt::New());
9890   result->alloc(nc,1);
9891
9892   // set of edges not used so far
9893   std::set<int> edgeSet;
9894   for (int i=0; i<nc; edgeSet.insert(i), i++);
9895
9896   int startSeg=0;
9897   int newIdx=0;
9898   // while we have points with only one neighbor segments
9899   do
9900     {
9901       std::list<int> linePiece;
9902       // fills a list of consecutive segment linked to startSeg. This can go forward or backward.
9903       for (int direction=0;direction<2;direction++) // direction=0 --> forward, direction=1 --> backward
9904         {
9905           // Fill the list forward (resp. backward) from the start segment:
9906           int activeSeg = startSeg;
9907           int prevPointId = -20;
9908           int ptId;
9909           while (!edgeSet.empty())
9910             {
9911               if (!(direction == 1 && prevPointId==-20)) // prevent adding twice startSeg
9912                 {
9913                   if (direction==0)
9914                     linePiece.push_back(activeSeg);
9915                   else
9916                     linePiece.push_front(activeSeg);
9917                   edgeSet.erase(activeSeg);
9918                 }
9919
9920               int ptId1 = d[dI[activeSeg]], ptId2 = d[dI[activeSeg]+1];
9921               ptId = direction ? (ptId1 == prevPointId ? ptId2 : ptId1) : (ptId2 == prevPointId ? ptId1 : ptId2);
9922               if (dsi[ptId] == 1) // hitting the end of the line
9923                 break;
9924               prevPointId = ptId;
9925               int seg1 = rD[rDI[ptId]], seg2 = rD[rDI[ptId]+1];
9926               activeSeg = (seg1 == activeSeg) ? seg2 : seg1;
9927             }
9928         }
9929       // Done, save final piece into DA:
9930       std::copy(linePiece.begin(), linePiece.end(), result->getPointer()+newIdx);
9931       newIdx += linePiece.size();
9932
9933       // identify next valid start segment (one which is not consumed)
9934       if(!edgeSet.empty())
9935         startSeg = *(edgeSet.begin());
9936     }
9937   while (!edgeSet.empty());
9938   return result.retn();
9939 }
9940
9941 /// @cond INTERNAL
9942
9943 void IKGeo2DInternalMapper2(INTERP_KERNEL::Node *n, const std::map<MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Node>,int>& m, int forbVal0, int forbVal1, std::vector<int>& isect)
9944 {
9945   MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Node> nTmp(n); nTmp->incrRef();
9946   std::map<MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Node>,int>::const_iterator it(m.find(nTmp));
9947   if(it==m.end())
9948     throw INTERP_KERNEL::Exception("Internal error in remapping !");
9949   int v((*it).second);
9950   if(v==forbVal0 || v==forbVal1)
9951     return ;
9952   if(std::find(isect.begin(),isect.end(),v)==isect.end())
9953     isect.push_back(v);
9954 }
9955
9956 bool IKGeo2DInternalMapper(const INTERP_KERNEL::ComposedEdge& c, const std::map<MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Node>,int>& m, int forbVal0, int forbVal1, std::vector<int>& isect)
9957 {
9958   int sz(c.size());
9959   if(sz<=1)
9960     return false;
9961   bool presenceOfOn(false);
9962   for(int i=0;i<sz;i++)
9963     {
9964       INTERP_KERNEL::ElementaryEdge *e(c[i]);
9965       if(e->getLoc()!=INTERP_KERNEL::FULL_ON_1)
9966         continue ;
9967       IKGeo2DInternalMapper2(e->getStartNode(),m,forbVal0,forbVal1,isect);
9968       IKGeo2DInternalMapper2(e->getEndNode(),m,forbVal0,forbVal1,isect);
9969     }
9970   return presenceOfOn;
9971 }
9972
9973 /// @endcond
9974
9975 /**
9976  * This method split some of edges of 2D cells in \a this. The edges to be split are specified in \a subNodesInSeg and in \a subNodesInSegI using index storage mode.
9977  * To do the work this method can optionally needs information about middle of subedges for quadratic cases if a minimal creation of new nodes is wanted.
9978  * So this method try to reduce at most the number of new nodes. The only case that can lead this method to add nodes if a SEG3 is split without information of middle.
9979  * \b WARNING : is returned value is different from 0 a call to MEDCouplingUMesh::mergeNodes is necessary to avoid to have a non conform mesh.
9980  *
9981  * \return int - the number of new nodes created (in most of cases 0).
9982  * 
9983  * \throw If \a this is not coherent.
9984  * \throw If \a this has not spaceDim equal to 2.
9985  * \throw If \a this has not meshDim equal to 2.
9986  * \throw If some subcells needed to be split are orphan.
9987  * \sa MEDCouplingUMesh::conformize2D
9988  */
9989 int MEDCouplingUMesh::split2DCells(const DataArrayInt *desc, const DataArrayInt *descI, const DataArrayInt *subNodesInSeg, const DataArrayInt *subNodesInSegI, const DataArrayInt *midOpt, const DataArrayInt *midOptI)
9990 {
9991   if(!desc || !descI || !subNodesInSeg || !subNodesInSegI)
9992     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::split2DCells : the 4 first arrays must be not null !");
9993   desc->checkAllocated(); descI->checkAllocated(); subNodesInSeg->checkAllocated(); subNodesInSegI->checkAllocated();
9994   if(getSpaceDimension()!=2 || getMeshDimension()!=2)
9995     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::split2DCells : This method only works for meshes with spaceDim=2 and meshDim=2 !");
9996   if(midOpt==0 && midOptI==0)
9997     {
9998       split2DCellsLinear(desc,descI,subNodesInSeg,subNodesInSegI);
9999       return 0;
10000     }
10001   else if(midOpt!=0 && midOptI!=0)
10002     return split2DCellsQuadratic(desc,descI,subNodesInSeg,subNodesInSegI,midOpt,midOptI);
10003   else
10004     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::split2DCells : middle parameters must be set to null for all or not null for all.");
10005 }
10006
10007 /*!
10008  * \b WARNING this method is \b potentially \b non \b const (if returned array is empty).
10009  * \b WARNING this method lead to have a non geometric type sorted mesh (for MED file users) !
10010  * This method performs a conformization of \b this. So if a edge in \a this can be split into entire edges in \a this this method
10011  * will suppress such edges to use sub edges in \a this. So this method does not add nodes in \a this if merged edges are both linear (INTERP_KERNEL::NORM_SEG2).
10012  * In the other cases new nodes can be created. If any are created, they will be appended at the end of the coordinates object before the invokation of this method.
10013  * 
10014  * Whatever the returned value, this method does not alter the order of cells in \a this neither the orientation of cells.
10015  * The modified cells, if any, are systematically declared as NORM_POLYGON or NORM_QPOLYG depending on the initial quadraticness of geometric type.
10016  *
10017  * This method expects that \b this has a meshDim equal 2 and spaceDim equal to 2 too.
10018  * This method expects that all nodes in \a this are not closer than \a eps.
10019  * If it is not the case you can invoke MEDCouplingUMesh::mergeNodes before calling this method.
10020  * 
10021  * \param [in] eps the relative error to detect merged edges.
10022  * \return DataArrayInt  * - The list of cellIds in \a this that have been subdivided. If empty, nothing changed in \a this (as if it were a const method). The array is a newly allocated array
10023  *                           that the user is expected to deal with.
10024  *
10025  * \throw If \a this is not coherent.
10026  * \throw If \a this has not spaceDim equal to 2.
10027  * \throw If \a this has not meshDim equal to 2.
10028  * \sa MEDCouplingUMesh::mergeNodes, MEDCouplingUMesh::split2DCells
10029  */
10030 DataArrayInt *MEDCouplingUMesh::conformize2D(double eps)
10031 {
10032   static const int SPACEDIM=2;
10033   checkCoherency();
10034   if(getSpaceDimension()!=2 || getMeshDimension()!=2)
10035     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::conformize2D : This method only works for meshes with spaceDim=2 and meshDim=2 !");
10036   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> desc1(DataArrayInt::New()),descIndx1(DataArrayInt::New()),revDesc1(DataArrayInt::New()),revDescIndx1(DataArrayInt::New());
10037   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> mDesc(buildDescendingConnectivity(desc1,descIndx1,revDesc1,revDescIndx1));
10038   const int *c(mDesc->getNodalConnectivity()->getConstPointer()),*ci(mDesc->getNodalConnectivityIndex()->getConstPointer()),*rd(revDesc1->getConstPointer()),*rdi(revDescIndx1->getConstPointer());
10039   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> bboxArr(mDesc->getBoundingBoxForBBTree());
10040   const double *bbox(bboxArr->begin()),*coords(getCoords()->begin());
10041   int nCell(getNumberOfCells()),nDescCell(mDesc->getNumberOfCells());
10042   std::vector< std::vector<int> > intersectEdge(nDescCell),overlapEdge(nDescCell);
10043   std::vector<double> addCoo;
10044   BBTree<SPACEDIM,int> myTree(bbox,0,0,nDescCell,-eps);
10045   INTERP_KERNEL::QUADRATIC_PLANAR::_precision=eps;
10046   INTERP_KERNEL::QUADRATIC_PLANAR::_arc_detection_precision=eps;
10047   for(int i=0;i<nDescCell;i++)
10048     {
10049       std::vector<int> candidates;
10050       myTree.getIntersectingElems(bbox+i*2*SPACEDIM,candidates);
10051       for(std::vector<int>::const_iterator it=candidates.begin();it!=candidates.end();it++)
10052         if(*it>i)
10053           {
10054             std::map<MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Node>,int> m;
10055             INTERP_KERNEL::Edge *e1(MEDCouplingUMeshBuildQPFromEdge2((INTERP_KERNEL::NormalizedCellType)c[ci[i]],c+ci[i]+1,coords,m)),
10056                 *e2(MEDCouplingUMeshBuildQPFromEdge2((INTERP_KERNEL::NormalizedCellType)c[ci[*it]],c+ci[*it]+1,coords,m));
10057             INTERP_KERNEL::MergePoints merge;
10058             INTERP_KERNEL::QuadraticPolygon c1,c2;
10059             e1->intersectWith(e2,merge,c1,c2);
10060             e1->decrRef(); e2->decrRef();
10061             if(IKGeo2DInternalMapper(c1,m,c[ci[i]+1],c[ci[i]+2],intersectEdge[i]))
10062               overlapEdge[i].push_back(*it);
10063             if(IKGeo2DInternalMapper(c2,m,c[ci[*it]+1],c[ci[*it]+2],intersectEdge[*it]))
10064               overlapEdge[*it].push_back(i);
10065           }
10066     }
10067   // splitting done. sort intersect point in intersectEdge.
10068   std::vector< std::vector<int> > middle(nDescCell);
10069   int nbOf2DCellsToBeSplit(0);
10070   bool middleNeedsToBeUsed(false);
10071   std::vector<bool> cells2DToTreat(nDescCell,false);
10072   for(int i=0;i<nDescCell;i++)
10073     {
10074       std::vector<int>& isect(intersectEdge[i]);
10075       int sz((int)isect.size());
10076       if(sz>1)
10077         {
10078           std::map<MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Node>,int> m;
10079           INTERP_KERNEL::Edge *e(MEDCouplingUMeshBuildQPFromEdge2((INTERP_KERNEL::NormalizedCellType)c[ci[i]],c+ci[i]+1,coords,m));
10080           e->sortSubNodesAbs(coords,isect);
10081           e->decrRef();
10082         }
10083       if(sz!=0)
10084         {
10085           int idx0(rdi[i]),idx1(rdi[i+1]);
10086           if(idx1-idx0!=1)
10087             throw INTERP_KERNEL::Exception("MEDCouplingUMesh::conformize2D : internal error #0 !");
10088           if(!cells2DToTreat[rd[idx0]])
10089             {
10090               cells2DToTreat[rd[idx0]]=true;
10091               nbOf2DCellsToBeSplit++;
10092             }
10093           // try to reuse at most eventual 'middle' of SEG3
10094           std::vector<int>& mid(middle[i]);
10095           mid.resize(sz+1,-1);
10096           if((INTERP_KERNEL::NormalizedCellType)c[ci[i]]==INTERP_KERNEL::NORM_SEG3)
10097             {
10098               middleNeedsToBeUsed=true;
10099               const std::vector<int>& candidates(overlapEdge[i]);
10100               std::vector<int> trueCandidates;
10101               for(std::vector<int>::const_iterator itc=candidates.begin();itc!=candidates.end();itc++)
10102                 if((INTERP_KERNEL::NormalizedCellType)c[ci[*itc]]==INTERP_KERNEL::NORM_SEG3)
10103                   trueCandidates.push_back(*itc);
10104               int stNode(c[ci[i]+1]),endNode(isect[0]);
10105               for(int j=0;j<sz+1;j++)
10106                 {
10107                   for(std::vector<int>::const_iterator itc=trueCandidates.begin();itc!=trueCandidates.end();itc++)
10108                     {
10109                       int tmpSt(c[ci[*itc]+1]),tmpEnd(c[ci[*itc]+2]);
10110                       if((tmpSt==stNode && tmpEnd==endNode) || (tmpSt==endNode && tmpEnd==stNode))
10111                         { mid[j]=*itc; break; }
10112                     }
10113                   stNode=endNode;
10114                   endNode=j<sz-1?isect[j+1]:c[ci[i]+2];
10115                 }
10116             }
10117         }
10118     }
10119   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret(DataArrayInt::New()),notRet(DataArrayInt::New()); ret->alloc(nbOf2DCellsToBeSplit,1);
10120   if(nbOf2DCellsToBeSplit==0)
10121     return ret.retn();
10122   //
10123   int *retPtr(ret->getPointer());
10124   for(int i=0;i<nCell;i++)
10125     if(cells2DToTreat[i])
10126       *retPtr++=i;
10127   //
10128   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> mSafe,nSafe,oSafe,pSafe,qSafe,rSafe;
10129   DataArrayInt *m(0),*n(0),*o(0),*p(0),*q(0),*r(0);
10130   MEDCouplingUMesh::ExtractFromIndexedArrays(ret->begin(),ret->end(),desc1,descIndx1,m,n); mSafe=m; nSafe=n;
10131   DataArrayInt::PutIntoToSkylineFrmt(intersectEdge,o,p); oSafe=o; pSafe=p;
10132   if(middleNeedsToBeUsed)
10133     { DataArrayInt::PutIntoToSkylineFrmt(middle,q,r); qSafe=q; rSafe=r; }
10134   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> modif(static_cast<MEDCouplingUMesh *>(buildPartOfMySelf(ret->begin(),ret->end(),true)));
10135   int nbOfNodesCreated(modif->split2DCells(mSafe,nSafe,oSafe,pSafe,qSafe,rSafe));
10136   setCoords(modif->getCoords());//if nbOfNodesCreated==0 modif and this have the same coordinates pointer so this line has no effect. But for quadratic cases this line is important.
10137   setPartOfMySelf(ret->begin(),ret->end(),*modif);
10138   {
10139     bool areNodesMerged; int newNbOfNodes;
10140     if(nbOfNodesCreated!=0)
10141       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp(mergeNodes(eps,areNodesMerged,newNbOfNodes));
10142   }
10143   return ret.retn();
10144 }
10145
10146 /*!
10147  * This non const method works on 2D mesh. This method scans every cell in \a this and look if each edge constituting this cell is not mergeable with neighbors edges of that cell.
10148  * If yes, the cell is "repaired" to minimize at most its number of edges. So this method do not change the overall shape of cells in \a this (with eps precision).
10149  * This method do not take care of shared edges between cells, so this method can lead to a non conform mesh (\a this). If a conform mesh is required you're expected
10150  * to invoke MEDCouplingUMesh::mergeNodes and MEDCouplingUMesh::conformize2D right after this call.
10151  * This method works on any 2D geometric types of cell (even static one). If a cell is touched its type becomes dynamic automaticaly. For 2D "repaired" quadratic cells
10152  * new nodes for center of merged edges is are systematically created and appended at the end of the previously existing nodes.
10153  *
10154  * If the returned array is empty it means that nothing has changed in \a this (as if it were a const method). If the array is not empty the connectivity of \a this is modified
10155  * using new instance, idem for coordinates.
10156  *
10157  * If \a this is constituted by only linear 2D cells, this method is close to the computation of the convex hull of each cells in \a this.
10158  * 
10159  * \return DataArrayInt  * - The list of cellIds in \a this that have at least one edge colinearized.
10160  *
10161  * \throw If \a this is not coherent.
10162  * \throw If \a this has not spaceDim equal to 2.
10163  * \throw If \a this has not meshDim equal to 2.
10164  * 
10165  * \sa MEDCouplingUMesh::conformize2D, MEDCouplingUMesh::mergeNodes, MEDCouplingUMesh::convexEnvelop2D.
10166  */
10167 DataArrayInt *MEDCouplingUMesh::colinearize2D(double eps)
10168 {
10169   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret(DataArrayInt::New()); ret->alloc(0,1);
10170   checkCoherency();
10171   if(getSpaceDimension()!=2 || getMeshDimension()!=2)
10172     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::colinearize2D : This method only works for meshes with spaceDim=2 and meshDim=2 !");
10173   INTERP_KERNEL::QUADRATIC_PLANAR::_arc_detection_precision=eps;
10174   INTERP_KERNEL::QUADRATIC_PLANAR::_precision=eps;
10175   int nbOfCells(getNumberOfCells()),nbOfNodes(getNumberOfNodes());
10176   const int *cptr(_nodal_connec->begin()),*ciptr(_nodal_connec_index->begin());
10177   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newc(DataArrayInt::New()),newci(DataArrayInt::New()); newci->alloc(nbOfCells+1,1); newc->alloc(0,1); newci->setIJ(0,0,0);
10178   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> appendedCoords(DataArrayDouble::New()); appendedCoords->alloc(0,1);//1 not 2 it is not a bug.
10179   const double *coords(_coords->begin());
10180   int *newciptr(newci->getPointer());
10181   for(int i=0;i<nbOfCells;i++,newciptr++,ciptr++)
10182     {
10183       if(Colinearize2DCell(coords,cptr+ciptr[0],cptr+ciptr[1],nbOfNodes,newc,appendedCoords))
10184         ret->pushBackSilent(i);
10185       newciptr[1]=newc->getNumberOfTuples();
10186     }
10187   //
10188   if(ret->empty())
10189     return ret.retn();
10190   if(!appendedCoords->empty())
10191     {
10192       appendedCoords->rearrange(2);
10193       MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> newCoords(DataArrayDouble::Aggregate(getCoords(),appendedCoords));//treat info on components
10194       //non const part
10195       setCoords(newCoords);
10196     }
10197   //non const part
10198   setConnectivity(newc,newci,true);
10199   return ret.retn();
10200 }
10201
10202 /*!
10203  * \param [out] intersectEdge1 - for each cell in \a m1Desc returns the result of the split. The result is given using pair of int given resp start and stop.
10204  *                               So for all edge \a i in \a m1Desc \a  intersectEdge1[i] is of length 2*n where n is the number of sub edges.
10205  *                               And for each j in [1,n) intersect[i][2*(j-1)+1]==intersect[i][2*j].
10206  * \param [out] subDiv2 - for each cell in \a m2Desc returns nodes that split it using convention \a m1Desc first, then \a m2Desc, then addCoo
10207  * \param [out] colinear2 - for each cell in \a m2Desc returns the edges in \a m1Desc that are colinear to it.
10208  * \param [out] addCoo - nodes to be append at the end
10209  * \param [out] mergedNodes - gives all pair of nodes of \a m2Desc that have same location than some nodes in \a m1Desc. key is id in \a m2Desc offseted and value is id in \a m1Desc.
10210  */
10211 void MEDCouplingUMesh::Intersect1DMeshes(const MEDCouplingUMesh *m1Desc, const MEDCouplingUMesh *m2Desc, double eps,
10212                                          std::vector< std::vector<int> >& intersectEdge1, std::vector< std::vector<int> >& colinear2, std::vector< std::vector<int> >& subDiv2, std::vector<double>& addCoo, std::map<int,int>& mergedNodes)
10213 {
10214   static const int SPACEDIM=2;
10215   INTERP_KERNEL::QUADRATIC_PLANAR::_precision=eps;
10216   INTERP_KERNEL::QUADRATIC_PLANAR::_arc_detection_precision=eps;
10217   const int *c1(m1Desc->getNodalConnectivity()->getConstPointer()),*ci1(m1Desc->getNodalConnectivityIndex()->getConstPointer());
10218   // Build BB tree of all edges in the tool mesh (second mesh)
10219   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> bbox1Arr(m1Desc->getBoundingBoxForBBTree()),bbox2Arr(m2Desc->getBoundingBoxForBBTree());
10220   const double *bbox1(bbox1Arr->begin()),*bbox2(bbox2Arr->begin());
10221   int nDescCell1(m1Desc->getNumberOfCells()),nDescCell2(m2Desc->getNumberOfCells());
10222   intersectEdge1.resize(nDescCell1);
10223   colinear2.resize(nDescCell2);
10224   subDiv2.resize(nDescCell2);
10225   BBTree<SPACEDIM,int> myTree(bbox2,0,0,m2Desc->getNumberOfCells(),-eps);
10226
10227   std::vector<int> candidates1(1);
10228   int offset1(m1Desc->getNumberOfNodes());
10229   int offset2(offset1+m2Desc->getNumberOfNodes());
10230   for(int i=0;i<nDescCell1;i++)  // for all edges in the first mesh
10231     {
10232       std::vector<int> candidates2; // edges of mesh2 candidate for intersection
10233       myTree.getIntersectingElems(bbox1+i*2*SPACEDIM,candidates2);
10234       if(!candidates2.empty()) // candidates2 holds edges from the second mesh potentially intersecting current edge i in mesh1
10235         {
10236           std::map<INTERP_KERNEL::Node *,int> map1,map2;
10237           // pol2 is not necessarily a closed polygon: just a set of (quadratic) edges (same as candidates2) in the Geometric DS format
10238           INTERP_KERNEL::QuadraticPolygon *pol2=MEDCouplingUMeshBuildQPFromMesh(m2Desc,candidates2,map2);
10239           candidates1[0]=i;
10240           INTERP_KERNEL::QuadraticPolygon *pol1=MEDCouplingUMeshBuildQPFromMesh(m1Desc,candidates1,map1);
10241           // This following part is to avoid that some removed nodes (for example due to a merge between pol1 and pol2) are replaced by a newly created one
10242           // This trick guarantees that Node * are discriminant (i.e. form a unique identifier)
10243           std::set<INTERP_KERNEL::Node *> nodes;
10244           pol1->getAllNodes(nodes); pol2->getAllNodes(nodes);
10245           std::size_t szz(nodes.size());
10246           std::vector< MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Node> > nodesSafe(szz);
10247           std::set<INTERP_KERNEL::Node *>::const_iterator itt(nodes.begin());
10248           for(std::size_t iii=0;iii<szz;iii++,itt++)
10249             { (*itt)->incrRef(); nodesSafe[iii]=*itt; }
10250           // end of protection
10251           // Performs egde cutting:
10252           pol1->splitAbs(*pol2,map1,map2,offset1,offset2,candidates2,intersectEdge1[i],i,colinear2,subDiv2,addCoo,mergedNodes);
10253           delete pol2;
10254           delete pol1;
10255         }
10256       else
10257         // Copy the edge (take only the two first points, ie discard quadratic point at this stage)
10258         intersectEdge1[i].insert(intersectEdge1[i].end(),c1+ci1[i]+1,c1+ci1[i]+3);
10259     }
10260 }
10261
10262 /*!
10263  * This method is private and is the first step of Partition of 2D mesh (spaceDim==2 and meshDim==2).
10264  * It builds the descending connectivity of the two meshes, and then using a binary tree
10265  * it computes the edge intersections. This results in new points being created : they're stored in addCoo.
10266  * Documentation about parameters  colinear2 and subDiv2 can be found in method QuadraticPolygon::splitAbs().
10267  */
10268 void MEDCouplingUMesh::IntersectDescending2DMeshes(const MEDCouplingUMesh *m1, const MEDCouplingUMesh *m2, double eps,
10269                                                    std::vector< std::vector<int> >& intersectEdge1, std::vector< std::vector<int> >& colinear2, std::vector< std::vector<int> >& subDiv2,
10270                                                    MEDCouplingUMesh *& m1Desc, DataArrayInt *&desc1, DataArrayInt *&descIndx1, DataArrayInt *&revDesc1, DataArrayInt *&revDescIndx1,
10271                                                    std::vector<double>& addCoo,
10272                                                    MEDCouplingUMesh *& m2Desc, DataArrayInt *&desc2, DataArrayInt *&descIndx2, DataArrayInt *&revDesc2, DataArrayInt *&revDescIndx2)
10273 {
10274   // Build desc connectivity
10275   desc1=DataArrayInt::New(); descIndx1=DataArrayInt::New(); revDesc1=DataArrayInt::New(); revDescIndx1=DataArrayInt::New();
10276   desc2=DataArrayInt::New();
10277   descIndx2=DataArrayInt::New();
10278   revDesc2=DataArrayInt::New();
10279   revDescIndx2=DataArrayInt::New();
10280   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> dd1(desc1),dd2(descIndx1),dd3(revDesc1),dd4(revDescIndx1);
10281   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> dd5(desc2),dd6(descIndx2),dd7(revDesc2),dd8(revDescIndx2);
10282   m1Desc=m1->buildDescendingConnectivity2(desc1,descIndx1,revDesc1,revDescIndx1);
10283   m2Desc=m2->buildDescendingConnectivity2(desc2,descIndx2,revDesc2,revDescIndx2);
10284   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> dd9(m1Desc),dd10(m2Desc);
10285   std::map<int,int> notUsedMap;
10286   Intersect1DMeshes(m1Desc,m2Desc,eps,intersectEdge1,colinear2,subDiv2,addCoo,notUsedMap);
10287   m1Desc->incrRef(); desc1->incrRef(); descIndx1->incrRef(); revDesc1->incrRef(); revDescIndx1->incrRef();
10288   m2Desc->incrRef(); desc2->incrRef(); descIndx2->incrRef(); revDesc2->incrRef(); revDescIndx2->incrRef();
10289 }
10290
10291 /*!
10292  * This method performs the 2nd step of Partition of 2D mesh.
10293  * This method has 4 inputs :
10294  *  - a mesh 'm1' with meshDim==1 and a SpaceDim==2
10295  *  - a mesh 'm2' with meshDim==1 and a SpaceDim==2
10296  *  - subDiv of size 'm2->getNumberOfCells()' that lists for each seg cell in 'm' the splitting node ids randomly sorted.
10297  * The aim of this method is to sort the splitting nodes, if any, and to put them in 'intersectEdge' output parameter based on edges of mesh 'm2'
10298  * Nodes end up lying consecutively on a cutted edge.
10299  * \param m1 is expected to be a mesh of meshDimension equal to 1 and spaceDim equal to 2. No check of that is performed by this method.
10300  * (Only present for its coords in case of 'subDiv' shares some nodes of 'm1')
10301  * \param m2 is expected to be a mesh of meshDimension equal to 1 and spaceDim equal to 2. No check of that is performed by this method.
10302  * \param addCoo input parameter with additional nodes linked to intersection of the 2 meshes.
10303  * \param[out] intersectEdge the same content as subDiv, but correclty oriented.
10304  */
10305 void MEDCouplingUMesh::BuildIntersectEdges(const MEDCouplingUMesh *m1, const MEDCouplingUMesh *m2,
10306                                            const std::vector<double>& addCoo,
10307                                            const std::vector< std::vector<int> >& subDiv, std::vector< std::vector<int> >& intersectEdge)
10308 {
10309   int offset1=m1->getNumberOfNodes();
10310   int ncell=m2->getNumberOfCells();
10311   const int *c=m2->getNodalConnectivity()->getConstPointer();
10312   const int *cI=m2->getNodalConnectivityIndex()->getConstPointer();
10313   const double *coo=m2->getCoords()->getConstPointer();
10314   const double *cooBis=m1->getCoords()->getConstPointer();
10315   int offset2=offset1+m2->getNumberOfNodes();
10316   intersectEdge.resize(ncell);
10317   for(int i=0;i<ncell;i++,cI++)
10318     {
10319       const std::vector<int>& divs=subDiv[i];
10320       int nnode=cI[1]-cI[0]-1;
10321       std::map<int, std::pair<INTERP_KERNEL::Node *,bool> > mapp2;
10322       std::map<INTERP_KERNEL::Node *, int> mapp22;
10323       for(int j=0;j<nnode;j++)
10324         {
10325           INTERP_KERNEL::Node *nn=new INTERP_KERNEL::Node(coo[2*c[(*cI)+j+1]],coo[2*c[(*cI)+j+1]+1]);
10326           int nnid=c[(*cI)+j+1];
10327           mapp2[nnid]=std::pair<INTERP_KERNEL::Node *,bool>(nn,true);
10328           mapp22[nn]=nnid+offset1;
10329         }
10330       INTERP_KERNEL::Edge *e=MEDCouplingUMeshBuildQPFromEdge((INTERP_KERNEL::NormalizedCellType)c[*cI],mapp2,c+(*cI)+1);
10331       for(std::map<int, std::pair<INTERP_KERNEL::Node *,bool> >::const_iterator it=mapp2.begin();it!=mapp2.end();it++)
10332         ((*it).second.first)->decrRef();
10333       std::vector<INTERP_KERNEL::Node *> addNodes(divs.size());
10334       std::map<INTERP_KERNEL::Node *,int> mapp3;
10335       for(std::size_t j=0;j<divs.size();j++)
10336         {
10337           int id=divs[j];
10338           INTERP_KERNEL::Node *tmp=0;
10339           if(id<offset1)
10340             tmp=new INTERP_KERNEL::Node(cooBis[2*id],cooBis[2*id+1]);
10341           else if(id<offset2)
10342             tmp=new INTERP_KERNEL::Node(coo[2*(id-offset1)],coo[2*(id-offset1)+1]);//if it happens, bad news mesh 'm2' is non conform.
10343           else
10344             tmp=new INTERP_KERNEL::Node(addCoo[2*(id-offset2)],addCoo[2*(id-offset2)+1]);
10345           addNodes[j]=tmp;
10346           mapp3[tmp]=id;
10347         }
10348       e->sortIdsAbs(addNodes,mapp22,mapp3,intersectEdge[i]);
10349       for(std::vector<INTERP_KERNEL::Node *>::const_iterator it=addNodes.begin();it!=addNodes.end();it++)
10350         (*it)->decrRef();
10351       e->decrRef();
10352     }
10353 }
10354
10355 /*!
10356  * This method is part of the Slice3D algorithm. It is the first step of assembly process, ones coordinates have been computed (by MEDCouplingUMesh::split3DCurveWithPlane method).
10357  * This method allows to compute given the status of 3D curve cells and the descending connectivity 3DSurf->3DCurve to deduce the intersection of each 3D surf cells
10358  * with a plane. The result will be put in 'cut3DSuf' out parameter.
10359  * \param [in] cut3DCurve  input paramter that gives for each 3DCurve cell if it owns fully to the plane or partially.
10360  * \param [out] nodesOnPlane, returns all the nodes that are on the plane.
10361  * \param [in] nodal3DSurf is the nodal connectivity of 3D surf mesh.
10362  * \param [in] nodalIndx3DSurf is the nodal connectivity index of 3D surf mesh.
10363  * \param [in] nodal3DCurve is the nodal connectivity of 3D curve mesh.
10364  * \param [in] nodal3DIndxCurve is the nodal connectivity index of 3D curve mesh.
10365  * \param [in] desc is the descending connectivity 3DSurf->3DCurve
10366  * \param [in] descIndx is the descending connectivity index 3DSurf->3DCurve
10367  * \param [out] cut3DSuf input/output param.
10368  */
10369 void MEDCouplingUMesh::AssemblyForSplitFrom3DCurve(const std::vector<int>& cut3DCurve, std::vector<int>& nodesOnPlane, const int *nodal3DSurf, const int *nodalIndx3DSurf,
10370                                                    const int *nodal3DCurve, const int *nodalIndx3DCurve,
10371                                                    const int *desc, const int *descIndx, 
10372                                                    std::vector< std::pair<int,int> >& cut3DSurf)
10373 {
10374   std::set<int> nodesOnP(nodesOnPlane.begin(),nodesOnPlane.end());
10375   int nbOf3DSurfCell=(int)cut3DSurf.size();
10376   for(int i=0;i<nbOf3DSurfCell;i++)
10377     {
10378       std::vector<int> res;
10379       int offset=descIndx[i];
10380       int nbOfSeg=descIndx[i+1]-offset;
10381       for(int j=0;j<nbOfSeg;j++)
10382         {
10383           int edgeId=desc[offset+j];
10384           int status=cut3DCurve[edgeId];
10385           if(status!=-2)
10386             {
10387               if(status>-1)
10388                 res.push_back(status);
10389               else
10390                 {
10391                   res.push_back(nodal3DCurve[nodalIndx3DCurve[edgeId]+1]);
10392                   res.push_back(nodal3DCurve[nodalIndx3DCurve[edgeId]+2]);
10393                 }
10394             }
10395         }
10396       switch(res.size())
10397       {
10398         case 2:
10399           {
10400             cut3DSurf[i].first=res[0]; cut3DSurf[i].second=res[1];
10401             break;
10402           }
10403         case 1:
10404         case 0:
10405           {
10406             std::set<int> s1(nodal3DSurf+nodalIndx3DSurf[i]+1,nodal3DSurf+nodalIndx3DSurf[i+1]);
10407             std::set_intersection(nodesOnP.begin(),nodesOnP.end(),s1.begin(),s1.end(),std::back_insert_iterator< std::vector<int> >(res));
10408             if(res.size()==2)
10409               {
10410                 cut3DSurf[i].first=res[0]; cut3DSurf[i].second=res[1];
10411               }
10412             else
10413               {
10414                 cut3DSurf[i].first=-1; cut3DSurf[i].second=-1;
10415               }
10416             break;
10417           }
10418         default:
10419           {// case when plane is on a multi colinear edge of a polyhedron
10420             if((int)res.size()==2*nbOfSeg)
10421               {
10422                 cut3DSurf[i].first=-2; cut3DSurf[i].second=i;
10423               }
10424             else
10425               throw INTERP_KERNEL::Exception("MEDCouplingUMesh::AssemblyPointsFrom3DCurve : unexpected situation !");
10426           }
10427       }
10428     }
10429 }
10430
10431 /*!
10432  * \a this is expected to be a mesh with spaceDim==3 and meshDim==3. If not an exception will be thrown.
10433  * This method is part of the Slice3D algorithm. It is the second step of assembly process, ones coordinates have been computed (by MEDCouplingUMesh::split3DCurveWithPlane method).
10434  * This method allows to compute given the result of 3D surf cells with plane and the descending connectivity 3D->3DSurf to deduce the intersection of each 3D cells
10435  * with a plane. The result will be put in 'nodalRes' 'nodalResIndx' and 'cellIds' out parameters.
10436  * \param cut3DSurf  input paramter that gives for each 3DSurf its intersection with plane (result of MEDCouplingUMesh::AssemblyForSplitFrom3DCurve).
10437  * \param desc is the descending connectivity 3D->3DSurf
10438  * \param descIndx is the descending connectivity index 3D->3DSurf
10439  */
10440 void MEDCouplingUMesh::assemblyForSplitFrom3DSurf(const std::vector< std::pair<int,int> >& cut3DSurf,
10441                                                   const int *desc, const int *descIndx,
10442                                                   DataArrayInt *nodalRes, DataArrayInt *nodalResIndx, DataArrayInt *cellIds) const
10443 {
10444   checkFullyDefined();
10445   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
10446     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::assemblyForSplitFrom3DSurf works on umeshes with meshdim equal to 3 and spaceDim equal to 3 too!");
10447   const int *nodal3D=_nodal_connec->getConstPointer();
10448   const int *nodalIndx3D=_nodal_connec_index->getConstPointer();
10449   int nbOfCells=getNumberOfCells();
10450   for(int i=0;i<nbOfCells;i++)
10451     {
10452       std::map<int, std::set<int> > m;
10453       int offset=descIndx[i];
10454       int nbOfFaces=descIndx[i+1]-offset;
10455       int start=-1;
10456       int end=-1;
10457       for(int j=0;j<nbOfFaces;j++)
10458         {
10459           const std::pair<int,int>& p=cut3DSurf[desc[offset+j]];
10460           if(p.first!=-1 && p.second!=-1)
10461             {
10462               if(p.first!=-2)
10463                 {
10464                   start=p.first; end=p.second;
10465                   m[p.first].insert(p.second);
10466                   m[p.second].insert(p.first);
10467                 }
10468               else
10469                 {
10470                   const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)nodal3D[nodalIndx3D[i]]);
10471                   int sz=nodalIndx3D[i+1]-nodalIndx3D[i]-1;
10472                   INTERP_KERNEL::AutoPtr<int> tmp=new int[sz];
10473                   INTERP_KERNEL::NormalizedCellType cmsId;
10474                   unsigned nbOfNodesSon=cm.fillSonCellNodalConnectivity2(j,nodal3D+nodalIndx3D[i]+1,sz,tmp,cmsId);
10475                   start=tmp[0]; end=tmp[nbOfNodesSon-1];
10476                   for(unsigned k=0;k<nbOfNodesSon;k++)
10477                     {
10478                       m[tmp[k]].insert(tmp[(k+1)%nbOfNodesSon]);
10479                       m[tmp[(k+1)%nbOfNodesSon]].insert(tmp[k]);
10480                     }
10481                 }
10482             }
10483         }
10484       if(m.empty())
10485         continue;
10486       std::vector<int> conn(1,(int)INTERP_KERNEL::NORM_POLYGON);
10487       int prev=end;
10488       while(end!=start)
10489         {
10490           std::map<int, std::set<int> >::const_iterator it=m.find(start);
10491           const std::set<int>& s=(*it).second;
10492           std::set<int> s2; s2.insert(prev);
10493           std::set<int> s3;
10494           std::set_difference(s.begin(),s.end(),s2.begin(),s2.end(),inserter(s3,s3.begin()));
10495           if(s3.size()==1)
10496             {
10497               int val=*s3.begin();
10498               conn.push_back(start);
10499               prev=start;
10500               start=val;
10501             }
10502           else
10503             start=end;
10504         }
10505       conn.push_back(end);
10506       if(conn.size()>3)
10507         {
10508           nodalRes->insertAtTheEnd(conn.begin(),conn.end());
10509           nodalResIndx->pushBackSilent(nodalRes->getNumberOfTuples());
10510           cellIds->pushBackSilent(i);
10511         }
10512     }
10513 }
10514
10515 /*!
10516  * This method compute the convex hull of a single 2D cell. This method tries to conserve at maximum the given input connectivity. In particular, if the orientation of cell is not clockwise
10517  * as in MED format norm. If definitely the result of Jarvis algorithm is not matchable with the input connectivity, the result will be copied into \b nodalConnecOut parameter and
10518  * the geometric cell type set to INTERP_KERNEL::NORM_POLYGON.
10519  * This method excepts that \b coords parameter is expected to be in dimension 2. [ \b nodalConnBg , \b nodalConnEnd ) is the nodal connectivity of the input
10520  * cell (geometric cell type included at the position 0). If the meshdimension of the input cell is not equal to 2 an INTERP_KERNEL::Exception will be thrown.
10521  * 
10522  * \return false if the input connectivity represents already the convex hull, true if the input cell needs to be reordered.
10523  */
10524 bool MEDCouplingUMesh::BuildConvexEnvelopOf2DCellJarvis(const double *coords, const int *nodalConnBg, const int *nodalConnEnd, DataArrayInt *nodalConnecOut)
10525 {
10526   std::size_t sz=std::distance(nodalConnBg,nodalConnEnd);
10527   if(sz>=4)
10528     {
10529       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)*nodalConnBg);
10530       if(cm.getDimension()==2)
10531         {
10532           const int *node=nodalConnBg+1;
10533           int startNode=*node++;
10534           double refX=coords[2*startNode];
10535           for(;node!=nodalConnEnd;node++)
10536             {
10537               if(coords[2*(*node)]<refX)
10538                 {
10539                   startNode=*node;
10540                   refX=coords[2*startNode];
10541                 }
10542             }
10543           std::vector<int> tmpOut; tmpOut.reserve(sz); tmpOut.push_back(startNode);
10544           refX=1e300;
10545           double tmp1;
10546           double tmp2[2];
10547           double angle0=-M_PI/2;
10548           //
10549           int nextNode=-1;
10550           int prevNode=-1;
10551           double resRef;
10552           double angleNext=0.;
10553           while(nextNode!=startNode)
10554             {
10555               nextNode=-1;
10556               resRef=1e300;
10557               for(node=nodalConnBg+1;node!=nodalConnEnd;node++)
10558                 {
10559                   if(*node!=tmpOut.back() && *node!=prevNode)
10560                     {
10561                       tmp2[0]=coords[2*(*node)]-coords[2*tmpOut.back()]; tmp2[1]=coords[2*(*node)+1]-coords[2*tmpOut.back()+1];
10562                       double angleM=INTERP_KERNEL::EdgeArcCircle::GetAbsoluteAngle(tmp2,tmp1);
10563                       double res;
10564                       if(angleM<=angle0)
10565                         res=angle0-angleM;
10566                       else
10567                         res=angle0-angleM+2.*M_PI;
10568                       if(res<resRef)
10569                         {
10570                           nextNode=*node;
10571                           resRef=res;
10572                           angleNext=angleM;
10573                         }
10574                     }
10575                 }
10576               if(nextNode!=startNode)
10577                 {
10578                   angle0=angleNext-M_PI;
10579                   if(angle0<-M_PI)
10580                     angle0+=2*M_PI;
10581                   prevNode=tmpOut.back();
10582                   tmpOut.push_back(nextNode);
10583                 }
10584             }
10585           std::vector<int> tmp3(2*(sz-1));
10586           std::vector<int>::iterator it=std::copy(nodalConnBg+1,nodalConnEnd,tmp3.begin());
10587           std::copy(nodalConnBg+1,nodalConnEnd,it);
10588           if(std::search(tmp3.begin(),tmp3.end(),tmpOut.begin(),tmpOut.end())!=tmp3.end())
10589             {
10590               nodalConnecOut->insertAtTheEnd(nodalConnBg,nodalConnEnd);
10591               return false;
10592             }
10593           if(std::search(tmp3.rbegin(),tmp3.rend(),tmpOut.begin(),tmpOut.end())!=tmp3.rend())
10594             {
10595               nodalConnecOut->insertAtTheEnd(nodalConnBg,nodalConnEnd);
10596               return false;
10597             }
10598           else
10599             {
10600               nodalConnecOut->pushBackSilent((int)INTERP_KERNEL::NORM_POLYGON);
10601               nodalConnecOut->insertAtTheEnd(tmpOut.begin(),tmpOut.end());
10602               return true;
10603             }
10604         }
10605       else
10606         throw INTERP_KERNEL::Exception("MEDCouplingUMesh::BuildConvexEnvelopOf2DCellJarvis : invalid 2D cell connectivity !");
10607     }
10608   else
10609     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::BuildConvexEnvelopOf2DCellJarvis : invalid 2D cell connectivity !");
10610 }
10611
10612 /*!
10613  * This method works on an input pair (\b arr, \b arrIndx) where \b arr indexes is in \b arrIndx.
10614  * This method will not impact the size of inout parameter \b arrIndx but the size of \b arr will be modified in case of suppression.
10615  * 
10616  * \param [in] idsToRemoveBg begin of set of ids to remove in \b arr (included)
10617  * \param [in] idsToRemoveEnd end of set of ids to remove in \b arr (excluded)
10618  * \param [in,out] arr array in which the remove operation will be done.
10619  * \param [in,out] arrIndx array in the remove operation will modify
10620  * \param [in] offsetForRemoval (by default 0) offset so that for each i in [0,arrIndx->getNumberOfTuples()-1) removal process will be performed in the following range [arr+arrIndx[i]+offsetForRemoval,arr+arr[i+1])
10621  * \return true if \b arr and \b arrIndx have been modified, false if not.
10622  */
10623 bool MEDCouplingUMesh::RemoveIdsFromIndexedArrays(const int *idsToRemoveBg, const int *idsToRemoveEnd, DataArrayInt *arr, DataArrayInt *arrIndx, int offsetForRemoval)
10624 {
10625   if(!arrIndx || !arr)
10626     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::RemoveIdsFromIndexedArrays : some input arrays are empty !");
10627   if(offsetForRemoval<0)
10628     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::RemoveIdsFromIndexedArrays : offsetForRemoval should be >=0 !");
10629   std::set<int> s(idsToRemoveBg,idsToRemoveEnd);
10630   int nbOfGrps=arrIndx->getNumberOfTuples()-1;
10631   int *arrIPtr=arrIndx->getPointer();
10632   *arrIPtr++=0;
10633   int previousArrI=0;
10634   const int *arrPtr=arr->getConstPointer();
10635   std::vector<int> arrOut;//no utility to switch to DataArrayInt because copy always needed
10636   for(int i=0;i<nbOfGrps;i++,arrIPtr++)
10637     {
10638       if(*arrIPtr-previousArrI>offsetForRemoval)
10639         {
10640           for(const int *work=arrPtr+previousArrI+offsetForRemoval;work!=arrPtr+*arrIPtr;work++)
10641             {
10642               if(s.find(*work)==s.end())
10643                 arrOut.push_back(*work);
10644             }
10645         }
10646       previousArrI=*arrIPtr;
10647       *arrIPtr=(int)arrOut.size();
10648     }
10649   if(arr->getNumberOfTuples()==(int)arrOut.size())
10650     return false;
10651   arr->alloc((int)arrOut.size(),1);
10652   std::copy(arrOut.begin(),arrOut.end(),arr->getPointer());
10653   return true;
10654 }
10655
10656 /*!
10657  * This method works on a pair input (\b arrIn, \b arrIndxIn) where \b arrIn indexes is in \b arrIndxIn.
10658  * This method returns the result of the extraction ( specified by a set of ids in [\b idsOfSelectBg , \b idsOfSelectEnd ) ).
10659  * The selection of extraction is done standardly in new2old format.
10660  * This method returns indexed arrays using 2 arrays (arrOut,arrIndexOut).
10661  *
10662  * \param [in] idsOfSelectBg begin of set of ids of the input extraction (included)
10663  * \param [in] idsOfSelectEnd end of set of ids of the input extraction (excluded)
10664  * \param [in] arrIn arr origin array from which the extraction will be done.
10665  * \param [in] arrIndxIn is the input index array allowing to walk into \b arrIn
10666  * \param [out] arrOut the resulting array
10667  * \param [out] arrIndexOut the index array of the resulting array \b arrOut
10668  * \sa MEDCouplingUMesh::ExtractFromIndexedArrays2
10669  */
10670 void MEDCouplingUMesh::ExtractFromIndexedArrays(const int *idsOfSelectBg, const int *idsOfSelectEnd, const DataArrayInt *arrIn, const DataArrayInt *arrIndxIn,
10671                                                 DataArrayInt* &arrOut, DataArrayInt* &arrIndexOut)
10672 {
10673   if(!arrIn || !arrIndxIn)
10674     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ExtractFromIndexedArrays : input pointer is NULL !");
10675   arrIn->checkAllocated(); arrIndxIn->checkAllocated();
10676   if(arrIn->getNumberOfComponents()!=1 || arrIndxIn->getNumberOfComponents()!=1)
10677     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ExtractFromIndexedArrays : input arrays must have exactly one component !");
10678   std::size_t sz=std::distance(idsOfSelectBg,idsOfSelectEnd);
10679   const int *arrInPtr=arrIn->getConstPointer();
10680   const int *arrIndxPtr=arrIndxIn->getConstPointer();
10681   int nbOfGrps=arrIndxIn->getNumberOfTuples()-1;
10682   if(nbOfGrps<0)
10683     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ExtractFromIndexedArrays : The format of \"arrIndxIn\" is invalid ! Its nb of tuples should be >=1 !");
10684   int maxSizeOfArr=arrIn->getNumberOfTuples();
10685   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> arro=DataArrayInt::New();
10686   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> arrIo=DataArrayInt::New();
10687   arrIo->alloc((int)(sz+1),1);
10688   const int *idsIt=idsOfSelectBg;
10689   int *work=arrIo->getPointer();
10690   *work++=0;
10691   int lgth=0;
10692   for(std::size_t i=0;i<sz;i++,work++,idsIt++)
10693     {
10694       if(*idsIt>=0 && *idsIt<nbOfGrps)
10695         lgth+=arrIndxPtr[*idsIt+1]-arrIndxPtr[*idsIt];
10696       else
10697         {
10698           std::ostringstream oss; oss << "MEDCouplingUMesh::ExtractFromIndexedArrays : id located on pos #" << i << " value is " << *idsIt << " ! Must be in [0," << nbOfGrps << ") !";
10699           throw INTERP_KERNEL::Exception(oss.str().c_str());
10700         }
10701       if(lgth>=work[-1])
10702         *work=lgth;
10703       else
10704         {
10705           std::ostringstream oss; oss << "MEDCouplingUMesh::ExtractFromIndexedArrays : id located on pos #" << i << " value is " << *idsIt << " and at this pos arrIndxIn[" << *idsIt;
10706           oss << "+1]-arrIndxIn[" << *idsIt << "] < 0 ! The input index array is bugged !";
10707           throw INTERP_KERNEL::Exception(oss.str().c_str());
10708         }
10709     }
10710   arro->alloc(lgth,1);
10711   work=arro->getPointer();
10712   idsIt=idsOfSelectBg;
10713   for(std::size_t i=0;i<sz;i++,idsIt++)
10714     {
10715       if(arrIndxPtr[*idsIt]>=0 && arrIndxPtr[*idsIt+1]<=maxSizeOfArr)
10716         work=std::copy(arrInPtr+arrIndxPtr[*idsIt],arrInPtr+arrIndxPtr[*idsIt+1],work);
10717       else
10718         {
10719           std::ostringstream oss; oss << "MEDCouplingUMesh::ExtractFromIndexedArrays : id located on pos #" << i << " value is " << *idsIt << " arrIndx[" << *idsIt << "] must be >= 0 and arrIndx[";
10720           oss << *idsIt << "+1] <= " << maxSizeOfArr << " (the size of arrIn)!";
10721           throw INTERP_KERNEL::Exception(oss.str().c_str());
10722         }
10723     }
10724   arrOut=arro.retn();
10725   arrIndexOut=arrIo.retn();
10726 }
10727
10728 /*!
10729  * This method works on a pair input (\b arrIn, \b arrIndxIn) where \b arrIn indexes is in \b arrIndxIn.
10730  * This method returns the result of the extraction ( specified by a set of ids with a slice given by \a idsOfSelectStart, \a idsOfSelectStop and \a idsOfSelectStep ).
10731  * The selection of extraction is done standardly in new2old format.
10732  * This method returns indexed arrays using 2 arrays (arrOut,arrIndexOut).
10733  *
10734  * \param [in] idsOfSelectBg begin of set of ids of the input extraction (included)
10735  * \param [in] idsOfSelectEnd end of set of ids of the input extraction (excluded)
10736  * \param [in] arrIn arr origin array from which the extraction will be done.
10737  * \param [in] arrIndxIn is the input index array allowing to walk into \b arrIn
10738  * \param [out] arrOut the resulting array
10739  * \param [out] arrIndexOut the index array of the resulting array \b arrOut
10740  * \sa MEDCouplingUMesh::ExtractFromIndexedArrays
10741  */
10742 void MEDCouplingUMesh::ExtractFromIndexedArrays2(int idsOfSelectStart, int idsOfSelectStop, int idsOfSelectStep, const DataArrayInt *arrIn, const DataArrayInt *arrIndxIn,
10743                                                  DataArrayInt* &arrOut, DataArrayInt* &arrIndexOut)
10744 {
10745   if(!arrIn || !arrIndxIn)
10746     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ExtractFromIndexedArrays2 : input pointer is NULL !");
10747   arrIn->checkAllocated(); arrIndxIn->checkAllocated();
10748   if(arrIn->getNumberOfComponents()!=1 || arrIndxIn->getNumberOfComponents()!=1)
10749     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ExtractFromIndexedArrays2 : input arrays must have exactly one component !");
10750   int sz=DataArrayInt::GetNumberOfItemGivenBESRelative(idsOfSelectStart,idsOfSelectStop,idsOfSelectStep,"MEDCouplingUMesh::ExtractFromIndexedArrays2 : Input slice ");
10751   const int *arrInPtr=arrIn->getConstPointer();
10752   const int *arrIndxPtr=arrIndxIn->getConstPointer();
10753   int nbOfGrps=arrIndxIn->getNumberOfTuples()-1;
10754   if(nbOfGrps<0)
10755     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ExtractFromIndexedArrays2 : The format of \"arrIndxIn\" is invalid ! Its nb of tuples should be >=1 !");
10756   int maxSizeOfArr=arrIn->getNumberOfTuples();
10757   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> arro=DataArrayInt::New();
10758   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> arrIo=DataArrayInt::New();
10759   arrIo->alloc((int)(sz+1),1);
10760   int idsIt=idsOfSelectStart;
10761   int *work=arrIo->getPointer();
10762   *work++=0;
10763   int lgth=0;
10764   for(int i=0;i<sz;i++,work++,idsIt+=idsOfSelectStep)
10765     {
10766       if(idsIt>=0 && idsIt<nbOfGrps)
10767         lgth+=arrIndxPtr[idsIt+1]-arrIndxPtr[idsIt];
10768       else
10769         {
10770           std::ostringstream oss; oss << "MEDCouplingUMesh::ExtractFromIndexedArrays2 : id located on pos #" << i << " value is " << idsIt << " ! Must be in [0," << nbOfGrps << ") !";
10771           throw INTERP_KERNEL::Exception(oss.str().c_str());
10772         }
10773       if(lgth>=work[-1])
10774         *work=lgth;
10775       else
10776         {
10777           std::ostringstream oss; oss << "MEDCouplingUMesh::ExtractFromIndexedArrays2 : id located on pos #" << i << " value is " << idsIt << " and at this pos arrIndxIn[" << idsIt;
10778           oss << "+1]-arrIndxIn[" << idsIt << "] < 0 ! The input index array is bugged !";
10779           throw INTERP_KERNEL::Exception(oss.str().c_str());
10780         }
10781     }
10782   arro->alloc(lgth,1);
10783   work=arro->getPointer();
10784   idsIt=idsOfSelectStart;
10785   for(int i=0;i<sz;i++,idsIt+=idsOfSelectStep)
10786     {
10787       if(arrIndxPtr[idsIt]>=0 && arrIndxPtr[idsIt+1]<=maxSizeOfArr)
10788         work=std::copy(arrInPtr+arrIndxPtr[idsIt],arrInPtr+arrIndxPtr[idsIt+1],work);
10789       else
10790         {
10791           std::ostringstream oss; oss << "MEDCouplingUMesh::ExtractFromIndexedArrays2 : id located on pos #" << i << " value is " << idsIt << " arrIndx[" << idsIt << "] must be >= 0 and arrIndx[";
10792           oss << idsIt << "+1] <= " << maxSizeOfArr << " (the size of arrIn)!";
10793           throw INTERP_KERNEL::Exception(oss.str().c_str());
10794         }
10795     }
10796   arrOut=arro.retn();
10797   arrIndexOut=arrIo.retn();
10798 }
10799
10800 /*!
10801  * This method works on an input pair (\b arrIn, \b arrIndxIn) where \b arrIn indexes is in \b arrIndxIn.
10802  * This method builds an output pair (\b arrOut,\b arrIndexOut) that is a copy from \b arrIn for all cell ids \b not \b in [ \b idsOfSelectBg , \b idsOfSelectEnd ) and for
10803  * cellIds \b in [ \b idsOfSelectBg , \b idsOfSelectEnd ) a copy coming from the corresponding values in input pair (\b srcArr, \b srcArrIndex).
10804  * This method is an generalization of MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx that performs the same thing but by without building explicitely a result output arrays.
10805  *
10806  * \param [in] idsOfSelectBg begin of set of ids of the input extraction (included)
10807  * \param [in] idsOfSelectEnd end of set of ids of the input extraction (excluded)
10808  * \param [in] arrIn arr origin array from which the extraction will be done.
10809  * \param [in] arrIndxIn is the input index array allowing to walk into \b arrIn
10810  * \param [in] srcArr input array that will be used as source of copy for ids in [ \b idsOfSelectBg, \b idsOfSelectEnd )
10811  * \param [in] srcArrIndex index array of \b srcArr
10812  * \param [out] arrOut the resulting array
10813  * \param [out] arrIndexOut the index array of the resulting array \b arrOut
10814  * 
10815  * \sa MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx
10816  */
10817 void MEDCouplingUMesh::SetPartOfIndexedArrays(const int *idsOfSelectBg, const int *idsOfSelectEnd, const DataArrayInt *arrIn, const DataArrayInt *arrIndxIn,
10818                                               const DataArrayInt *srcArr, const DataArrayInt *srcArrIndex,
10819                                               DataArrayInt* &arrOut, DataArrayInt* &arrIndexOut)
10820 {
10821   if(arrIn==0 || arrIndxIn==0 || srcArr==0 || srcArrIndex==0)
10822     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::SetPartOfIndexedArrays : presence of null pointer in input parameter !");
10823   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> arro=DataArrayInt::New();
10824   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> arrIo=DataArrayInt::New();
10825   int nbOfTuples=arrIndxIn->getNumberOfTuples()-1;
10826   std::vector<bool> v(nbOfTuples,true);
10827   int offset=0;
10828   const int *arrIndxInPtr=arrIndxIn->getConstPointer();
10829   const int *srcArrIndexPtr=srcArrIndex->getConstPointer();
10830   for(const int *it=idsOfSelectBg;it!=idsOfSelectEnd;it++,srcArrIndexPtr++)
10831     {
10832       if(*it>=0 && *it<nbOfTuples)
10833         {
10834           v[*it]=false;
10835           offset+=(srcArrIndexPtr[1]-srcArrIndexPtr[0])-(arrIndxInPtr[*it+1]-arrIndxInPtr[*it]);
10836         }
10837       else
10838         {
10839           std::ostringstream oss; oss << "MEDCouplingUMesh::SetPartOfIndexedArrays : On pos #" << std::distance(idsOfSelectBg,it) << " value is " << *it << " not in [0," << nbOfTuples << ") !";
10840           throw INTERP_KERNEL::Exception(oss.str().c_str());
10841         }
10842     }
10843   srcArrIndexPtr=srcArrIndex->getConstPointer();
10844   arrIo->alloc(nbOfTuples+1,1);
10845   arro->alloc(arrIn->getNumberOfTuples()+offset,1);
10846   const int *arrInPtr=arrIn->getConstPointer();
10847   const int *srcArrPtr=srcArr->getConstPointer();
10848   int *arrIoPtr=arrIo->getPointer(); *arrIoPtr++=0;
10849   int *arroPtr=arro->getPointer();
10850   for(int ii=0;ii<nbOfTuples;ii++,arrIoPtr++)
10851     {
10852       if(v[ii])
10853         {
10854           arroPtr=std::copy(arrInPtr+arrIndxInPtr[ii],arrInPtr+arrIndxInPtr[ii+1],arroPtr);
10855           *arrIoPtr=arrIoPtr[-1]+(arrIndxInPtr[ii+1]-arrIndxInPtr[ii]);
10856         }
10857       else
10858         {
10859           std::size_t pos=std::distance(idsOfSelectBg,std::find(idsOfSelectBg,idsOfSelectEnd,ii));
10860           arroPtr=std::copy(srcArrPtr+srcArrIndexPtr[pos],srcArrPtr+srcArrIndexPtr[pos+1],arroPtr);
10861           *arrIoPtr=arrIoPtr[-1]+(srcArrIndexPtr[pos+1]-srcArrIndexPtr[pos]);
10862         }
10863     }
10864   arrOut=arro.retn();
10865   arrIndexOut=arrIo.retn();
10866 }
10867
10868 /*!
10869  * This method works on an input pair (\b arrIn, \b arrIndxIn) where \b arrIn indexes is in \b arrIndxIn.
10870  * This method is an specialization of MEDCouplingUMesh::SetPartOfIndexedArrays in the case of assignement do not modify the index in \b arrIndxIn.
10871  *
10872  * \param [in] idsOfSelectBg begin of set of ids of the input extraction (included)
10873  * \param [in] idsOfSelectEnd end of set of ids of the input extraction (excluded)
10874  * \param [in,out] arrInOut arr origin array from which the extraction will be done.
10875  * \param [in] arrIndxIn is the input index array allowing to walk into \b arrIn
10876  * \param [in] srcArr input array that will be used as source of copy for ids in [ \b idsOfSelectBg , \b idsOfSelectEnd )
10877  * \param [in] srcArrIndex index array of \b srcArr
10878  * 
10879  * \sa MEDCouplingUMesh::SetPartOfIndexedArrays
10880  */
10881 void MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx(const int *idsOfSelectBg, const int *idsOfSelectEnd, DataArrayInt *arrInOut, const DataArrayInt *arrIndxIn,
10882                                                      const DataArrayInt *srcArr, const DataArrayInt *srcArrIndex)
10883 {
10884   if(arrInOut==0 || arrIndxIn==0 || srcArr==0 || srcArrIndex==0)
10885     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx : presence of null pointer in input parameter !");
10886   int nbOfTuples=arrIndxIn->getNumberOfTuples()-1;
10887   const int *arrIndxInPtr=arrIndxIn->getConstPointer();
10888   const int *srcArrIndexPtr=srcArrIndex->getConstPointer();
10889   int *arrInOutPtr=arrInOut->getPointer();
10890   const int *srcArrPtr=srcArr->getConstPointer();
10891   for(const int *it=idsOfSelectBg;it!=idsOfSelectEnd;it++,srcArrIndexPtr++)
10892     {
10893       if(*it>=0 && *it<nbOfTuples)
10894         {
10895           if(srcArrIndexPtr[1]-srcArrIndexPtr[0]==arrIndxInPtr[*it+1]-arrIndxInPtr[*it])
10896             std::copy(srcArrPtr+srcArrIndexPtr[0],srcArrPtr+srcArrIndexPtr[1],arrInOutPtr+arrIndxInPtr[*it]);
10897           else
10898             {
10899               std::ostringstream oss; oss << "MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx : On pos #" << std::distance(idsOfSelectBg,it) << " id (idsOfSelectBg[" << std::distance(idsOfSelectBg,it)<< "]) is " << *it << " arrIndxIn[id+1]-arrIndxIn[id]!=srcArrIndex[pos+1]-srcArrIndex[pos] !";
10900               throw INTERP_KERNEL::Exception(oss.str().c_str());
10901             }
10902         }
10903       else
10904         {
10905           std::ostringstream oss; oss << "MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx : On pos #" << std::distance(idsOfSelectBg,it) << " value is " << *it << " not in [0," << nbOfTuples << ") !";
10906           throw INTERP_KERNEL::Exception(oss.str().c_str());
10907         }
10908     }
10909 }
10910
10911 /*!
10912  * This method works on a pair input (\b arrIn, \b arrIndxIn) where \b arr indexes is in \b arrIndxIn.
10913  * This method expects that these two input arrays come from the output of MEDCouplingUMesh::computeNeighborsOfCells method.
10914  * This method start from id 0 that will be contained in output DataArrayInt. It searches then all neighbors of id0 regarding arrIn[arrIndxIn[0]:arrIndxIn[0+1]].
10915  * Then it is repeated recursively until either all ids are fetched or no more ids are reachable step by step.
10916  * A negative value in \b arrIn means that it is ignored.
10917  * This method is useful to see if a mesh is contiguous regarding its connectivity. If it is not the case the size of returned array is different from arrIndxIn->getNumberOfTuples()-1.
10918  * 
10919  * \param [in] arrIn arr origin array from which the extraction will be done.
10920  * \param [in] arrIndxIn is the input index array allowing to walk into \b arrIn
10921  * \return a newly allocated DataArray that stores all ids fetched by the gradually spread process.
10922  * \sa MEDCouplingUMesh::ComputeSpreadZoneGraduallyFromSeed, MEDCouplingUMesh::partitionBySpreadZone
10923  */
10924 DataArrayInt *MEDCouplingUMesh::ComputeSpreadZoneGradually(const DataArrayInt *arrIn, const DataArrayInt *arrIndxIn)
10925 {
10926   int seed=0,nbOfDepthPeelingPerformed=0;
10927   return ComputeSpreadZoneGraduallyFromSeed(&seed,&seed+1,arrIn,arrIndxIn,-1,nbOfDepthPeelingPerformed);
10928 }
10929
10930 /*!
10931  * This method works on a pair input (\b arrIn, \b arrIndxIn) where \b arr indexes is in \b arrIndxIn.
10932  * This method expects that these two input arrays come from the output of MEDCouplingUMesh::computeNeighborsOfCells method.
10933  * This method start from id 0 that will be contained in output DataArrayInt. It searches then all neighbors of id0 regarding arrIn[arrIndxIn[0]:arrIndxIn[0+1]].
10934  * Then it is repeated recursively until either all ids are fetched or no more ids are reachable step by step.
10935  * A negative value in \b arrIn means that it is ignored.
10936  * This method is useful to see if a mesh is contiguous regarding its connectivity. If it is not the case the size of returned array is different from arrIndxIn->getNumberOfTuples()-1.
10937  * \param [in] seedBg the begin pointer (included) of an array containing the seed of the search zone
10938  * \param [in] seedEnd the end pointer (not included) of an array containing the seed of the search zone
10939  * \param [in] arrIn arr origin array from which the extraction will be done.
10940  * \param [in] arrIndxIn is the input index array allowing to walk into \b arrIn
10941  * \param [in] nbOfDepthPeeling the max number of peels requested in search. By default -1, that is to say, no limit.
10942  * \param [out] nbOfDepthPeelingPerformed the number of peels effectively performed. May be different from \a nbOfDepthPeeling
10943  * \return a newly allocated DataArray that stores all ids fetched by the gradually spread process.
10944  * \sa MEDCouplingUMesh::partitionBySpreadZone
10945  */
10946 DataArrayInt *MEDCouplingUMesh::ComputeSpreadZoneGraduallyFromSeed(const int *seedBg, const int *seedEnd, const DataArrayInt *arrIn, const DataArrayInt *arrIndxIn, int nbOfDepthPeeling, int& nbOfDepthPeelingPerformed)
10947 {
10948   nbOfDepthPeelingPerformed=0;
10949   if(!arrIndxIn)
10950     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ComputeSpreadZoneGraduallyFromSeed : arrIndxIn input pointer is NULL !");
10951   int nbOfTuples=arrIndxIn->getNumberOfTuples()-1;
10952   if(nbOfTuples<=0)
10953     {
10954       DataArrayInt *ret=DataArrayInt::New(); ret->alloc(0,1);
10955       return ret;
10956     }
10957   //
10958   std::vector<bool> fetched(nbOfTuples,false);
10959   return ComputeSpreadZoneGraduallyFromSeedAlg(fetched,seedBg,seedEnd,arrIn,arrIndxIn,nbOfDepthPeeling,nbOfDepthPeelingPerformed);
10960 }
10961
10962 DataArrayInt *MEDCouplingUMesh::ComputeSpreadZoneGraduallyFromSeedAlg(std::vector<bool>& fetched, const int *seedBg, const int *seedEnd, const DataArrayInt *arrIn, const DataArrayInt *arrIndxIn, int nbOfDepthPeeling, int& nbOfDepthPeelingPerformed)
10963 {
10964   nbOfDepthPeelingPerformed=0;
10965   if(!seedBg || !seedEnd || !arrIn || !arrIndxIn)
10966     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ComputeSpreadZoneGraduallyFromSeedAlg : some input pointer is NULL !");
10967   int nbOfTuples=arrIndxIn->getNumberOfTuples()-1;
10968   std::vector<bool> fetched2(nbOfTuples,false);
10969   int i=0;
10970   for(const int *seedElt=seedBg;seedElt!=seedEnd;seedElt++,i++)
10971     {
10972       if(*seedElt>=0 && *seedElt<nbOfTuples)
10973         { fetched[*seedElt]=true; fetched2[*seedElt]=true; }
10974       else
10975         { std::ostringstream oss; oss << "MEDCouplingUMesh::ComputeSpreadZoneGraduallyFromSeedAlg : At pos #" << i << " of seeds value is " << *seedElt << "! Should be in [0," << nbOfTuples << ") !"; throw INTERP_KERNEL::Exception(oss.str().c_str()); }
10976     }
10977   const int *arrInPtr=arrIn->getConstPointer();
10978   const int *arrIndxPtr=arrIndxIn->getConstPointer();
10979   int targetNbOfDepthPeeling=nbOfDepthPeeling!=-1?nbOfDepthPeeling:std::numeric_limits<int>::max();
10980   std::vector<int> idsToFetch1(seedBg,seedEnd);
10981   std::vector<int> idsToFetch2;
10982   std::vector<int> *idsToFetch=&idsToFetch1;
10983   std::vector<int> *idsToFetchOther=&idsToFetch2;
10984   while(!idsToFetch->empty() && nbOfDepthPeelingPerformed<targetNbOfDepthPeeling)
10985     {
10986       for(std::vector<int>::const_iterator it=idsToFetch->begin();it!=idsToFetch->end();it++)
10987         for(const int *it2=arrInPtr+arrIndxPtr[*it];it2!=arrInPtr+arrIndxPtr[*it+1];it2++)
10988           if(!fetched[*it2])
10989             { fetched[*it2]=true; fetched2[*it2]=true; idsToFetchOther->push_back(*it2); }
10990       std::swap(idsToFetch,idsToFetchOther);
10991       idsToFetchOther->clear();
10992       nbOfDepthPeelingPerformed++;
10993     }
10994   int lgth=(int)std::count(fetched2.begin(),fetched2.end(),true);
10995   i=0;
10996   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New(); ret->alloc(lgth,1);
10997   int *retPtr=ret->getPointer();
10998   for(std::vector<bool>::const_iterator it=fetched2.begin();it!=fetched2.end();it++,i++)
10999     if(*it)
11000       *retPtr++=i;
11001   return ret.retn();
11002 }
11003
11004 /*!
11005  * This method works on an input pair (\b arrIn, \b arrIndxIn) where \b arrIn indexes is in \b arrIndxIn.
11006  * This method builds an output pair (\b arrOut,\b arrIndexOut) that is a copy from \b arrIn for all cell ids \b not \b in [ \b idsOfSelectBg , \b idsOfSelectEnd ) and for
11007  * cellIds \b in [\b idsOfSelectBg, \b idsOfSelectEnd) a copy coming from the corresponding values in input pair (\b srcArr, \b srcArrIndex).
11008  * This method is an generalization of MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx that performs the same thing but by without building explicitely a result output arrays.
11009  *
11010  * \param [in] start begin of set of ids of the input extraction (included)
11011  * \param [in] end end of set of ids of the input extraction (excluded)
11012  * \param [in] step step of the set of ids in range mode.
11013  * \param [in] arrIn arr origin array from which the extraction will be done.
11014  * \param [in] arrIndxIn is the input index array allowing to walk into \b arrIn
11015  * \param [in] srcArr input array that will be used as source of copy for ids in [\b idsOfSelectBg, \b idsOfSelectEnd)
11016  * \param [in] srcArrIndex index array of \b srcArr
11017  * \param [out] arrOut the resulting array
11018  * \param [out] arrIndexOut the index array of the resulting array \b arrOut
11019  * 
11020  * \sa MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx MEDCouplingUMesh::SetPartOfIndexedArrays
11021  */
11022 void MEDCouplingUMesh::SetPartOfIndexedArrays2(int start, int end, int step, const DataArrayInt *arrIn, const DataArrayInt *arrIndxIn,
11023                                                const DataArrayInt *srcArr, const DataArrayInt *srcArrIndex,
11024                                                DataArrayInt* &arrOut, DataArrayInt* &arrIndexOut)
11025 {
11026   if(arrIn==0 || arrIndxIn==0 || srcArr==0 || srcArrIndex==0)
11027     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::SetPartOfIndexedArrays2 : presence of null pointer in input parameter !");
11028   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> arro=DataArrayInt::New();
11029   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> arrIo=DataArrayInt::New();
11030   int nbOfTuples=arrIndxIn->getNumberOfTuples()-1;
11031   int offset=0;
11032   const int *arrIndxInPtr=arrIndxIn->getConstPointer();
11033   const int *srcArrIndexPtr=srcArrIndex->getConstPointer();
11034   int nbOfElemsToSet=DataArray::GetNumberOfItemGivenBESRelative(start,end,step,"MEDCouplingUMesh::SetPartOfIndexedArrays2 : ");
11035   int it=start;
11036   for(int i=0;i<nbOfElemsToSet;i++,srcArrIndexPtr++,it+=step)
11037     {
11038       if(it>=0 && it<nbOfTuples)
11039         offset+=(srcArrIndexPtr[1]-srcArrIndexPtr[0])-(arrIndxInPtr[it+1]-arrIndxInPtr[it]);
11040       else
11041         {
11042           std::ostringstream oss; oss << "MEDCouplingUMesh::SetPartOfIndexedArrays2 : On pos #" << i << " value is " << it << " not in [0," << nbOfTuples << ") !";
11043           throw INTERP_KERNEL::Exception(oss.str().c_str());
11044         }
11045     }
11046   srcArrIndexPtr=srcArrIndex->getConstPointer();
11047   arrIo->alloc(nbOfTuples+1,1);
11048   arro->alloc(arrIn->getNumberOfTuples()+offset,1);
11049   const int *arrInPtr=arrIn->getConstPointer();
11050   const int *srcArrPtr=srcArr->getConstPointer();
11051   int *arrIoPtr=arrIo->getPointer(); *arrIoPtr++=0;
11052   int *arroPtr=arro->getPointer();
11053   for(int ii=0;ii<nbOfTuples;ii++,arrIoPtr++)
11054     {
11055       int pos=DataArray::GetPosOfItemGivenBESRelativeNoThrow(ii,start,end,step);
11056       if(pos<0)
11057         {
11058           arroPtr=std::copy(arrInPtr+arrIndxInPtr[ii],arrInPtr+arrIndxInPtr[ii+1],arroPtr);
11059           *arrIoPtr=arrIoPtr[-1]+(arrIndxInPtr[ii+1]-arrIndxInPtr[ii]);
11060         }
11061       else
11062         {
11063           arroPtr=std::copy(srcArrPtr+srcArrIndexPtr[pos],srcArrPtr+srcArrIndexPtr[pos+1],arroPtr);
11064           *arrIoPtr=arrIoPtr[-1]+(srcArrIndexPtr[pos+1]-srcArrIndexPtr[pos]);
11065         }
11066     }
11067   arrOut=arro.retn();
11068   arrIndexOut=arrIo.retn();
11069 }
11070
11071 /*!
11072  * This method works on an input pair (\b arrIn, \b arrIndxIn) where \b arrIn indexes is in \b arrIndxIn.
11073  * This method is an specialization of MEDCouplingUMesh::SetPartOfIndexedArrays in the case of assignement do not modify the index in \b arrIndxIn.
11074  *
11075  * \param [in] start begin of set of ids of the input extraction (included)
11076  * \param [in] end end of set of ids of the input extraction (excluded)
11077  * \param [in] step step of the set of ids in range mode.
11078  * \param [in,out] arrInOut arr origin array from which the extraction will be done.
11079  * \param [in] arrIndxIn is the input index array allowing to walk into \b arrIn
11080  * \param [in] srcArr input array that will be used as source of copy for ids in [\b idsOfSelectBg, \b idsOfSelectEnd)
11081  * \param [in] srcArrIndex index array of \b srcArr
11082  * 
11083  * \sa MEDCouplingUMesh::SetPartOfIndexedArrays2 MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx
11084  */
11085 void MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx2(int start, int end, int step, DataArrayInt *arrInOut, const DataArrayInt *arrIndxIn,
11086                                                       const DataArrayInt *srcArr, const DataArrayInt *srcArrIndex)
11087 {
11088   if(arrInOut==0 || arrIndxIn==0 || srcArr==0 || srcArrIndex==0)
11089     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx2 : presence of null pointer in input parameter !");
11090   int nbOfTuples=arrIndxIn->getNumberOfTuples()-1;
11091   const int *arrIndxInPtr=arrIndxIn->getConstPointer();
11092   const int *srcArrIndexPtr=srcArrIndex->getConstPointer();
11093   int *arrInOutPtr=arrInOut->getPointer();
11094   const int *srcArrPtr=srcArr->getConstPointer();
11095   int nbOfElemsToSet=DataArray::GetNumberOfItemGivenBESRelative(start,end,step,"MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx2 : ");
11096   int it=start;
11097   for(int i=0;i<nbOfElemsToSet;i++,srcArrIndexPtr++,it+=step)
11098     {
11099       if(it>=0 && it<nbOfTuples)
11100         {
11101           if(srcArrIndexPtr[1]-srcArrIndexPtr[0]==arrIndxInPtr[it+1]-arrIndxInPtr[it])
11102             std::copy(srcArrPtr+srcArrIndexPtr[0],srcArrPtr+srcArrIndexPtr[1],arrInOutPtr+arrIndxInPtr[it]);
11103           else
11104             {
11105               std::ostringstream oss; oss << "MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx2 : On pos #" << i << " id (idsOfSelectBg[" << i << "]) is " << it << " arrIndxIn[id+1]-arrIndxIn[id]!=srcArrIndex[pos+1]-srcArrIndex[pos] !";
11106               throw INTERP_KERNEL::Exception(oss.str().c_str());
11107             }
11108         }
11109       else
11110         {
11111           std::ostringstream oss; oss << "MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx2 : On pos #" << i << " value is " << it << " not in [0," << nbOfTuples << ") !";
11112           throw INTERP_KERNEL::Exception(oss.str().c_str());
11113         }
11114     }
11115 }
11116
11117 /*!
11118  * \b this is expected to be a mesh fully defined whose spaceDim==meshDim.
11119  * It returns a new allocated mesh having the same mesh dimension and lying on same coordinates.
11120  * The returned mesh contains as poly cells as number of contiguous zone (regarding connectivity).
11121  * A spread contiguous zone is built using poly cells (polyhedra in 3D, polygons in 2D and polyline in 1D).
11122  * The sum of measure field of returned mesh is equal to the sum of measure field of this.
11123  * 
11124  * \return a newly allocated mesh lying on the same coords than \b this with same meshdimension than \b this.
11125  */
11126 MEDCouplingUMesh *MEDCouplingUMesh::buildSpreadZonesWithPoly() const
11127 {
11128   checkFullyDefined();
11129   int mdim=getMeshDimension();
11130   int spaceDim=getSpaceDimension();
11131   if(mdim!=spaceDim)
11132     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSpreadZonesWithPoly : meshdimension and spacedimension do not match !");
11133   std::vector<DataArrayInt *> partition=partitionBySpreadZone();
11134   std::vector< MEDCouplingAutoRefCountObjectPtr<DataArrayInt> > partitionAuto; partitionAuto.reserve(partition.size());
11135   std::copy(partition.begin(),partition.end(),std::back_insert_iterator<std::vector< MEDCouplingAutoRefCountObjectPtr<DataArrayInt> > >(partitionAuto));
11136   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> ret=MEDCouplingUMesh::New(getName(),mdim);
11137   ret->setCoords(getCoords());
11138   ret->allocateCells((int)partition.size());
11139   //
11140   for(std::vector<DataArrayInt *>::const_iterator it=partition.begin();it!=partition.end();it++)
11141     {
11142       MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> tmp=static_cast<MEDCouplingUMesh *>(buildPartOfMySelf((*it)->begin(),(*it)->end(),true));
11143       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> cell;
11144       switch(mdim)
11145       {
11146         case 2:
11147           cell=tmp->buildUnionOf2DMesh();
11148           break;
11149         case 3:
11150           cell=tmp->buildUnionOf3DMesh();
11151           break;
11152         default:
11153           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSpreadZonesWithPoly : meshdimension supported are [2,3] ! Not implemented yet for others !");
11154       }
11155
11156       ret->insertNextCell((INTERP_KERNEL::NormalizedCellType)cell->getIJSafe(0,0),cell->getNumberOfTuples()-1,cell->getConstPointer()+1);
11157     }
11158   //
11159   ret->finishInsertingCells();
11160   return ret.retn();
11161 }
11162
11163 /*!
11164  * This method partitions \b this into contiguous zone.
11165  * This method only needs a well defined connectivity. Coordinates are not considered here.
11166  * This method returns a vector of \b newly allocated arrays that the caller has to deal with.
11167  */
11168 std::vector<DataArrayInt *> MEDCouplingUMesh::partitionBySpreadZone() const
11169 {
11170   int nbOfCellsCur=getNumberOfCells();
11171   std::vector<DataArrayInt *> ret;
11172   if(nbOfCellsCur<=0)
11173     return ret;
11174   DataArrayInt *neigh=0,*neighI=0;
11175   computeNeighborsOfCells(neigh,neighI);
11176   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> neighAuto(neigh),neighIAuto(neighI);
11177   std::vector<bool> fetchedCells(nbOfCellsCur,false);
11178   std::vector< MEDCouplingAutoRefCountObjectPtr<DataArrayInt> > ret2;
11179   int seed=0;
11180   while(seed<nbOfCellsCur)
11181     {
11182       int nbOfPeelPerformed=0;
11183       ret2.push_back(ComputeSpreadZoneGraduallyFromSeedAlg(fetchedCells,&seed,&seed+1,neigh,neighI,-1,nbOfPeelPerformed));
11184       seed=(int)std::distance(fetchedCells.begin(),std::find(fetchedCells.begin()+seed,fetchedCells.end(),false));
11185     }
11186   for(std::vector< MEDCouplingAutoRefCountObjectPtr<DataArrayInt> >::iterator it=ret2.begin();it!=ret2.end();it++)
11187     ret.push_back((*it).retn());
11188   return ret;
11189 }
11190
11191 /*!
11192  * This method returns given a distribution of cell type (returned for example by MEDCouplingUMesh::getDistributionOfTypes method and customized after) a
11193  * newly allocated DataArrayInt instance with 2 components ready to be interpreted as input of DataArrayInt::findRangeIdForEachTuple method.
11194  *
11195  * \param [in] code a code with the same format than those returned by MEDCouplingUMesh::getDistributionOfTypes except for the code[3*k+2] that should contain start id of chunck.
11196  * \return a newly allocated DataArrayInt to be managed by the caller.
11197  * \throw In case of \a code has not the right format (typically of size 3*n)
11198  */
11199 DataArrayInt *MEDCouplingUMesh::ComputeRangesFromTypeDistribution(const std::vector<int>& code)
11200 {
11201   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New();
11202   std::size_t nb=code.size()/3;
11203   if(code.size()%3!=0)
11204     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ComputeRangesFromTypeDistribution : invalid input code !");
11205   ret->alloc((int)nb,2);
11206   int *retPtr=ret->getPointer();
11207   for(std::size_t i=0;i<nb;i++,retPtr+=2)
11208     {
11209       retPtr[0]=code[3*i+2];
11210       retPtr[1]=code[3*i+2]+code[3*i+1];
11211     }
11212   return ret.retn();
11213 }
11214
11215 /*!
11216  * This method expects that \a this a 3D mesh (spaceDim=3 and meshDim=3) with all coordinates and connectivities set.
11217  * All cells in \a this are expected to be linear 3D cells.
11218  * This method will split **all** 3D cells in \a this into INTERP_KERNEL::NORM_TETRA4 cells and put them in the returned mesh.
11219  * It leads to an increase to number of cells.
11220  * This method contrary to MEDCouplingUMesh::simplexize can append coordinates in \a this to perform its work.
11221  * The \a nbOfAdditionalPoints returned value informs about it. If > 0, the coordinates array in returned mesh will have \a nbOfAdditionalPoints 
11222  * more tuples (nodes) than in \a this. Anyway, all the nodes in \a this (with the same order) will be in the returned mesh.
11223  *
11224  * \param [in] policy - the policy of splitting that must be in (PLANAR_FACE_5, PLANAR_FACE_6, GENERAL_24, GENERAL_48). The policy will be used only for INTERP_KERNEL::NORM_HEXA8 cells.
11225  *                      For all other cells, the splitting policy will be ignored.
11226  * \param [out] nbOfAdditionalPoints - number of nodes added to \c this->_coords. If > 0 a new coordinates object will be constructed result of the aggregation of the old one and the new points added. 
11227  * \param [out] n2oCells - A new instance of DataArrayInt holding, for each new cell,
11228  *          an id of old cell producing it. The caller is to delete this array using
11229  *         decrRef() as it is no more needed.
11230  * \return MEDCoupling1SGTUMesh * - the mesh containing only INTERP_KERNEL::NORM_TETRA4 cells.
11231  *
11232  * \warning This method operates on each cells in this independantly ! So it can leads to non conform mesh in returned value ! If you expect to have a conform mesh in output
11233  * the policy PLANAR_FACE_6 should be used on a mesh sorted with MEDCoupling1SGTUMesh::sortHexa8EachOther.
11234  * 
11235  * \throw If \a this is not a 3D mesh (spaceDim==3 and meshDim==3).
11236  * \throw If \a this is not fully constituted with linear 3D cells.
11237  * \sa MEDCouplingUMesh::simplexize, MEDCoupling1SGTUMesh::sortHexa8EachOther
11238  */
11239 MEDCoupling1SGTUMesh *MEDCouplingUMesh::tetrahedrize(int policy, DataArrayInt *& n2oCells, int& nbOfAdditionalPoints) const
11240 {
11241   INTERP_KERNEL::SplittingPolicy pol((INTERP_KERNEL::SplittingPolicy)policy);
11242   checkConnectivityFullyDefined();
11243   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
11244     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::tetrahedrize : only available for mesh with meshdim == 3 and spacedim == 3 !");
11245   int nbOfCells(getNumberOfCells()),nbNodes(getNumberOfNodes());
11246   MEDCouplingAutoRefCountObjectPtr<MEDCoupling1SGTUMesh> ret0(MEDCoupling1SGTUMesh::New(getName(),INTERP_KERNEL::NORM_TETRA4));
11247   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret(DataArrayInt::New()); ret->alloc(nbOfCells,1);
11248   int *retPt(ret->getPointer());
11249   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> newConn(DataArrayInt::New()); newConn->alloc(0,1);
11250   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> addPts(DataArrayDouble::New()); addPts->alloc(0,1);
11251   const int *oldc(_nodal_connec->begin());
11252   const int *oldci(_nodal_connec_index->begin());
11253   const double *coords(_coords->begin());
11254   for(int i=0;i<nbOfCells;i++,oldci++,retPt++)
11255     {
11256       std::vector<int> a; std::vector<double> b;
11257       INTERP_KERNEL::SplitIntoTetras(pol,(INTERP_KERNEL::NormalizedCellType)oldc[oldci[0]],oldc+oldci[0]+1,oldc+oldci[1],coords,a,b);
11258       std::size_t nbOfTet(a.size()/4); *retPt=(int)nbOfTet;
11259       const int *aa(&a[0]);
11260       if(!b.empty())
11261         {
11262           for(std::vector<int>::iterator it=a.begin();it!=a.end();it++)
11263             if(*it<0)
11264               *it=(-(*(it))-1+nbNodes);
11265           addPts->insertAtTheEnd(b.begin(),b.end());
11266           nbNodes+=(int)b.size()/3;
11267         }
11268       for(std::size_t j=0;j<nbOfTet;j++,aa+=4)
11269         newConn->insertAtTheEnd(aa,aa+4);
11270     }
11271   if(!addPts->empty())
11272     {
11273       addPts->rearrange(3);
11274       nbOfAdditionalPoints=addPts->getNumberOfTuples();
11275       addPts=DataArrayDouble::Aggregate(getCoords(),addPts);
11276       ret0->setCoords(addPts);
11277     }
11278   else
11279     {
11280       nbOfAdditionalPoints=0;
11281       ret0->setCoords(getCoords());
11282     }
11283   ret0->setNodalConnectivity(newConn);
11284   //
11285   ret->computeOffsets2();
11286   n2oCells=ret->buildExplicitArrOfSliceOnScaledArr(0,nbOfCells,1);
11287   return ret0.retn();
11288 }
11289
11290 /*!
11291  * It is the linear part of MEDCouplingUMesh::split2DCells. Here no additionnal nodes will be added in \b this. So coordinates pointer remain unchanged (is not even touch). 
11292  *
11293  * \sa MEDCouplingUMesh::split2DCells
11294  */
11295 void MEDCouplingUMesh::split2DCellsLinear(const DataArrayInt *desc, const DataArrayInt *descI, const DataArrayInt *subNodesInSeg, const DataArrayInt *subNodesInSegI)
11296 {
11297   checkConnectivityFullyDefined();
11298   int ncells(getNumberOfCells()),lgthToReach(getMeshLength()+subNodesInSeg->getNumberOfTuples());
11299   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> c(DataArrayInt::New()); c->alloc((std::size_t)lgthToReach);
11300   const int *subPtr(subNodesInSeg->begin()),*subIPtr(subNodesInSegI->begin()),*descPtr(desc->begin()),*descIPtr(descI->begin()),*oldConn(getNodalConnectivity()->begin());
11301   int *cPtr(c->getPointer()),*ciPtr(getNodalConnectivityIndex()->getPointer());
11302   int prevPosOfCi(ciPtr[0]);
11303   for(int i=0;i<ncells;i++,ciPtr++,descIPtr++)
11304     {
11305       int offset(descIPtr[0]),sz(descIPtr[1]-descIPtr[0]),deltaSz(0);
11306       *cPtr++=(int)INTERP_KERNEL::NORM_POLYGON; *cPtr++=oldConn[prevPosOfCi+1];
11307       for(int j=0;j<sz;j++)
11308         {
11309           int offset2(subIPtr[descPtr[offset+j]]),sz2(subIPtr[descPtr[offset+j]+1]-subIPtr[descPtr[offset+j]]);
11310           for(int k=0;k<sz2;k++)
11311             *cPtr++=subPtr[offset2+k];
11312           if(j!=sz-1)
11313             *cPtr++=oldConn[prevPosOfCi+j+2];
11314           deltaSz+=sz2;
11315         }
11316       prevPosOfCi=ciPtr[1];
11317       ciPtr[1]=ciPtr[0]+1+sz+deltaSz;//sz==old nb of nodes because (nb of subedges=nb of nodes for polygons)
11318     }
11319   if(c->end()!=cPtr)
11320     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::split2DCellsLinear : Some of edges to be split are orphan !");
11321   _nodal_connec->decrRef();
11322   _nodal_connec=c.retn(); _types.clear(); _types.insert(INTERP_KERNEL::NORM_POLYGON);
11323 }
11324
11325 int InternalAddPoint(const INTERP_KERNEL::Edge *e, int id, const double *coo, int startId, int endId, DataArrayDouble& addCoo, int& nodesCnter)
11326 {
11327   if(id!=-1)
11328     return id;
11329   else
11330     {
11331       int ret(nodesCnter++);
11332       double newPt[2];
11333       e->getMiddleOfPoints(coo+2*startId,coo+2*endId,newPt);
11334       addCoo.insertAtTheEnd(newPt,newPt+2);
11335       return ret;
11336     }
11337 }
11338
11339 /// @cond INTERNAL
11340
11341 void EnterTheResultOf2DCellFirst(const INTERP_KERNEL::Edge *e, int start, int stp, int nbOfEdges, bool linOrArc, const double *coords, const int *connBg, int offset, DataArrayInt *newConnOfCell, DataArrayDouble *appendedCoords, std::vector<int>& middles)
11342 {
11343   int tmp[3];
11344   int trueStart(start>=0?start:nbOfEdges+start);
11345   tmp[0]=linOrArc?(int)INTERP_KERNEL::NORM_QPOLYG:(int)INTERP_KERNEL::NORM_POLYGON; tmp[1]=connBg[trueStart]; tmp[2]=connBg[stp];
11346   newConnOfCell->insertAtTheEnd(tmp,tmp+3);
11347   if(linOrArc)
11348     {
11349       if(stp-start>1)
11350         {
11351           int tmp2(0),tmp3(appendedCoords->getNumberOfTuples()/2);
11352           InternalAddPoint(e,-1,coords,tmp[1],tmp[2],*appendedCoords,tmp2);
11353           middles.push_back(tmp3+offset);
11354         }
11355       else
11356         middles.push_back(connBg[trueStart+nbOfEdges]);
11357     }
11358 }
11359
11360 void EnterTheResultOf2DCellMiddle(const INTERP_KERNEL::Edge *e, int start, int stp, int nbOfEdges, bool linOrArc, const double *coords, const int *connBg, int offset, DataArrayInt *newConnOfCell, DataArrayDouble *appendedCoords, std::vector<int>& middles)
11361 {
11362   int tmpSrt(newConnOfCell->back()),tmpEnd(connBg[stp]);
11363   newConnOfCell->pushBackSilent(tmpEnd);
11364   if(linOrArc)
11365     {
11366       if(stp-start>1)
11367         {
11368           int tmp2(0),tmp3(appendedCoords->getNumberOfTuples()/2);
11369           InternalAddPoint(e,-1,coords,tmpSrt,tmpEnd,*appendedCoords,tmp2);
11370           middles.push_back(tmp3+offset);
11371         }
11372       else
11373         middles.push_back(connBg[start+nbOfEdges]);
11374     }
11375 }
11376
11377 void EnterTheResultOf2DCellEnd(const INTERP_KERNEL::Edge *e, int start, int stp, int nbOfEdges, bool linOrArc, const double *coords, const int *connBg, int offset, DataArrayInt *newConnOfCell, DataArrayDouble *appendedCoords, std::vector<int>& middles)
11378 {
11379   if(linOrArc)
11380     {
11381       if(stp-start>1)
11382         {
11383           int tmpSrt(connBg[start]),tmpEnd(connBg[stp]);
11384           int tmp2(0),tmp3(appendedCoords->getNumberOfTuples()/2);
11385           InternalAddPoint(e,-1,coords,tmpSrt,tmpEnd,*appendedCoords,tmp2);
11386           middles.push_back(tmp3+offset);
11387         }
11388       else
11389         middles.push_back(connBg[start+nbOfEdges]);
11390     }
11391 }
11392
11393 /// @cond INTERNAL
11394
11395 /*!
11396  * Returns true if a colinearization has been found in the given cell. If false is returned the content pushed in \a newConnOfCell is equal to [ \a connBg , \a connEnd ) .
11397  * \a appendedCoords is a DataArrayDouble instance with number of components equal to one (even if the items are pushed by pair).
11398  */
11399 bool MEDCouplingUMesh::Colinearize2DCell(const double *coords, const int *connBg, const int *connEnd, int offset, DataArrayInt *newConnOfCell, DataArrayDouble *appendedCoords)
11400 {
11401   std::size_t sz(std::distance(connBg,connEnd));
11402   if(sz<3)//3 because 2+1(for the cell type) and 2 is the minimal number of edges of 2D cell.
11403     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::Colinearize2DCell : the input cell has invalid format !");
11404   sz--;
11405   INTERP_KERNEL::AutoPtr<int> tmpConn(new int[sz]);
11406   const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)connBg[0]));
11407   unsigned nbs(cm.getNumberOfSons2(connBg+1,sz)),nbOfHit(0);
11408   int posBaseElt(0),posEndElt(0),nbOfTurn(0);
11409   INTERP_KERNEL::NormalizedCellType typeOfSon;
11410   std::vector<int> middles;
11411   bool ret(false);
11412   for(;nbOfHit<nbs;nbOfTurn++)
11413     {
11414       cm.fillSonCellNodalConnectivity2(posBaseElt,connBg+1,sz,tmpConn,typeOfSon);
11415       std::map<MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Node>,int> m;
11416       INTERP_KERNEL::Edge *e(MEDCouplingUMeshBuildQPFromEdge2(typeOfSon,tmpConn,coords,m));
11417       posEndElt++;
11418       nbOfHit++;
11419       unsigned endI(nbs-nbOfHit);
11420       for(unsigned i=0;i<endI;i++)
11421         {
11422           cm.fillSonCellNodalConnectivity2(posBaseElt+(int)i+1,connBg+1,sz,tmpConn,typeOfSon);
11423           INTERP_KERNEL::Edge *eCand(MEDCouplingUMeshBuildQPFromEdge2(typeOfSon,tmpConn,coords,m));
11424           INTERP_KERNEL::EdgeIntersector *eint(INTERP_KERNEL::Edge::BuildIntersectorWith(e,eCand));
11425           bool isColinear(eint->areColinears());
11426           if(isColinear)
11427             {
11428               nbOfHit++;
11429               posEndElt++;
11430               ret=true;
11431             }
11432           delete eint;
11433           eCand->decrRef();
11434           if(!isColinear)
11435             {
11436               if(nbOfTurn==0)
11437                 {//look if the first edge of cell is not colinear with last edges in this case the start of nodal connectivity is shifted back
11438                   unsigned endII(nbs-nbOfHit-1);//warning nbOfHit can be modified, so put end condition in a variable.
11439                   for(unsigned ii=0;ii<endII;ii++)
11440                     {
11441                       cm.fillSonCellNodalConnectivity2(nbs-ii-1,connBg+1,sz,tmpConn,typeOfSon);
11442                       eCand=MEDCouplingUMeshBuildQPFromEdge2(typeOfSon,tmpConn,coords,m);
11443                       eint=INTERP_KERNEL::Edge::BuildIntersectorWith(e,eCand);
11444                       isColinear=eint->areColinears();
11445                       if(isColinear)
11446                         {
11447                           nbOfHit++;
11448                           posBaseElt--;
11449                           ret=true;
11450                         }
11451                       delete eint;
11452                       eCand->decrRef();
11453                       if(!isColinear)
11454                         break;
11455                     }
11456                 }
11457               break;
11458             }
11459         }
11460       //push [posBaseElt,posEndElt) in newConnOfCell using e
11461       if(nbOfTurn==0)
11462         EnterTheResultOf2DCellFirst(e,posBaseElt,posEndElt,(int)nbs,cm.isQuadratic(),coords,connBg+1,offset,newConnOfCell,appendedCoords,middles);
11463       else if(nbOfHit!=nbs)
11464         EnterTheResultOf2DCellMiddle(e,posBaseElt,posEndElt,(int)nbs,cm.isQuadratic(),coords,connBg+1,offset,newConnOfCell,appendedCoords,middles);
11465       else
11466         EnterTheResultOf2DCellEnd(e,posBaseElt,posEndElt,(int)nbs,cm.isQuadratic(),coords,connBg+1,offset,newConnOfCell,appendedCoords,middles);
11467       posBaseElt=posEndElt;
11468       e->decrRef();
11469     }
11470   if(!middles.empty())
11471     newConnOfCell->insertAtTheEnd(middles.begin(),middles.end());
11472   return ret;
11473 }
11474
11475 /*!
11476  * It is the quadratic part of MEDCouplingUMesh::split2DCells. Here some additionnal nodes can be added at the end of coordinates array object.
11477  *
11478  * \return  int - the number of new nodes created.
11479  * \sa MEDCouplingUMesh::split2DCells
11480  */
11481 int MEDCouplingUMesh::split2DCellsQuadratic(const DataArrayInt *desc, const DataArrayInt *descI, const DataArrayInt *subNodesInSeg, const DataArrayInt *subNodesInSegI, const DataArrayInt *mid, const DataArrayInt *midI)
11482 {
11483   checkCoherency();
11484   int ncells(getNumberOfCells()),lgthToReach(getMeshLength()+2*subNodesInSeg->getNumberOfTuples()),nodesCnt(getNumberOfNodes());
11485   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> c(DataArrayInt::New()); c->alloc((std::size_t)lgthToReach);
11486   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> addCoo(DataArrayDouble::New()); addCoo->alloc(0,1);
11487   const int *subPtr(subNodesInSeg->begin()),*subIPtr(subNodesInSegI->begin()),*descPtr(desc->begin()),*descIPtr(descI->begin()),*oldConn(getNodalConnectivity()->begin());
11488   const int *midPtr(mid->begin()),*midIPtr(midI->begin());
11489   const double *oldCoordsPtr(getCoords()->begin());
11490   int *cPtr(c->getPointer()),*ciPtr(getNodalConnectivityIndex()->getPointer());
11491   int prevPosOfCi(ciPtr[0]);
11492   for(int i=0;i<ncells;i++,ciPtr++,descIPtr++)
11493     {
11494       int offset(descIPtr[0]),sz(descIPtr[1]-descIPtr[0]),deltaSz(sz);
11495       for(int j=0;j<sz;j++)
11496         { int sz2(subIPtr[descPtr[offset+j]+1]-subIPtr[descPtr[offset+j]]); deltaSz+=sz2; }
11497       *cPtr++=(int)INTERP_KERNEL::NORM_QPOLYG; cPtr[0]=oldConn[prevPosOfCi+1];
11498       for(int j=0;j<sz;j++)//loop over subedges of oldConn
11499         {
11500           int offset2(subIPtr[descPtr[offset+j]]),sz2(subIPtr[descPtr[offset+j]+1]-subIPtr[descPtr[offset+j]]),offset3(midIPtr[descPtr[offset+j]]);
11501           if(sz2==0)
11502             {
11503               if(j<sz-1)
11504                 cPtr[1]=oldConn[prevPosOfCi+2+j];
11505               cPtr[deltaSz]=oldConn[prevPosOfCi+1+j+sz]; cPtr++;
11506               continue;
11507             }
11508           std::vector<INTERP_KERNEL::Node *> ns(3);
11509           ns[0]=new INTERP_KERNEL::Node(oldCoordsPtr[2*oldConn[prevPosOfCi+1+j]],oldCoordsPtr[2*oldConn[prevPosOfCi+1+j]+1]);
11510           ns[1]=new INTERP_KERNEL::Node(oldCoordsPtr[2*oldConn[prevPosOfCi+1+(1+j)%sz]],oldCoordsPtr[2*oldConn[prevPosOfCi+1+(1+j)%sz]+1]);
11511           ns[2]=new INTERP_KERNEL::Node(oldCoordsPtr[2*oldConn[prevPosOfCi+1+sz+j]],oldCoordsPtr[2*oldConn[prevPosOfCi+1+sz+j]+1]);
11512           MEDCouplingAutoRefCountObjectPtr<INTERP_KERNEL::Edge> e(INTERP_KERNEL::QuadraticPolygon::BuildArcCircleEdge(ns));
11513           for(int k=0;k<sz2;k++)//loop over subsplit of current subedge
11514             {
11515               cPtr[1]=subPtr[offset2+k];
11516               cPtr[deltaSz]=InternalAddPoint(e,midPtr[offset3+k],oldCoordsPtr,cPtr[0],cPtr[1],*addCoo,nodesCnt); cPtr++;
11517             }
11518           int tmpEnd(oldConn[prevPosOfCi+1+(j+1)%sz]);
11519           if(j!=sz-1)
11520             { cPtr[1]=tmpEnd; }
11521           cPtr[deltaSz]=InternalAddPoint(e,midPtr[offset3+sz2],oldCoordsPtr,cPtr[0],tmpEnd,*addCoo,nodesCnt); cPtr++;
11522         }
11523       prevPosOfCi=ciPtr[1]; cPtr+=deltaSz;
11524       ciPtr[1]=ciPtr[0]+1+2*deltaSz;//sz==old nb of nodes because (nb of subedges=nb of nodes for polygons)
11525     }
11526   if(c->end()!=cPtr)
11527     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::split2DCellsQuadratic : Some of edges to be split are orphan !");
11528   _nodal_connec->decrRef();
11529   _nodal_connec=c.retn(); _types.clear(); _types.insert(INTERP_KERNEL::NORM_QPOLYG);
11530   addCoo->rearrange(2);
11531   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> coo(DataArrayDouble::Aggregate(getCoords(),addCoo));//info are copied from getCoords() by using Aggregate
11532   setCoords(coo);
11533   return addCoo->getNumberOfTuples();
11534 }
11535
11536 MEDCouplingUMeshCellIterator::MEDCouplingUMeshCellIterator(MEDCouplingUMesh *mesh):_mesh(mesh),_cell(new MEDCouplingUMeshCell(mesh)),
11537     _own_cell(true),_cell_id(-1),_nb_cell(0)
11538 {
11539   if(mesh)
11540     {
11541       mesh->incrRef();
11542       _nb_cell=mesh->getNumberOfCells();
11543     }
11544 }
11545
11546 MEDCouplingUMeshCellIterator::~MEDCouplingUMeshCellIterator()
11547 {
11548   if(_mesh)
11549     _mesh->decrRef();
11550   if(_own_cell)
11551     delete _cell;
11552 }
11553
11554 MEDCouplingUMeshCellIterator::MEDCouplingUMeshCellIterator(MEDCouplingUMesh *mesh, MEDCouplingUMeshCell *itc, int bg, int end):_mesh(mesh),_cell(itc),
11555     _own_cell(false),_cell_id(bg-1),
11556     _nb_cell(end)
11557 {
11558   if(mesh)
11559     mesh->incrRef();
11560 }
11561
11562 MEDCouplingUMeshCell *MEDCouplingUMeshCellIterator::nextt()
11563 {
11564   _cell_id++;
11565   if(_cell_id<_nb_cell)
11566     {
11567       _cell->next();
11568       return _cell;
11569     }
11570   else
11571     return 0;
11572 }
11573
11574 MEDCouplingUMeshCellByTypeEntry::MEDCouplingUMeshCellByTypeEntry(MEDCouplingUMesh *mesh):_mesh(mesh)
11575 {
11576   if(_mesh)
11577     _mesh->incrRef();
11578 }
11579
11580 MEDCouplingUMeshCellByTypeIterator *MEDCouplingUMeshCellByTypeEntry::iterator()
11581 {
11582   return new MEDCouplingUMeshCellByTypeIterator(_mesh);
11583 }
11584
11585 MEDCouplingUMeshCellByTypeEntry::~MEDCouplingUMeshCellByTypeEntry()
11586 {
11587   if(_mesh)
11588     _mesh->decrRef();
11589 }
11590
11591 MEDCouplingUMeshCellEntry::MEDCouplingUMeshCellEntry(MEDCouplingUMesh *mesh,  INTERP_KERNEL::NormalizedCellType type, MEDCouplingUMeshCell *itc, int bg, int end):_mesh(mesh),_type(type),
11592     _itc(itc),
11593     _bg(bg),_end(end)
11594 {
11595   if(_mesh)
11596     _mesh->incrRef();
11597 }
11598
11599 MEDCouplingUMeshCellEntry::~MEDCouplingUMeshCellEntry()
11600 {
11601   if(_mesh)
11602     _mesh->decrRef();
11603 }
11604
11605 INTERP_KERNEL::NormalizedCellType MEDCouplingUMeshCellEntry::getType() const
11606 {
11607   return _type;
11608 }
11609
11610 int MEDCouplingUMeshCellEntry::getNumberOfElems() const
11611 {
11612   return _end-_bg;
11613 }
11614
11615 MEDCouplingUMeshCellIterator *MEDCouplingUMeshCellEntry::iterator()
11616 {
11617   return new MEDCouplingUMeshCellIterator(_mesh,_itc,_bg,_end);
11618 }
11619
11620 MEDCouplingUMeshCellByTypeIterator::MEDCouplingUMeshCellByTypeIterator(MEDCouplingUMesh *mesh):_mesh(mesh),_cell(new MEDCouplingUMeshCell(mesh)),_cell_id(0),_nb_cell(0)
11621 {
11622   if(mesh)
11623     {
11624       mesh->incrRef();
11625       _nb_cell=mesh->getNumberOfCells();
11626     }
11627 }
11628
11629 MEDCouplingUMeshCellByTypeIterator::~MEDCouplingUMeshCellByTypeIterator()
11630 {
11631   if(_mesh)
11632     _mesh->decrRef();
11633   delete _cell;
11634 }
11635
11636 MEDCouplingUMeshCellEntry *MEDCouplingUMeshCellByTypeIterator::nextt()
11637 {
11638   const int *c=_mesh->getNodalConnectivity()->getConstPointer();
11639   const int *ci=_mesh->getNodalConnectivityIndex()->getConstPointer();
11640   if(_cell_id<_nb_cell)
11641     {
11642       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)c[ci[_cell_id]];
11643       int nbOfElems=(int)std::distance(ci+_cell_id,std::find_if(ci+_cell_id,ci+_nb_cell,ParaMEDMEMImpl::ConnReader(c,type)));
11644       int startId=_cell_id;
11645       _cell_id+=nbOfElems;
11646       return new MEDCouplingUMeshCellEntry(_mesh,type,_cell,startId,_cell_id);
11647     }
11648   else
11649     return 0;
11650 }
11651
11652 MEDCouplingUMeshCell::MEDCouplingUMeshCell(MEDCouplingUMesh *mesh):_conn(0),_conn_indx(0),_conn_lgth(NOTICABLE_FIRST_VAL)
11653 {
11654   if(mesh)
11655     {
11656       _conn=mesh->getNodalConnectivity()->getPointer();
11657       _conn_indx=mesh->getNodalConnectivityIndex()->getPointer();
11658     }
11659 }
11660
11661 void MEDCouplingUMeshCell::next()
11662 {
11663   if(_conn_lgth!=NOTICABLE_FIRST_VAL)
11664     {
11665       _conn+=_conn_lgth;
11666       _conn_indx++;
11667     }
11668   _conn_lgth=_conn_indx[1]-_conn_indx[0];
11669 }
11670
11671 std::string MEDCouplingUMeshCell::repr() const
11672 {
11673   if(_conn_lgth!=NOTICABLE_FIRST_VAL)
11674     {
11675       std::ostringstream oss; oss << "Cell Type " << INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)_conn[0]).getRepr();
11676       oss << " : ";
11677       std::copy(_conn+1,_conn+_conn_lgth,std::ostream_iterator<int>(oss," "));
11678       return oss.str();
11679     }
11680   else
11681     return std::string("MEDCouplingUMeshCell::repr : Invalid pos");
11682 }
11683
11684 INTERP_KERNEL::NormalizedCellType MEDCouplingUMeshCell::getType() const
11685 {
11686   if(_conn_lgth!=NOTICABLE_FIRST_VAL)
11687     return (INTERP_KERNEL::NormalizedCellType)_conn[0];
11688   else
11689     return INTERP_KERNEL::NORM_ERROR;
11690 }
11691
11692 const int *MEDCouplingUMeshCell::getAllConn(int& lgth) const
11693 {
11694   lgth=_conn_lgth;
11695   if(_conn_lgth!=NOTICABLE_FIRST_VAL)
11696     return _conn;
11697   else
11698     return 0;
11699 }