Salome HOME
Backward compatibility OCCT < 6.8.0
[modules/geom.git] / src / GEOMImpl / GEOMImpl_IShapesOperations.cxx
index 68231130216ea6a1bcf1ebba3bb98498ad6e3b24..75a2b46d4de397113a72d2c3417179e1e41b8f7a 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
+// Copyright (C) 2007-2014  CEA/DEN, EDF R&D, OPEN CASCADE
 //
 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
@@ -6,7 +6,7 @@
 // This library is free software; you can redistribute it and/or
 // modify it under the terms of the GNU Lesser General Public
 // License as published by the Free Software Foundation; either
-// version 2.1 of the License.
+// version 2.1 of the License, or (at your option) any later version.
 //
 // This library is distributed in the hope that it will be useful,
 // but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -18,6 +18,7 @@
 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 //
 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
 
 //  File      : GEOMImpl_IShapesOperations.cxx
 //  Created   :
@@ -32,7 +33,6 @@
 
 #include "GEOMImpl_VectorDriver.hxx"
 #include "GEOMImpl_ShapeDriver.hxx"
-#include "GEOMImpl_CopyDriver.hxx"
 #include "GEOMImpl_GlueDriver.hxx"
 
 #include "GEOMImpl_IVector.hxx"
 #include "GEOMImpl_Block6Explorer.hxx"
 #include "GEOMImpl_IHealingOperations.hxx"
 
-#include <GEOMImpl_Gen.hxx>
+#include "GEOMImpl_Gen.hxx"
 
 #include "GEOM_Function.hxx"
 #include "GEOM_ISubShape.hxx"
 #include "GEOM_PythonDump.hxx"
 
+#include "GEOMUtils.hxx"
+
 #include "GEOMAlgo_ClsfBox.hxx"
 #include "GEOMAlgo_ClsfSolid.hxx"
 #include "GEOMAlgo_CoupleOfShapes.hxx"
@@ -61,9 +63,9 @@
 
 #include <Basics_OCCTVersion.hxx>
 
-#include "utilities.h"
-#include "OpUtil.hxx"
-#include "Utils_ExceptHandlers.hxx"
+#include <utilities.h>
+#include <OpUtil.hxx>
+#include <Utils_ExceptHandlers.hxx>
 
 #include <TFunction_DriverTable.hxx>
 #include <TFunction_Driver.hxx>
 #include <BRepClass3d_SolidClassifier.hxx>
 #include <Precision.hxx>
 
-#define STD_SORT_ALGO 1
-
 //=============================================================================
 /*!
  *   constructor:
@@ -197,9 +197,7 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeEdge
 
   //Compute the Edge value
   try {
-#if OCC_VERSION_LARGE > 0x06010000
     OCC_CATCH_SIGNALS;
-#endif
     if (!GetSolver()->ComputeFunction(aFunction)) {
       SetErrorCode("Vector driver failed");
       return NULL;
@@ -258,9 +256,7 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeEdgeOnCurveByLength
 
   //Compute the Edge value
   try {
-#if OCC_VERSION_LARGE > 0x06010000
     OCC_CATCH_SIGNALS;
-#endif
     if (!GetSolver()->ComputeFunction(aFunction)) {
       SetErrorCode("Vector driver failed");
       return NULL;
@@ -316,9 +312,7 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeEdgeWire
 
   //Compute the Edge value
   try {
-#if OCC_VERSION_LARGE > 0x06010000
     OCC_CATCH_SIGNALS;
-#endif
     if (!GetSolver()->ComputeFunction(aFunction)) {
       SetErrorCode("Shape driver failed");
       return NULL;
@@ -392,9 +386,7 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeWire
 
   //Compute the shape
   try {
-#if OCC_VERSION_LARGE > 0x06010000
     OCC_CATCH_SIGNALS;
-#endif
     if (!GetSolver()->ComputeFunction(aFunction)) {
       SetErrorCode("Shape driver failed");
       return NULL;
@@ -459,9 +451,7 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeFace (Handle(GEOM_Object) th
   //Compute the Face value
   Standard_Boolean isWarning = Standard_False;
   try {
-#if OCC_VERSION_LARGE > 0x06010000
     OCC_CATCH_SIGNALS;
-#endif
     if (!GetSolver()->ComputeFunction(aFunction)) {
       SetErrorCode("Shape driver failed to compute a face");
       return NULL;
@@ -530,9 +520,7 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeFaceWires
   //Compute the shape
   Standard_Boolean isWarning = Standard_False;
   try {
-#if OCC_VERSION_LARGE > 0x06010000
     OCC_CATCH_SIGNALS;
-#endif
     if (!GetSolver()->ComputeFunction(aFunction)) {
       SetErrorCode("Shape driver failed");
       return NULL;
@@ -643,9 +631,7 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeShape
 
   //Compute the shape
   try {
-#if OCC_VERSION_LARGE > 0x06010000
     OCC_CATCH_SIGNALS;
-#endif
     if (!GetSolver()->ComputeFunction(aFunction)) {
       SetErrorCode("Shape driver failed");
       return NULL;
@@ -712,9 +698,7 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeGlueFaces
   //Compute the sub-shape value
   Standard_Boolean isWarning = Standard_False;
   try {
-#if OCC_VERSION_LARGE > 0x06010000
     OCC_CATCH_SIGNALS;
-#endif
     if (!GetSolver()->ComputeFunction(aFunction)) {
       SetErrorCode("Shape driver failed to glue faces");
       return NULL;
@@ -869,9 +853,7 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeGlueFacesByList
   //Compute the sub-shape value
   Standard_Boolean isWarning = Standard_False;
   try {
-#if OCC_VERSION_LARGE > 0x06010000
     OCC_CATCH_SIGNALS;
-#endif
     if (!GetSolver()->ComputeFunction(aFunction)) {
       SetErrorCode("Shape driver failed to glue faces");
       return NULL;
@@ -944,9 +926,7 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeGlueEdges
   //Compute the sub-shape value
   Standard_Boolean isWarning = Standard_False;
   try {
-#if OCC_VERSION_LARGE > 0x06010000
     OCC_CATCH_SIGNALS;
-#endif
     if (!GetSolver()->ComputeFunction(aFunction)) {
       SetErrorCode("Shape driver failed to glue edges");
       return NULL;
@@ -1023,7 +1003,7 @@ Handle(TColStd_HSequenceOfTransient) GEOMImpl_IShapesOperations::GetGlueShapes
   }
 
   // for stable order of returned entities
-  GEOMImpl_IShapesOperations::SortShapes(listOnePerSet, Standard_False);
+  GEOMUtils::SortShapes(listOnePerSet, Standard_False);
 
   TopTools_ListIteratorOfListOfShape aListIt (listOnePerSet);
   for (; aListIt.More(); aListIt.Next()) {
@@ -1107,9 +1087,7 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeGlueEdgesByList
   //Compute the sub-shape value
   Standard_Boolean isWarning = Standard_False;
   try {
-#if OCC_VERSION_LARGE > 0x06010000
     OCC_CATCH_SIGNALS;
-#endif
     if (!GetSolver()->ComputeFunction(aFunction)) {
       SetErrorCode("Shape driver failed to glue edges");
       return NULL;
@@ -1151,9 +1129,38 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::MakeGlueEdgesByList
  *  GetExistingSubObjects
  */
 //=============================================================================
-Handle(TColStd_HSequenceOfTransient) GEOMImpl_IShapesOperations::GetExistingSubObjects
-                                          (Handle(GEOM_Object)    theShape,
-                                           const Standard_Boolean theGroupsOnly)
+Handle(TColStd_HSequenceOfTransient)
+GEOMImpl_IShapesOperations::GetExistingSubObjects(Handle(GEOM_Object)    theShape,
+                                                 const Standard_Boolean theGroupsOnly)
+{
+  // note: this method does not return fields
+
+  Standard_Integer types = theGroupsOnly ? Groups : Groups|SubShapes;
+  Handle(TColStd_HSequenceOfTransient) results = GetExistingSubObjects(theShape, types);
+
+  if (results->Length() > 0) {
+    //Make a Python command
+    TCollection_AsciiString anAsciiList;
+    for (int i = 1; i <= results->Length(); i++)
+    {
+      Handle(GEOM_BaseObject) obj = Handle(GEOM_BaseObject)::DownCast( results->Value(i));
+      obj->GetEntryString();
+      if ( i < results->Length() )
+       anAsciiList += ",";
+    }
+    
+    GEOM::TPythonDump pd (theShape->GetLastFunction(), /*append=*/true);
+    pd << "[" << anAsciiList.ToCString();
+    pd << "] = geompy.GetExistingSubObjects(";
+    pd << theShape << ", " << (bool)theGroupsOnly << ")";
+  }
+
+  return results;
+}
+
+Handle(TColStd_HSequenceOfTransient)
+GEOMImpl_IShapesOperations::GetExistingSubObjects(Handle(GEOM_Object)    theShape,
+                                                 const Standard_Integer theTypes)
 {
   SetErrorCode(KO);
 
@@ -1171,22 +1178,21 @@ Handle(TColStd_HSequenceOfTransient) GEOMImpl_IShapesOperations::GetExistingSubO
 
   SetErrorCode(KO);
 
-  TCollection_AsciiString anAsciiList;
-
   TDataStd_ListIteratorOfListOfExtendedString anIt (aListEntries);
   for (; anIt.More(); anIt.Next()) {
     TCollection_ExtendedString anEntry = anIt.Value();
     Standard_Integer aStrLen = anEntry.LengthOfCString();
-    char* anEntryStr = new char[aStrLen];
+    char* anEntryStr = new char[aStrLen+1];
     anEntry.ToUTF8CString(anEntryStr);
-    Handle(GEOM_Object) anObj = GetEngine()->GetObject(GetDocID(), anEntryStr, false);
-    if (!anObj.IsNull()) {
-      if (!theGroupsOnly || anObj->GetType() == GEOM_GROUP) {
+    Handle(GEOM_BaseObject) anObj = GetEngine()->GetObject(GetDocID(), anEntryStr, false);
+    if (!anObj.IsNull() ) {
+      bool isGroup    = anObj->IsKind(STANDARD_TYPE(GEOM_Object)) && anObj->GetType() == GEOM_GROUP;
+      bool isSubShape = anObj->IsKind(STANDARD_TYPE(GEOM_Object)) && anObj->GetType() != GEOM_GROUP;
+      bool isField    = anObj->IsKind(STANDARD_TYPE(GEOM_Field));
+      if (theTypes & Groups    && isGroup ||
+         theTypes & SubShapes && isSubShape ||
+         theTypes & Fields    && isField) {
         aSeq->Append(anObj);
-
-        // for python command
-        anAsciiList += anEntryStr;
-        anAsciiList += ",";
       }
     }
     delete [] anEntryStr;
@@ -1197,14 +1203,6 @@ Handle(TColStd_HSequenceOfTransient) GEOMImpl_IShapesOperations::GetExistingSubO
     return aSeq;
   }
 
-  //Make a Python command
-  anAsciiList.Trunc(anAsciiList.Length() - 1);
-
-  GEOM::TPythonDump pd (aMainShape, /*append=*/true);
-  pd << "[" << anAsciiList.ToCString();
-  pd << "] = geompy.GetExistingSubObjects(";
-  pd << theShape << ", " << (bool)theGroupsOnly << ")";
-
   SetErrorCode(OK);
 
   return aSeq;
@@ -1267,7 +1265,7 @@ Handle(TColStd_HSequenceOfTransient) GEOMImpl_IShapesOperations::MakeExplode
     bool isOldSorting = false;
     if (theExplodeType == EXPLODE_OLD_INCLUDE_MAIN)
       isOldSorting = true;
-    SortShapes(listShape, isOldSorting);
+    GEOMUtils::SortShapes(listShape, isOldSorting);
   }
 
   TopTools_IndexedMapOfShape anIndices;
@@ -1391,7 +1389,7 @@ Handle(TColStd_HSequenceOfInteger) GEOMImpl_IShapesOperations::SubShapeAllIDs
     bool isOldSorting = false;
     if (theExplodeType == EXPLODE_OLD_INCLUDE_MAIN)
       isOldSorting = true;
-    SortShapes(listShape, isOldSorting);
+    GEOMUtils::SortShapes(listShape, isOldSorting);
   }
 
   TopTools_IndexedMapOfShape anIndices;
@@ -1558,14 +1556,62 @@ Standard_Integer GEOMImpl_IShapesOperations::GetSubShapeIndex (Handle(GEOM_Objec
 
   TopTools_IndexedMapOfShape anIndices;
   TopExp::MapShapes(aMainShape, anIndices);
-  if (anIndices.Contains(aSubShape)) {
+//   if (anIndices.Contains(aSubShape)) {
+//     SetErrorCode(OK);
+//     return anIndices.FindIndex(aSubShape);
+//   }
+  int id = anIndices.FindIndex(aSubShape);
+  if (id > 0)
+  {
     SetErrorCode(OK);
-    return anIndices.FindIndex(aSubShape);
+    return id;
   }
-
   return -1;
 }
 
+
+
+//=============================================================================
+/*!
+ *  GetSubShapeIndices
+ */
+//=============================================================================
+Handle(TColStd_HSequenceOfInteger) GEOMImpl_IShapesOperations::GetSubShapesIndices (Handle(GEOM_Object) theMainShape,
+                                                                                    std::list<Handle(GEOM_Object)> theSubShapes)
+{
+  MESSAGE("GEOMImpl_IShapesOperations::GetSubShapesIndices")
+  SetErrorCode(KO);
+  
+  Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
+  
+  TopoDS_Shape aMainShape = theMainShape->GetValue();
+  if (aMainShape.IsNull())
+  {
+    MESSAGE("NULL main shape")
+    return NULL;
+  }
+  
+  TopTools_IndexedMapOfShape anIndices;
+  TopExp::MapShapes(aMainShape, anIndices);
+  
+  std::list<Handle(GEOM_Object)>::iterator it;
+  for (it=theSubShapes.begin(); it != theSubShapes.end(); ++it)
+  {
+    TopoDS_Shape aSubShape = (*it)->GetValue(); 
+    if (aSubShape.IsNull())
+    {
+      MESSAGE("NULL subshape")
+      return NULL;
+    }
+    int id = anIndices.FindIndex(aSubShape);
+    aSeq->Append(id);
+  }  
+  
+  SetErrorCode(OK);
+  return aSeq;
+}
+
+
 //=============================================================================
 /*!
  *  GetTopologyIndex
@@ -1739,9 +1785,7 @@ Standard_Integer GEOMImpl_IShapesOperations::NumberOfSubShapes
   */
 
   try {
-#if OCC_VERSION_LARGE > 0x06010000
     OCC_CATCH_SIGNALS;
-#endif
     int iType, nbTypes [TopAbs_SHAPE];
     for (iType = 0; iType < TopAbs_SHAPE; ++iType)
       nbTypes[iType] = 0;
@@ -1811,9 +1855,7 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::ReverseShape(Handle(GEOM_Object)
 
   //Compute the sub-shape value
   try {
-#if OCC_VERSION_LARGE > 0x06010000
     OCC_CATCH_SIGNALS;
-#endif
     if (!GetSolver()->ComputeFunction(aFunction)) {
       SetErrorCode("Shape driver failed to reverse shape");
       return NULL;
@@ -2091,22 +2133,22 @@ static GEOM::TPythonDump& operator<< (GEOM::TPythonDump&   theDump,
 {
   switch (theState) {
   case GEOMAlgo_ST_IN:
-    theDump << "geompy.GEOM.ST_IN";
+    theDump << "GEOM.ST_IN";
     break;
   case GEOMAlgo_ST_OUT:
-    theDump << "geompy.GEOM.ST_OUT";
+    theDump << "GEOM.ST_OUT";
     break;
   case GEOMAlgo_ST_ON:
-    theDump << "geompy.GEOM.ST_ON";
+    theDump << "GEOM.ST_ON";
     break;
   case GEOMAlgo_ST_ONIN:
-    theDump << "geompy.GEOM.ST_ONIN";
+    theDump << "GEOM.ST_ONIN";
     break;
   case GEOMAlgo_ST_ONOUT:
-    theDump << "geompy.GEOM.ST_ONOUT";
+    theDump << "GEOM.ST_ONOUT";
     break;
   default:
-    theDump << "geompy.GEOM.ST_UNKNOWN";
+    theDump << "GEOM.ST_UNKNOWN";
     break;
   }
   return theDump;
@@ -2217,7 +2259,7 @@ Handle(TColStd_HSequenceOfInteger)
   TopoDS_Shape aShape = theShape->GetValue();
 
   // Check presence of triangulation, build if need
-  if (!CheckTriangulation(aShape)) {
+  if (!GEOMUtils::CheckTriangulation(aShape)) {
     SetErrorCode("Cannot build triangulation on the shape");
     return aSeqOfIDs;
   }
@@ -2302,7 +2344,7 @@ Handle(TColStd_HSequenceOfInteger)
   Handle(GEOM_Function) aFunction = GEOM::GetCreatedLast(theShape,theBox)->GetLastFunction();
 
   // Make a Python command
-  GEOM::TPythonDump(aFunction)
+  GEOM::TPythonDump(aFunction, /*append=*/true)
     << "listShapesOnBoxIDs = geompy.GetShapesOnBoxIDs("
     << theBox << ", "
     << theShape << ", "
@@ -2384,7 +2426,7 @@ Handle(TColStd_HSequenceOfInteger)
   TopTools_ListOfShape res;
 
   // Check presence of triangulation, build if need
-  if (!CheckTriangulation(aShape)) {
+  if (!GEOMUtils::CheckTriangulation(aShape)) {
     SetErrorCode("Cannot build triangulation on the shape");
     return aSeqOfIDs;
   }
@@ -2475,7 +2517,7 @@ Handle(TColStd_HSequenceOfInteger)
     GEOM::GetCreatedLast(theShape,theCheckShape)->GetLastFunction();
 
   // Make a Python command
-  GEOM::TPythonDump(aFunction)
+  GEOM::TPythonDump(aFunction, /*append=*/true)
     << "listShapesOnBoxIDs = geompy.GetShapesOnShapeIDs("
     << theCheckShape << ", "
     << theShape << ", "
@@ -2572,6 +2614,15 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::GetShapesOnShapeAsCompound
     aRes->AddFunction(GEOMImpl_ShapeDriver::GetID(), SHAPES_ON_SHAPE);
   aFunction->SetValue(aCompound);
 
+  aSeq->Clear();
+  aSeq->Append( theCheckShape->GetLastFunction() );
+  aSeq->Append( theShape->GetLastFunction() );
+
+  GEOMImpl_IShapes aCI( aFunction );
+  aCI.SetShapes( aSeq );
+  aCI.SetSubShapeType( theShapeType );
+  aCI.SetTolerance( theState );
+
   GEOM::TPythonDump(aFunction)
     << aRes << " = geompy.GetShapesOnShapeAsCompound("
     << theCheckShape << ", "
@@ -2604,7 +2655,7 @@ Handle(TColStd_HSequenceOfInteger)
   Handle(TColStd_HSequenceOfInteger) aSeqOfIDs;
 
   // Check presence of triangulation, build if need
-  if (!CheckTriangulation(theShape)) {
+  if (!GEOMUtils::CheckTriangulation(theShape)) {
     SetErrorCode("Cannot build triangulation on the shape");
     return aSeqOfIDs;
   }
@@ -2613,9 +2664,7 @@ Handle(TColStd_HSequenceOfInteger)
   // Compute tolerance
   Standard_Real T, VertMax = -RealLast();
   try {
-#if OCC_VERSION_LARGE > 0x06010000
     OCC_CATCH_SIGNALS;
-#endif
     for (TopExp_Explorer ExV (theShape, TopAbs_VERTEX); ExV.More(); ExV.Next()) {
       TopoDS_Vertex Vertex = TopoDS::Vertex(ExV.Current());
       T = BRep_Tool::Tolerance(Vertex);
@@ -3321,7 +3370,7 @@ Handle(TColStd_HSequenceOfInteger) GEOMImpl_IShapesOperations::GetShapesOnSphere
 
   // Make a Python command
   GEOM::TPythonDump(aFunction, /*append=*/true)
-    << "listShapesOnCylinder = geompy.GetShapesOnCylinderIDs"
+    << "listShapesOnCylinder = geompy.GetShapesOnSphereIDs"
     << "(" << theShape << ", " << aShapeType << ", " << theCenter << ", "
     << theRadius << ", " << theState << ")";
 
@@ -3385,7 +3434,7 @@ Handle(TColStd_HSequenceOfInteger)
   Handle(TColStd_HSequenceOfInteger) aSeqOfIDs;
 
   // Check presence of triangulation, build if need
-  if (!CheckTriangulation(aShape)) {
+  if (!GEOMUtils::CheckTriangulation(aShape)) {
     SetErrorCode("Cannot build triangulation on the shape");
     return aSeqOfIDs;
   }
@@ -3776,28 +3825,6 @@ namespace {
   }
 }
 
-//================================================================================
-/*!
- * \brief Return type of shape for explode. In case of compound it will be a type of sub-shape.
- */
-//================================================================================
-TopAbs_ShapeEnum GEOMImpl_IShapesOperations::GetTypeOfSimplePart (const TopoDS_Shape& theShape)
-{
-  TopAbs_ShapeEnum aType = theShape.ShapeType();
-  if      (aType == TopAbs_VERTEX)                             return TopAbs_VERTEX;
-  else if (aType == TopAbs_EDGE  || aType == TopAbs_WIRE)      return TopAbs_EDGE;
-  else if (aType == TopAbs_FACE  || aType == TopAbs_SHELL)     return TopAbs_FACE;
-  else if (aType == TopAbs_SOLID || aType == TopAbs_COMPSOLID) return TopAbs_SOLID;
-  else if (aType == TopAbs_COMPOUND) {
-    // Only the iType of the first shape in the compound is taken into account
-    TopoDS_Iterator It (theShape, Standard_False, Standard_False);
-    if (It.More()) {
-      return GetTypeOfSimplePart(It.Value());
-    }
-  }
-  return TopAbs_SHAPE;
-}
-
 //=============================================================================
 /*!
  *  case GetInPlace:
@@ -3813,87 +3840,46 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::GetInPlace (Handle(GEOM_Object)
 
   TopoDS_Shape aWhere = theShapeWhere->GetValue();
   TopoDS_Shape aWhat  = theShapeWhat->GetValue();
-  TopoDS_Shape aPntShape;
-  TopoDS_Vertex aVertex;
 
   if (aWhere.IsNull() || aWhat.IsNull()) {
     SetErrorCode("Error: aWhere and aWhat TopoDS_Shape are Null.");
     return NULL;
   }
 
-  Handle(GEOM_Function) aWhereFunction = theShapeWhere->GetLastFunction();
-  if (aWhereFunction.IsNull()) {
-    SetErrorCode("Error: aWhereFunction is Null.");
-    return NULL;
-  }
+  // Compute confusion tolerance.
+  Standard_Real    aTolConf = Precision::Confusion();
+  Standard_Integer i;
 
-  TopTools_IndexedMapOfShape aWhereIndices;
-  TopExp::MapShapes(aWhere, aWhereIndices);
+  for (i = 0; i < 2; ++i) {
+    TopExp_Explorer anExp(i == 0 ? aWhere : aWhat, TopAbs_VERTEX);
 
-  TopAbs_ShapeEnum iType = TopAbs_SOLID;
-  Standard_Real    dl_l = 1e-3;
-  Standard_Real    min_l, Tol_0D, Tol_1D, Tol_2D, Tol_3D, Tol_Mass;
-  Standard_Real    aXmin, aYmin, aZmin, aXmax, aYmax, aZmax;
-  Bnd_Box          BoundingBox;
-  gp_Pnt           aPnt, aPnt_aWhat, tab_Pnt[2];
-  GProp_GProps     aProps;
-
-  // Find the iType of the aWhat shape
-  iType = GetTypeOfSimplePart(aWhat);
-  if (iType == TopAbs_SHAPE) {
-    SetErrorCode("Error: An attempt to extract a shape of not supported type.");
-    return NULL;
-  }
-
-  TopExp_Explorer Exp_aWhat  ( aWhat,  iType );
-  TopExp_Explorer Exp_aWhere ( aWhere, iType );
-  TopExp_Explorer Exp_Edge   ( aWhere, TopAbs_EDGE );
+    for (; anExp.More(); anExp.Next()) {
+      const TopoDS_Vertex aVtx = TopoDS::Vertex(anExp.Current());
+      const Standard_Real aTolVtx = BRep_Tool::Tolerance(aVtx);
 
-  // Find the shortest edge in theShapeWhere shape
-  BRepBndLib::Add(aWhere, BoundingBox);
-  BoundingBox.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
-  min_l = fabs(aXmax - aXmin);
-  if( min_l < fabs(aYmax - aYmin) ) min_l = fabs(aYmax - aYmin);
-  if( min_l < fabs(aZmax - aZmin) ) min_l = fabs(aZmax - aZmin);
-  min_l /= dl_l;
-  // Mantis issue 0020908 BEGIN
-  if (!Exp_Edge.More()) {
-    min_l = Precision::Confusion();
-  }
-  // Mantis issue 0020908 END
-  for ( Standard_Integer nbEdge = 0; Exp_Edge.More(); Exp_Edge.Next(), nbEdge++ ) {
-    TopExp_Explorer Exp_Vertex( Exp_Edge.Current(), TopAbs_VERTEX);
-    for ( Standard_Integer nbVertex = 0; Exp_Vertex.More(); Exp_Vertex.Next(), nbVertex++ ) {
-      aPnt = BRep_Tool::Pnt( TopoDS::Vertex( Exp_Vertex.Current() ) );
-      tab_Pnt[nbVertex] = aPnt;
-    }
-    if ( ! tab_Pnt[0].IsEqual(tab_Pnt[1], dl_l) ) {
-      BRepGProp::LinearProperties(Exp_Edge.Current(), aProps);
-      if ( aProps.Mass() < min_l ) min_l = aProps.Mass();
+      if (aTolVtx > aTolConf) {
+        aTolConf = aTolVtx;
+      }
     }
   }
 
-  // Compute tolerances
-  Tol_0D = dl_l;
-  Tol_1D = dl_l * min_l;
-  Tol_2D = dl_l * ( min_l * min_l) * ( 2. + dl_l);
-  Tol_3D = dl_l * ( min_l * min_l * min_l ) * ( 3. + (3 * dl_l) + (dl_l * dl_l) );
-
-  if (Tol_0D < Precision::Confusion()) Tol_0D = Precision::Confusion();
-  if (Tol_1D < Precision::Confusion()) Tol_1D = Precision::Confusion();
-  if (Tol_2D < Precision::Confusion()) Tol_2D = Precision::Confusion();
-  if (Tol_3D < Precision::Confusion()) Tol_3D = Precision::Confusion();
+  // Compute mass tolerance.
+  Bnd_Box       aBoundingBox;
+  Standard_Real aXmin, aYmin, aZmin, aXmax, aYmax, aZmax;
+  Standard_Real aMassTol;
 
-  Tol_Mass = Tol_3D;
-  if ( iType == TopAbs_VERTEX )    Tol_Mass = Tol_0D;
-  else if ( iType == TopAbs_EDGE ) Tol_Mass = Tol_1D;
-  else if ( iType == TopAbs_FACE ) Tol_Mass = Tol_2D;
+  BRepBndLib::Add(aWhere, aBoundingBox);
+  BRepBndLib::Add(aWhat,  aBoundingBox);
+  aBoundingBox.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
+  aMassTol = Max(aXmax - aXmin, aYmax - aYmin);
+  aMassTol = Max(aMassTol, aZmax - aZmin);
+  aMassTol *= aTolConf;
 
   // Searching for the sub-shapes inside the ShapeWhere shape
   GEOMAlgo_GetInPlace aGIP;
-  aGIP.SetTolerance(Tol_1D);
-  aGIP.SetTolMass(Tol_Mass);
-  aGIP.SetTolCG(Tol_1D);
+  aGIP.SetTolerance(aTolConf);
+  aGIP.SetTolMass(aMassTol);
+  aGIP.SetTolCG(aTolConf);
 
   aGIP.SetArgument(aWhat);
   aGIP.SetShapeWhere(aWhere);
@@ -3905,24 +3891,26 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::GetInPlace (Handle(GEOM_Object)
     return NULL;
   }
 
-  // aGIP.IsFound() returns true only when the whole theShapeWhat
-  // is found (as one shape or several parts). But we are also interested
-  // in the partial result, that is why this check is commented.
-  //if (!aGIP.IsFound()) {
-  //  SetErrorCode(NOT_FOUND_ANY);
-  //  return NULL;
-  //}
+  // Add direct result.
+  TopTools_ListOfShape        aLSA;
+  const TopoDS_Shape         &aShapeResult = aGIP.Result();
+  TopTools_MapOfShape         aMFence;
+  TopTools_IndexedMapOfShape  aWhereIndices;
 
-  const TopTools_DataMapOfShapeListOfShape& aDMSLS = aGIP.Images();
-  if (!aDMSLS.IsBound(aWhat)) {
-    SetErrorCode(NOT_FOUND_ANY);
-    return NULL;
+  TopExp::MapShapes(aWhere, aWhereIndices);
+
+  if (aShapeResult.IsNull() == Standard_False) {
+    TopoDS_Iterator anIt(aShapeResult);
+
+    for (; anIt.More(); anIt.Next()) {
+      const TopoDS_Shape &aPart = anIt.Value();
+
+      if(aWhereIndices.Contains(aPart) && aMFence.Add(aPart)) {
+        aLSA.Append(aPart);
+      }
+    }
   }
 
-  // the list of shapes aLSA contains the shapes
-  // of the Shape For Search that corresponds
-  // to the Argument aWhat
-  const TopTools_ListOfShape& aLSA = aDMSLS.Find(aWhat);
   if (aLSA.Extent() == 0) {
     SetErrorCode(NOT_FOUND_ANY); // Not found any Results
     return NULL;
@@ -4041,7 +4029,7 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::GetInPlaceOld (Handle(GEOM_Objec
     return NULL;
   }
   */
-  iType = GetTypeOfSimplePart(aWhat);
+  iType = GEOMUtils::GetTypeOfSimplePart(aWhat);
   if (iType == TopAbs_SHAPE) {
     SetErrorCode("Error: An attempt to extract a shape of not supported type.");
     return NULL;
@@ -4230,13 +4218,40 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::GetInPlaceByHistory
     return NULL;
   }
 
-  Handle(TColStd_HArray1OfInteger) aModifiedArray =
-    new TColStd_HArray1OfInteger (1, aModifiedList.Extent());
+  Standard_Integer nbFound = aModifiedList.Extent();
   TColStd_ListIteratorOfListOfInteger anIterModif (aModifiedList);
-  for (Standard_Integer imod = 1; anIterModif.More(); anIterModif.Next(), imod++) {
-    aModifiedArray->SetValue(imod, anIterModif.Value());
+  if ( nbFound > 1 )
+  {
+    // remove sub-shapes inappropriate for group creation
+    TopAbs_ShapeEnum subType = TopAbs_SHAPE;
+    while ( anIterModif.More() ) {
+      TopAbs_ShapeEnum type = aWhereIndices( anIterModif.Value() ).ShapeType();
+      bool okForGroup = ( type == TopAbs_VERTEX || type == TopAbs_EDGE ||
+                          type == TopAbs_FACE   || type == TopAbs_SOLID );
+      if ( okForGroup ) {
+        if ( subType == TopAbs_SHAPE )
+          subType = type;
+        else
+          okForGroup = ( subType == type );
+      }
+      if ( okForGroup )
+        anIterModif.Next();
+      else
+        aModifiedList.Remove( anIterModif );
+      nbFound -= ( !okForGroup );
+    }
+    if ( nbFound == 0 ) {
+      SetErrorCode("Error: result found but it's type is inappropriate for group creation.");
+      return NULL;
+    }
   }
 
+  Handle(TColStd_HArray1OfInteger) aModifiedArray =
+    new TColStd_HArray1OfInteger( 1, nbFound );
+  anIterModif.Initialize(aModifiedList);
+  for (Standard_Integer imod = 1; anIterModif.More(); anIterModif.Next(), imod++)
+    aModifiedArray->SetValue(imod, anIterModif.Value());
+
   //Add a new object
   Handle(GEOM_Object) aResult = GetEngine()->AddSubShape(theShapeWhere, aModifiedArray);
   if (aResult.IsNull()) {
@@ -4260,327 +4275,12 @@ Handle(GEOM_Object) GEOMImpl_IShapesOperations::GetInPlaceByHistory
   Handle(GEOM_Function) aFunction = aResult->GetFunction(1);
 
   GEOM::TPythonDump(aFunction) << aResult << " = geompy.GetInPlaceByHistory("
-    << theShapeWhere << ", " << theShapeWhat << ")";
+                               << theShapeWhere << ", " << theShapeWhat << ")";
 
   SetErrorCode(OK);
   return aResult;
 }
 
-//=======================================================================
-//function : ShapeToDouble
-//purpose  : used by CompareShapes::operator()
-//=======================================================================
-std::pair<double, double> ShapeToDouble (const TopoDS_Shape& S, bool isOldSorting)
-{
-  // Computing of CentreOfMass
-  gp_Pnt GPoint;
-  double Len;
-
-  if (S.ShapeType() == TopAbs_VERTEX) {
-    GPoint = BRep_Tool::Pnt(TopoDS::Vertex(S));
-    Len = (double)S.Orientation();
-  }
-  else {
-    GProp_GProps GPr;
-    // BEGIN: fix for Mantis issue 0020842
-    if (isOldSorting) {
-      BRepGProp::LinearProperties(S, GPr);
-    }
-    else {
-      if (S.ShapeType() == TopAbs_EDGE || S.ShapeType() == TopAbs_WIRE) {
-        BRepGProp::LinearProperties(S, GPr);
-      }
-      else if (S.ShapeType() == TopAbs_FACE || S.ShapeType() == TopAbs_SHELL) {
-        BRepGProp::SurfaceProperties(S, GPr);
-      }
-      else {
-        BRepGProp::VolumeProperties(S, GPr);
-      }
-    }
-    // END: fix for Mantis issue 0020842
-    GPoint = GPr.CentreOfMass();
-    Len = GPr.Mass();
-  }
-
-  double dMidXYZ = GPoint.X() * 999.0 + GPoint.Y() * 99.0 + GPoint.Z() * 0.9;
-  return std::make_pair(dMidXYZ, Len);
-}
-
-//=======================================================================
-//function : CompareShapes::operator()
-//purpose  : used by std::sort(), called from SortShapes()
-//=======================================================================
-bool GEOMImpl_IShapesOperations::CompareShapes::operator()(const TopoDS_Shape& theShape1,
-                                                           const TopoDS_Shape& theShape2)
-{
-  if (!myMap.IsBound(theShape1)) {
-    myMap.Bind(theShape1, ShapeToDouble(theShape1, myIsOldSorting));
-  }
-
-  if (!myMap.IsBound(theShape2)) {
-    myMap.Bind(theShape2, ShapeToDouble(theShape2, myIsOldSorting));
-  }
-
-  std::pair<double, double> val1 = myMap.Find(theShape1);
-  std::pair<double, double> val2 = myMap.Find(theShape2);
-
-  double tol = Precision::Confusion();
-  bool exchange = Standard_False;
-
-  double dMidXYZ = val1.first - val2.first;
-  if (dMidXYZ >= tol) {
-    exchange = Standard_True;
-  }
-  else if (Abs(dMidXYZ) < tol) {
-    double dLength = val1.second - val2.second;
-    if (dLength >= tol) {
-      exchange = Standard_True;
-    }
-    else if (Abs(dLength) < tol && theShape1.ShapeType() <= TopAbs_FACE) {
-      // PAL17233
-      // equal values possible on shapes such as two halves of a sphere and
-      // a membrane inside the sphere
-      Bnd_Box box1,box2;
-      BRepBndLib::Add(theShape1, box1);
-      if (!box1.IsVoid()) {
-        BRepBndLib::Add(theShape2, box2);
-        Standard_Real dSquareExtent = box1.SquareExtent() - box2.SquareExtent();
-        if (dSquareExtent >= tol) {
-          exchange = Standard_True;
-        }
-        else if (Abs(dSquareExtent) < tol) {
-          Standard_Real aXmin, aYmin, aZmin, aXmax, aYmax, aZmax, val1, val2;
-          box1.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
-          val1 = (aXmin+aXmax)*999.0 + (aYmin+aYmax)*99.0 + (aZmin+aZmax)*0.9;
-          box2.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
-          val2 = (aXmin+aXmax)*999.0 + (aYmin+aYmax)*99.0 + (aZmin+aZmax)*0.9;
-          if ((val1 - val2) >= tol) {
-            exchange = Standard_True;
-          }
-        }
-      }
-    }
-  }
-
-  //return val1 < val2;
-  return !exchange;
-}
-
-//=======================================================================
-//function : SortShapes
-//purpose  :
-//=======================================================================
-void GEOMImpl_IShapesOperations::SortShapes(TopTools_ListOfShape& SL,
-                                            const Standard_Boolean isOldSorting)
-{
-#ifdef STD_SORT_ALGO
-  std::vector<TopoDS_Shape> aShapesVec;
-  aShapesVec.reserve(SL.Extent());
-
-  TopTools_ListIteratorOfListOfShape it (SL);
-  for (; it.More(); it.Next()) {
-    aShapesVec.push_back(it.Value());
-  }
-  SL.Clear();
-
-  CompareShapes shComp (isOldSorting);
-  std::stable_sort(aShapesVec.begin(), aShapesVec.end(), shComp);
-  //std::sort(aShapesVec.begin(), aShapesVec.end(), shComp);
-
-  std::vector<TopoDS_Shape>::const_iterator anIter = aShapesVec.begin();
-  for (; anIter != aShapesVec.end(); ++anIter) {
-    SL.Append(*anIter);
-  }
-#else
-  // old implementation
-  Standard_Integer MaxShapes = SL.Extent();
-  TopTools_Array1OfShape  aShapes (1,MaxShapes);
-  TColStd_Array1OfInteger OrderInd(1,MaxShapes);
-  TColStd_Array1OfReal    MidXYZ  (1,MaxShapes); //X,Y,Z;
-  TColStd_Array1OfReal    Length  (1,MaxShapes); //X,Y,Z;
-
-  // Computing of CentreOfMass
-  Standard_Integer Index;
-  GProp_GProps GPr;
-  gp_Pnt GPoint;
-  TopTools_ListIteratorOfListOfShape it(SL);
-  for (Index=1;  it.More();  Index++)
-  {
-    TopoDS_Shape S = it.Value();
-    SL.Remove( it ); // == it.Next()
-    aShapes(Index) = S;
-    OrderInd.SetValue (Index, Index);
-    if (S.ShapeType() == TopAbs_VERTEX) {
-      GPoint = BRep_Tool::Pnt( TopoDS::Vertex( S ));
-      Length.SetValue( Index, (Standard_Real) S.Orientation());
-    }
-    else {
-      // BEGIN: fix for Mantis issue 0020842
-      if (isOldSorting) {
-        BRepGProp::LinearProperties (S, GPr);
-      }
-      else {
-        if (S.ShapeType() == TopAbs_EDGE || S.ShapeType() == TopAbs_WIRE) {
-          BRepGProp::LinearProperties (S, GPr);
-        }
-        else if (S.ShapeType() == TopAbs_FACE || S.ShapeType() == TopAbs_SHELL) {
-          BRepGProp::SurfaceProperties(S, GPr);
-        }
-        else {
-          BRepGProp::VolumeProperties(S, GPr);
-        }
-      }
-      // END: fix for Mantis issue 0020842
-      GPoint = GPr.CentreOfMass();
-      Length.SetValue(Index, GPr.Mass());
-    }
-    MidXYZ.SetValue(Index, GPoint.X()*999.0 + GPoint.Y()*99.0 + GPoint.Z()*0.9);
-    //cout << Index << " L: " << Length(Index) << "CG: " << MidXYZ(Index) << endl;
-  }
-
-  // Sorting
-  Standard_Integer aTemp;
-  Standard_Boolean exchange, Sort = Standard_True;
-  Standard_Real    tol = Precision::Confusion();
-  while (Sort)
-  {
-    Sort = Standard_False;
-    for (Index=1; Index < MaxShapes; Index++)
-    {
-      exchange = Standard_False;
-      Standard_Real dMidXYZ = MidXYZ(OrderInd(Index)) - MidXYZ(OrderInd(Index+1));
-      Standard_Real dLength = Length(OrderInd(Index)) - Length(OrderInd(Index+1));
-      if ( dMidXYZ >= tol ) {
-//         cout << "MidXYZ: " << MidXYZ(OrderInd(Index))<< " > " <<MidXYZ(OrderInd(Index+1))
-//              << " d: " << dMidXYZ << endl;
-        exchange = Standard_True;
-      }
-      else if ( Abs(dMidXYZ) < tol && dLength >= tol ) {
-//         cout << "Length: " << Length(OrderInd(Index))<< " > " <<Length(OrderInd(Index+1))
-//              << " d: " << dLength << endl;
-        exchange = Standard_True;
-      }
-      else if ( Abs(dMidXYZ) < tol && Abs(dLength) < tol &&
-                aShapes(OrderInd(Index)).ShapeType() <= TopAbs_FACE) {
-        // PAL17233
-        // equal values possible on shapes such as two halves of a sphere and
-        // a membrane inside the sphere
-        Bnd_Box box1,box2;
-        BRepBndLib::Add( aShapes( OrderInd(Index) ), box1 );
-        if ( box1.IsVoid() ) continue;
-        BRepBndLib::Add( aShapes( OrderInd(Index+1) ), box2 );
-        Standard_Real dSquareExtent = box1.SquareExtent() - box2.SquareExtent();
-        if ( dSquareExtent >= tol ) {
-//           cout << "SquareExtent: " << box1.SquareExtent()<<" > "<<box2.SquareExtent() << endl;
-          exchange = Standard_True;
-        }
-        else if ( Abs(dSquareExtent) < tol ) {
-          Standard_Real aXmin, aYmin, aZmin, aXmax, aYmax, aZmax, val1, val2;
-          box1.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
-          val1 = (aXmin+aXmax)*999 + (aYmin+aYmax)*99 + (aZmin+aZmax)*0.9;
-          box2.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
-          val2 = (aXmin+aXmax)*999 + (aYmin+aYmax)*99 + (aZmin+aZmax)*0.9;
-          //exchange = val1 > val2;
-          if ((val1 - val2) >= tol) {
-            exchange = Standard_True;
-          }
-          //cout << "box: " << val1<<" > "<<val2 << endl;
-        }
-      }
-
-      if (exchange)
-      {
-//         cout << "exchange " << Index << " & " << Index+1 << endl;
-        aTemp = OrderInd(Index);
-        OrderInd(Index) = OrderInd(Index+1);
-        OrderInd(Index+1) = aTemp;
-        Sort = Standard_True;
-      }
-    }
-  }
-
-  for (Index=1; Index <= MaxShapes; Index++)
-    SL.Append( aShapes( OrderInd(Index) ));
-#endif
-}
-
-//=======================================================================
-//function : CompsolidToCompound
-//purpose  :
-//=======================================================================
-TopoDS_Shape GEOMImpl_IShapesOperations::CompsolidToCompound (const TopoDS_Shape& theCompsolid)
-{
-  if (theCompsolid.ShapeType() != TopAbs_COMPSOLID) {
-    return theCompsolid;
-  }
-
-  TopoDS_Compound aCompound;
-  BRep_Builder B;
-  B.MakeCompound(aCompound);
-
-  TopTools_MapOfShape mapShape;
-  TopoDS_Iterator It (theCompsolid, Standard_True, Standard_True);
-
-  for (; It.More(); It.Next()) {
-    TopoDS_Shape aShape_i = It.Value();
-    if (mapShape.Add(aShape_i)) {
-      B.Add(aCompound, aShape_i);
-    }
-  }
-
-  return aCompound;
-}
-
-//=======================================================================
-//function : CheckTriangulation
-//purpose  :
-//=======================================================================
-bool GEOMImpl_IShapesOperations::CheckTriangulation (const TopoDS_Shape& aShape)
-{
-  bool isTriangulation = true;
-
-  TopExp_Explorer exp (aShape, TopAbs_FACE);
-  if (exp.More())
-  {
-    TopLoc_Location aTopLoc;
-    Handle(Poly_Triangulation) aTRF;
-    aTRF = BRep_Tool::Triangulation(TopoDS::Face(exp.Current()), aTopLoc);
-    if (aTRF.IsNull()) {
-      isTriangulation = false;
-    }
-  }
-  else // no faces, try edges
-  {
-    TopExp_Explorer expe (aShape, TopAbs_EDGE);
-    if (!expe.More()) {
-      return false;
-    }
-    TopLoc_Location aLoc;
-    Handle(Poly_Polygon3D) aPE = BRep_Tool::Polygon3D(TopoDS::Edge(expe.Current()), aLoc);
-    if (aPE.IsNull()) {
-      isTriangulation = false;
-    }
-  }
-
-  if (!isTriangulation) {
-    // calculate deflection
-    Standard_Real aDeviationCoefficient = 0.001;
-
-    Bnd_Box B;
-    BRepBndLib::Add(aShape, B);
-    Standard_Real aXmin, aYmin, aZmin, aXmax, aYmax, aZmax;
-    B.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
-
-    Standard_Real dx = aXmax - aXmin, dy = aYmax - aYmin, dz = aZmax - aZmin;
-    Standard_Real aDeflection = Max(Max(dx, dy), dz) * aDeviationCoefficient * 4;
-    Standard_Real aHLRAngle = 0.349066;
-
-    BRepMesh_IncrementalMesh Inc (aShape, aDeflection, Standard_False, aHLRAngle);
-  }
-
-  return true;
-}
-
 #define MAX_TOLERANCE 1.e-7
 
 //=======================================================================
@@ -5008,7 +4708,7 @@ Handle(TColStd_HSequenceOfInteger) GEOMImpl_IShapesOperations::GetSameIDs
     Handle(GEOM_Function) aFunction = GEOM::GetCreatedLast(theShapeWhere,theShapeWhat)->GetLastFunction();
 
   // Make a Python command
-  GEOM::TPythonDump(aFunction)
+  GEOM::TPythonDump(aFunction, /*append=*/true)
     << "listSameIDs = geompy.GetSameIDs("
     << theShapeWhere << ", "
     << theShapeWhat << ")";