Salome HOME
Allow some blocks operations on other shapes (get face from a shell).
[modules/geom.git] / src / GEOMImpl / GEOMImpl_IBlocksOperations.cxx
1 // Copyright (C) 2005  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
3 // 
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Lesser General Public
6 // License as published by the Free Software Foundation; either 
7 // version 2.1 of the License.
8 // 
9 // This library is distributed in the hope that it will be useful 
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
12 // Lesser General Public License for more details.
13 //
14 // You should have received a copy of the GNU Lesser General Public  
15 // License along with this library; if not, write to the Free Software 
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 //
18 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 //
20 #ifdef WNT
21 #pragma warning( disable:4786 )
22 #endif
23
24 #include <Standard_Stream.hxx>
25
26 #include <GEOMImpl_IBlocksOperations.hxx>
27
28 #include <GEOMImpl_Types.hxx>
29
30 #include <GEOMImpl_BlockDriver.hxx>
31 #include <GEOMImpl_IBlocks.hxx>
32 #include <GEOMImpl_IBlockTrsf.hxx>
33 #include <GEOMImpl_CopyDriver.hxx>
34 #include <GEOMImpl_Block6Explorer.hxx>
35
36 #include <GEOM_Function.hxx>
37 #include <GEOM_PythonDump.hxx>
38
39 #include <GEOMAlgo_GlueAnalyser.hxx>
40 #include <GEOMAlgo_CoupleOfShapes.hxx>
41 #include <GEOMAlgo_ListOfCoupleOfShapes.hxx>
42 #include <GEOMAlgo_ListIteratorOfListOfCoupleOfShapes.hxx>
43 #include <BlockFix_CheckTool.hxx>
44
45 #include "utilities.h"
46 #include <OpUtil.hxx>
47 #include <Utils_ExceptHandlers.hxx>
48
49 #include <TFunction_DriverTable.hxx>
50 #include <TFunction_Driver.hxx>
51 #include <TFunction_Logbook.hxx>
52 #include <TDataStd_Integer.hxx>
53 #include <TDF_Tool.hxx>
54
55 #include <BRep_Tool.hxx>
56 #include <BRep_Builder.hxx>
57 #include <BRepTools.hxx>
58 #include <BRepTools_WireExplorer.hxx>
59 #include <BRepGProp.hxx>
60 #include <BRepBndLib.hxx>
61 #include <BRepAdaptor_Surface.hxx>
62 #include <BRepClass_FaceClassifier.hxx>
63 #include <BRepClass3d_SolidClassifier.hxx>
64 #include <BRepExtrema_DistShapeShape.hxx>
65
66 #include <TopAbs.hxx>
67 #include <TopoDS.hxx>
68 #include <TopoDS_Edge.hxx>
69 #include <TopoDS_Vertex.hxx>
70 #include <TopoDS_Compound.hxx>
71 #include <TopoDS_Iterator.hxx>
72 #include <TopExp.hxx>
73 #include <TopExp_Explorer.hxx>
74 #include <TopTools_MapOfShape.hxx>
75 #include <TopTools_Array1OfShape.hxx>
76 #include <TopTools_IndexedMapOfShape.hxx>
77 #include <TopTools_DataMapOfShapeInteger.hxx>
78 #include <TopTools_ListIteratorOfListOfShape.hxx>
79 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
80 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
81
82 #include <Bnd_Box.hxx>
83 #include <GProp_GProps.hxx>
84
85 #include <Geom_Surface.hxx>
86 #include <ShapeAnalysis_Surface.hxx>
87
88 #include <TColStd_MapOfInteger.hxx>
89 #include <TColStd_Array1OfReal.hxx>
90 #include <TColStd_Array1OfInteger.hxx>
91 #include <TColStd_Array2OfInteger.hxx>
92
93 //#include <OSD_Timer.hxx>
94
95 #include <Precision.hxx>
96
97 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
98
99 //=============================================================================
100 /*!
101  *   constructor:
102  */
103 //=============================================================================
104 GEOMImpl_IBlocksOperations::GEOMImpl_IBlocksOperations (GEOM_Engine* theEngine, int theDocID)
105 : GEOM_IOperations(theEngine, theDocID)
106 {
107   MESSAGE("GEOMImpl_IBlocksOperations::GEOMImpl_IBlocksOperations");
108 }
109
110 //=============================================================================
111 /*!
112  *  destructor
113  */
114 //=============================================================================
115 GEOMImpl_IBlocksOperations::~GEOMImpl_IBlocksOperations()
116 {
117   MESSAGE("GEOMImpl_IBlocksOperations::~GEOMImpl_IBlocksOperations");
118 }
119
120
121 //=============================================================================
122 /*!
123  *  MakeQuad
124  */
125 //=============================================================================
126 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::MakeQuad
127                      (Handle(GEOM_Object) theEdge1, Handle(GEOM_Object) theEdge2,
128                       Handle(GEOM_Object) theEdge3, Handle(GEOM_Object) theEdge4)
129 {
130   SetErrorCode(KO);
131
132   if (theEdge1.IsNull() || theEdge2.IsNull() ||
133       theEdge3.IsNull() || theEdge4.IsNull()) return NULL;
134
135   //Add a new Face object
136   Handle(GEOM_Object) aFace = GetEngine()->AddObject(GetDocID(), GEOM_FACE);
137
138   //Add a new Face function
139   Handle(GEOM_Function) aFunction =
140     aFace->AddFunction(GEOMImpl_BlockDriver::GetID(), BLOCK_FACE_FOUR_EDGES);
141
142   //Check if the function is set correctly
143   if (aFunction->GetDriverGUID() != GEOMImpl_BlockDriver::GetID()) return NULL;
144
145   GEOMImpl_IBlocks aPI (aFunction);
146
147   Handle(GEOM_Function) aRef1 = theEdge1->GetLastFunction();
148   Handle(GEOM_Function) aRef2 = theEdge2->GetLastFunction();
149   Handle(GEOM_Function) aRef3 = theEdge3->GetLastFunction();
150   Handle(GEOM_Function) aRef4 = theEdge4->GetLastFunction();
151   if (aRef1.IsNull() || aRef2.IsNull() ||
152       aRef3.IsNull() || aRef4.IsNull()) return NULL;
153
154   Handle(TColStd_HSequenceOfTransient) aShapesSeq = new TColStd_HSequenceOfTransient;
155   aShapesSeq->Append(aRef1);
156   aShapesSeq->Append(aRef2);
157   aShapesSeq->Append(aRef3);
158   aShapesSeq->Append(aRef4);
159
160   aPI.SetShapes(aShapesSeq);
161
162   //Compute the Face value
163   try {
164     if (!GetSolver()->ComputeFunction(aFunction)) {
165       SetErrorCode("Block driver failed to compute a face");
166       return NULL;
167     }
168   }
169   catch (Standard_Failure) {
170     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
171     SetErrorCode(aFail->GetMessageString());
172     return NULL;
173   }
174
175   //Make a Python command
176   GEOM::TPythonDump(aFunction) << aFace << " = geompy.MakeQuad("
177     << theEdge1 << ", " << theEdge2 << ", " << theEdge3 << ", " << theEdge4 << ")";
178
179   SetErrorCode(OK);
180   return aFace;
181 }
182
183 //=============================================================================
184 /*!
185  *  MakeQuad2Edges
186  */
187 //=============================================================================
188 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::MakeQuad2Edges
189                      (Handle(GEOM_Object) theEdge1, Handle(GEOM_Object) theEdge2)
190 {
191   SetErrorCode(KO);
192
193   if (theEdge1.IsNull() || theEdge2.IsNull()) return NULL;
194
195   //Add a new Face object
196   Handle(GEOM_Object) aFace = GetEngine()->AddObject(GetDocID(), GEOM_FACE);
197
198   //Add a new Face function
199   Handle(GEOM_Function) aFunction =
200     aFace->AddFunction(GEOMImpl_BlockDriver::GetID(), BLOCK_FACE_TWO_EDGES);
201
202   //Check if the function is set correctly
203   if (aFunction->GetDriverGUID() != GEOMImpl_BlockDriver::GetID()) return NULL;
204
205   GEOMImpl_IBlocks aPI (aFunction);
206
207   Handle(GEOM_Function) aRef1 = theEdge1->GetLastFunction();
208   Handle(GEOM_Function) aRef2 = theEdge2->GetLastFunction();
209   if (aRef1.IsNull() || aRef2.IsNull()) return NULL;
210
211   Handle(TColStd_HSequenceOfTransient) aShapesSeq = new TColStd_HSequenceOfTransient;
212   aShapesSeq->Append(aRef1);
213   aShapesSeq->Append(aRef2);
214
215   aPI.SetShapes(aShapesSeq);
216
217   //Compute the Face value
218   try {
219     if (!GetSolver()->ComputeFunction(aFunction)) {
220       SetErrorCode("Block driver failed to compute a face");
221       return NULL;
222     }
223   }
224   catch (Standard_Failure) {
225     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
226     SetErrorCode(aFail->GetMessageString());
227     return NULL;
228   }
229
230   //Make a Python command
231   GEOM::TPythonDump(aFunction) << aFace << " = geompy.MakeQuad2Edges("
232                                << theEdge1 << ", " << theEdge2 << ")";
233
234   SetErrorCode(OK);
235   return aFace;
236 }
237
238 //=============================================================================
239 /*!
240  *  MakeQuad4Vertices
241  */
242 //=============================================================================
243 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::MakeQuad4Vertices
244                      (Handle(GEOM_Object) thePnt1, Handle(GEOM_Object) thePnt2,
245                       Handle(GEOM_Object) thePnt3, Handle(GEOM_Object) thePnt4)
246 {
247   SetErrorCode(KO);
248
249   if (thePnt1.IsNull() || thePnt2.IsNull() ||
250       thePnt3.IsNull() || thePnt4.IsNull()) return NULL;
251
252   //Add a new Face object
253   Handle(GEOM_Object) aFace = GetEngine()->AddObject(GetDocID(), GEOM_FACE);
254
255   //Add a new Face function
256   Handle(GEOM_Function) aFunction =
257     aFace->AddFunction(GEOMImpl_BlockDriver::GetID(), BLOCK_FACE_FOUR_PNT);
258
259   //Check if the function is set correctly
260   if (aFunction->GetDriverGUID() != GEOMImpl_BlockDriver::GetID()) return NULL;
261
262   GEOMImpl_IBlocks aPI (aFunction);
263
264   Handle(GEOM_Function) aRef1 = thePnt1->GetLastFunction();
265   Handle(GEOM_Function) aRef2 = thePnt2->GetLastFunction();
266   Handle(GEOM_Function) aRef3 = thePnt3->GetLastFunction();
267   Handle(GEOM_Function) aRef4 = thePnt4->GetLastFunction();
268   if (aRef1.IsNull() || aRef2.IsNull() ||
269       aRef3.IsNull() || aRef4.IsNull()) return NULL;
270
271   Handle(TColStd_HSequenceOfTransient) aShapesSeq = new TColStd_HSequenceOfTransient;
272   aShapesSeq->Append(aRef1);
273   aShapesSeq->Append(aRef2);
274   aShapesSeq->Append(aRef3);
275   aShapesSeq->Append(aRef4);
276
277   aPI.SetShapes(aShapesSeq);
278
279   //Compute the Face value
280   try {
281     if (!GetSolver()->ComputeFunction(aFunction)) {
282       SetErrorCode("Block driver failed to compute a face");
283       return NULL;
284     }
285   }
286   catch (Standard_Failure) {
287     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
288     SetErrorCode(aFail->GetMessageString());
289     return NULL;
290   }
291
292   //Make a Python command
293   GEOM::TPythonDump(aFunction) << aFace << " = geompy.MakeQuad4Vertices("
294     << thePnt1 << ", " << thePnt2 << ", " << thePnt3 << ", " << thePnt4 << ")";
295
296   SetErrorCode(OK);
297   return aFace;
298 }
299
300 //=============================================================================
301 /*!
302  *  MakeHexa
303  */
304 //=============================================================================
305 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::MakeHexa
306                      (Handle(GEOM_Object) theFace1, Handle(GEOM_Object) theFace2,
307                       Handle(GEOM_Object) theFace3, Handle(GEOM_Object) theFace4,
308                       Handle(GEOM_Object) theFace5, Handle(GEOM_Object) theFace6)
309 {
310   SetErrorCode(KO);
311
312   if (theFace1.IsNull() || theFace2.IsNull() ||
313       theFace3.IsNull() || theFace4.IsNull() ||
314       theFace5.IsNull() || theFace6.IsNull()) return NULL;
315
316   //Add a new Solid object
317   Handle(GEOM_Object) aBlock = GetEngine()->AddObject(GetDocID(), GEOM_BLOCK);
318
319   //Add a new Block function
320   Handle(GEOM_Function) aFunction =
321     aBlock->AddFunction(GEOMImpl_BlockDriver::GetID(), BLOCK_SIX_FACES);
322
323   //Check if the function is set correctly
324   if (aFunction->GetDriverGUID() != GEOMImpl_BlockDriver::GetID()) return NULL;
325
326   GEOMImpl_IBlocks aPI (aFunction);
327
328   Handle(GEOM_Function) aRef1 = theFace1->GetLastFunction();
329   Handle(GEOM_Function) aRef2 = theFace2->GetLastFunction();
330   Handle(GEOM_Function) aRef3 = theFace3->GetLastFunction();
331   Handle(GEOM_Function) aRef4 = theFace4->GetLastFunction();
332   Handle(GEOM_Function) aRef5 = theFace5->GetLastFunction();
333   Handle(GEOM_Function) aRef6 = theFace6->GetLastFunction();
334   if (aRef1.IsNull() || aRef2.IsNull() ||
335       aRef3.IsNull() || aRef4.IsNull() ||
336       aRef5.IsNull() || aRef6.IsNull()) return NULL;
337
338   Handle(TColStd_HSequenceOfTransient) aShapesSeq = new TColStd_HSequenceOfTransient;
339   aShapesSeq->Append(aRef1);
340   aShapesSeq->Append(aRef2);
341   aShapesSeq->Append(aRef3);
342   aShapesSeq->Append(aRef4);
343   aShapesSeq->Append(aRef5);
344   aShapesSeq->Append(aRef6);
345
346   aPI.SetShapes(aShapesSeq);
347
348   //Compute the Block value
349   try {
350     if (!GetSolver()->ComputeFunction(aFunction)) {
351       SetErrorCode("Block driver failed to compute a block");
352       return NULL;
353     }
354   }
355   catch (Standard_Failure) {
356     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
357     SetErrorCode(aFail->GetMessageString());
358     return NULL;
359   }
360
361   //Make a Python command
362   GEOM::TPythonDump(aFunction) << aBlock << " = geompy.MakeHexa("
363     << theFace1 << ", " << theFace2 << ", " << theFace3 << ", "
364       << theFace4 << ", " << theFace5 << ", " << theFace6 << ")";
365
366   SetErrorCode(OK);
367   return aBlock;
368 }
369
370 //=============================================================================
371 /*!
372  *  MakeHexa2Faces
373  */
374 //=============================================================================
375 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::MakeHexa2Faces
376                    (Handle(GEOM_Object) theFace1, Handle(GEOM_Object) theFace2)
377 {
378   SetErrorCode(KO);
379
380   if (theFace1.IsNull() || theFace2.IsNull()) return NULL;
381
382   //Add a new Solid object
383   Handle(GEOM_Object) aBlock = GetEngine()->AddObject(GetDocID(), GEOM_BLOCK);
384
385   //Add a new Block function
386   Handle(GEOM_Function) aFunction =
387     aBlock->AddFunction(GEOMImpl_BlockDriver::GetID(), BLOCK_TWO_FACES);
388
389   //Check if the function is set correctly
390   if (aFunction->GetDriverGUID() != GEOMImpl_BlockDriver::GetID()) return NULL;
391
392   GEOMImpl_IBlocks aPI (aFunction);
393
394   Handle(GEOM_Function) aRef1 = theFace1->GetLastFunction();
395   Handle(GEOM_Function) aRef2 = theFace2->GetLastFunction();
396   if (aRef1.IsNull() || aRef2.IsNull()) return NULL;
397
398   Handle(TColStd_HSequenceOfTransient) aShapesSeq = new TColStd_HSequenceOfTransient;
399   aShapesSeq->Append(aRef1);
400   aShapesSeq->Append(aRef2);
401
402   aPI.SetShapes(aShapesSeq);
403
404   //Compute the Block value
405   try {
406     if (!GetSolver()->ComputeFunction(aFunction)) {
407       SetErrorCode("Block driver failed to compute a block");
408       return NULL;
409     }
410   }
411   catch (Standard_Failure) {
412     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
413     SetErrorCode(aFail->GetMessageString());
414     return NULL;
415   }
416
417   //Make a Python command
418   GEOM::TPythonDump(aFunction) << aBlock << " = geompy.MakeHexa2Faces("
419                                << theFace1 << ", " << theFace2 << ")";
420
421   SetErrorCode(OK);
422   return aBlock;
423 }
424
425 //=============================================================================
426 /*!
427  *  MakeBlockCompound
428  */
429 //=============================================================================
430 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::MakeBlockCompound
431                                               (Handle(GEOM_Object) theCompound)
432 {
433   SetErrorCode(KO);
434
435   if (theCompound.IsNull()) return NULL;
436
437   //Add a new object
438   Handle(GEOM_Object) aBlockComp = GetEngine()->AddObject(GetDocID(), GEOM_COMPOUND);
439
440   //Add a new BlocksComp function
441   Handle(GEOM_Function) aFunction =
442     aBlockComp->AddFunction(GEOMImpl_BlockDriver::GetID(), BLOCK_COMPOUND_GLUE);
443
444   //Check if the function is set correctly
445   if (aFunction->GetDriverGUID() != GEOMImpl_BlockDriver::GetID()) return NULL;
446
447   GEOMImpl_IBlocks aPI (aFunction);
448
449   Handle(GEOM_Function) aRef1 = theCompound->GetLastFunction();
450   if (aRef1.IsNull()) return NULL;
451
452   Handle(TColStd_HSequenceOfTransient) aShapesSeq = new TColStd_HSequenceOfTransient;
453   aShapesSeq->Append(aRef1);
454
455   aPI.SetShapes(aShapesSeq);
456
457   //Compute the Blocks Compound value
458   try {
459     if (!GetSolver()->ComputeFunction(aFunction)) {
460       SetErrorCode("Block driver failed to compute a blocks compound");
461       return NULL;
462     }
463   }
464   catch (Standard_Failure) {
465     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
466     SetErrorCode(aFail->GetMessageString());
467     return NULL;
468   }
469
470   //Make a Python command
471   GEOM::TPythonDump(aFunction) << aBlockComp
472     << " = geompy.MakeBlockCompound(" << theCompound << ")";
473
474   SetErrorCode(OK);
475   return aBlockComp;
476 }
477
478 //=============================================================================
479 /*!
480  *  GetPoint
481  */
482 //=============================================================================
483 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::GetPoint
484                                                (Handle(GEOM_Object) theShape,
485                                                 const Standard_Real theX,
486                                                 const Standard_Real theY,
487                                                 const Standard_Real theZ,
488                                                 const Standard_Real theEpsilon)
489 {
490   SetErrorCode(KO);
491
492   //New Point object
493   Handle(GEOM_Object) aResult;
494
495   // Arguments
496   if (theShape.IsNull()) return NULL;
497
498   TopoDS_Shape aBlockOrComp = theShape->GetValue();
499   if (aBlockOrComp.IsNull()) {
500     SetErrorCode("Given shape is null");
501     return NULL;
502   }
503
504   //Compute the Vertex value
505   gp_Pnt P (theX, theY, theZ);
506   Standard_Real eps = Max(theEpsilon, Precision::Confusion());
507
508   TopoDS_Shape V;
509   Standard_Integer isFound = 0;
510   TopTools_MapOfShape mapShape;
511   TopExp_Explorer exp (aBlockOrComp, TopAbs_VERTEX);
512
513   for (; exp.More(); exp.Next()) {
514     if (mapShape.Add(exp.Current())) {
515       TopoDS_Vertex aVi = TopoDS::Vertex(exp.Current());
516       gp_Pnt aPi = BRep_Tool::Pnt(aVi);
517       if (aPi.Distance(P) < eps) {
518         V = aVi;
519         isFound++;
520       }
521     }
522   }
523
524   if (isFound == 0) {
525     SetErrorCode("Vertex has not been found");
526     return NULL;
527   } else if (isFound > 1) {
528     SetErrorCode("Multiple vertices found by the given coordinates and epsilon");
529     return NULL;
530   } else {
531     TopTools_IndexedMapOfShape anIndices;
532     TopExp::MapShapes(aBlockOrComp, anIndices);
533     Handle(TColStd_HArray1OfInteger) anArray = new TColStd_HArray1OfInteger(1,1);
534     anArray->SetValue(1, anIndices.FindIndex(V));
535     aResult = GetEngine()->AddSubShape(theShape, anArray);
536   }
537
538   //The GetPoint() doesn't change object so no new function is required.
539   Handle(GEOM_Function) aFunction = theShape->GetLastFunction();
540
541   //Make a Python command
542   GEOM::TPythonDump(aFunction, /*append=*/true)
543     << aResult << " = geompy.GetPoint(" << theShape << ", "
544     << theX << ", " << theY << ", " << theZ << ", " << theEpsilon << ")";
545
546   SetErrorCode(OK);
547   return aResult;
548 }
549
550 //=============================================================================
551 /*!
552  *  GetEdge
553  */
554 //=============================================================================
555 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::GetEdge
556                                                 (Handle(GEOM_Object) theShape,
557                                                  Handle(GEOM_Object) thePoint1,
558                                                  Handle(GEOM_Object) thePoint2)
559 {
560   SetErrorCode(KO);
561
562   //New Edge object
563   Handle(GEOM_Object) aResult;
564
565   // Arguments
566   if (theShape.IsNull() || thePoint1.IsNull() || thePoint2.IsNull()) return NULL;
567
568   TopoDS_Shape aBlockOrComp = theShape->GetValue();
569   if (aBlockOrComp.IsNull()) {
570     SetErrorCode("Given shape is null");
571     return NULL;
572   }
573
574   TopoDS_Shape anArg1 = thePoint1->GetValue();
575   TopoDS_Shape anArg2 = thePoint2->GetValue();
576   if (anArg1.IsNull() || anArg2.IsNull()) {
577     SetErrorCode("Null shape is given as argument");
578     return NULL;
579   }
580   if (anArg1.ShapeType() != TopAbs_VERTEX ||
581       anArg2.ShapeType() != TopAbs_VERTEX) {
582     SetErrorCode("Element for edge identification is not a vertex");
583     return NULL;
584   }
585
586   //Compute the Edge value
587   try {
588     TopTools_IndexedDataMapOfShapeListOfShape MVE;
589     GEOMImpl_Block6Explorer::MapShapesAndAncestors
590       (aBlockOrComp, TopAbs_VERTEX, TopAbs_EDGE, MVE);
591
592     TopoDS_Shape V1,V2;
593     Standard_Integer ish, ext = MVE.Extent();
594
595     if (MVE.Contains(anArg1)) {
596       V1 = anArg1;
597     } else {
598       for (ish = 1; ish <= ext; ish++) {
599         TopoDS_Shape aShi = MVE.FindKey(ish);
600         if (BRepTools::Compare(TopoDS::Vertex(anArg1), TopoDS::Vertex(aShi))) {
601           V1 = aShi;
602           break;
603         }
604       }
605     }
606
607     if (MVE.Contains(anArg2)) {
608       V2 = anArg2;
609     } else {
610       for (ish = 1; ish <= ext; ish++) {
611         TopoDS_Shape aShi = MVE.FindKey(ish);
612         if (BRepTools::Compare(TopoDS::Vertex(anArg2), TopoDS::Vertex(aShi))) {
613           V2 = aShi;
614           break;
615         }
616       }
617     }
618
619     if (V1.IsNull() || V2.IsNull()) {
620       SetErrorCode("The given vertex does not belong to the shape");
621       return NULL;
622     }
623
624     TopoDS_Shape anEdge;
625     Standard_Integer isFound =
626       GEOMImpl_Block6Explorer::FindEdge(anEdge, V1, V2, MVE, Standard_True);
627     if (isFound == 0) {
628       SetErrorCode("The given vertices do not belong to one edge of the given shape");
629       return NULL;
630     } else if (isFound > 1) {
631       SetErrorCode("Multiple edges found by the given vertices of the shape");
632       return NULL;
633     } else {
634       TopTools_IndexedMapOfShape anIndices;
635       TopExp::MapShapes(aBlockOrComp, anIndices);
636       Handle(TColStd_HArray1OfInteger) anArray = new TColStd_HArray1OfInteger(1,1);
637       anArray->SetValue(1, anIndices.FindIndex(anEdge));
638       aResult = GetEngine()->AddSubShape(theShape, anArray);
639     }
640   } catch (Standard_Failure) {
641     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
642     SetErrorCode(aFail->GetMessageString());
643     return NULL;
644   }
645
646   Handle(GEOM_Function) aFunction = aResult->GetLastFunction();
647
648   //Make a Python command
649   GEOM::TPythonDump(aFunction) << aResult << " = geompy.GetEdge("
650     << theShape << ", " << thePoint1 << ", " << thePoint2 << ")";
651
652   SetErrorCode(OK);
653   return aResult;
654 }
655
656 //=============================================================================
657 /*!
658  *  GetEdgeNearPoint
659  */
660 //=============================================================================
661 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::GetEdgeNearPoint
662                                                 (Handle(GEOM_Object) theShape,
663                                                  Handle(GEOM_Object) thePoint)
664 {
665   SetErrorCode(KO);
666
667   //New object
668   Handle(GEOM_Object) aResult;
669
670   // Arguments
671   if (theShape.IsNull() || thePoint.IsNull()) return NULL;
672
673   TopoDS_Shape aBlockOrComp = theShape->GetValue();
674   if (aBlockOrComp.IsNull()) {
675     SetErrorCode("Given shape is null");
676     return NULL;
677   }
678
679   TopoDS_Shape anArg = thePoint->GetValue();
680   if (anArg.IsNull()) {
681     SetErrorCode("Null shape is given as argument");
682     return NULL;
683   }
684   if (anArg.ShapeType() != TopAbs_VERTEX) {
685     SetErrorCode("Element for edge identification is not a vertex");
686     return NULL;
687   }
688
689   //Compute the Edge value
690   try {
691     TopoDS_Shape aShape;
692
693     TopoDS_Vertex aVert = TopoDS::Vertex(anArg);
694
695     // 1. Explode blocks on edges
696     TopTools_MapOfShape mapShape;
697     Standard_Integer nbEdges = 0;
698     TopExp_Explorer exp (aBlockOrComp, TopAbs_EDGE);
699     for (; exp.More(); exp.Next()) {
700       if (mapShape.Add(exp.Current())) {
701         nbEdges++;
702       }
703     }
704
705     if (nbEdges == 0) {
706       SetErrorCode("Given shape contains no edges");
707       return NULL;
708     }
709
710     mapShape.Clear();
711     Standard_Integer ind = 1;
712     TopTools_Array1OfShape anEdges (1, nbEdges);
713     TColStd_Array1OfReal aDistances (1, nbEdges);
714     for (exp.Init(aBlockOrComp, TopAbs_EDGE); exp.More(); exp.Next()) {
715       if (mapShape.Add(exp.Current())) {
716         TopoDS_Shape anEdge = exp.Current();
717         anEdges(ind) = anEdge;
718
719         // 2. Classify the point relatively each edge
720         BRepExtrema_DistShapeShape aDistTool (aVert, anEdges(ind));
721         if (!aDistTool.IsDone()) {
722           SetErrorCode("Can not find a distance from the given point to one of edges");
723           return NULL;
724         }
725         aDistances(ind) = aDistTool.Value();
726         ind++;
727       }
728     }
729
730     // 3. Define edge, having minimum distance to the point
731     Standard_Real nearest = RealLast(), nbFound = 0;
732     Standard_Real prec = Precision::Confusion();
733     for (ind = 1; ind <= nbEdges; ind++) {
734       if (Abs(aDistances(ind) - nearest) < prec) {
735         nbFound++;
736       } else if (aDistances(ind) < nearest) {
737         nearest = aDistances(ind);
738         aShape = anEdges(ind);
739         nbFound = 1;
740       } else {
741       }
742     }
743     if (nbFound > 1) {
744       SetErrorCode("Multiple edges near the given point are found");
745       return NULL;
746     } else if (nbFound == 0) {
747       SetErrorCode("There are no edges near the given point");
748       return NULL;
749     } else {
750       TopTools_IndexedMapOfShape anIndices;
751       TopExp::MapShapes(aBlockOrComp, anIndices);
752       Handle(TColStd_HArray1OfInteger) anArray = new TColStd_HArray1OfInteger(1,1);
753       anArray->SetValue(1, anIndices.FindIndex(aShape));
754       aResult = GetEngine()->AddSubShape(theShape, anArray);
755     }
756   }
757   catch (Standard_Failure) {
758     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
759     SetErrorCode(aFail->GetMessageString());
760     return NULL;
761   }
762
763   Handle(GEOM_Function) aFunction = aResult->GetLastFunction();
764
765   //Make a Python command
766   GEOM::TPythonDump(aFunction) << aResult << " = geompy.GetEdgeNearPoint("
767                                << theShape << ", " << thePoint << ")";
768
769   SetErrorCode(OK);
770   return aResult;
771 }
772
773 //=============================================================================
774 /*!
775  *  GetFaceByPoints
776  */
777 //=============================================================================
778 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::GetFaceByPoints
779                                                 (Handle(GEOM_Object) theShape,
780                                                  Handle(GEOM_Object) thePoint1,
781                                                  Handle(GEOM_Object) thePoint2,
782                                                  Handle(GEOM_Object) thePoint3,
783                                                  Handle(GEOM_Object) thePoint4)
784 {
785   SetErrorCode(KO);
786
787   //New object
788   Handle(GEOM_Object) aResult;
789
790   // Arguments
791   if (theShape.IsNull() ||
792       thePoint1.IsNull() || thePoint2.IsNull() ||
793       thePoint3.IsNull() || thePoint4.IsNull()) return NULL;
794
795   TopoDS_Shape aBlockOrComp = theShape->GetValue();
796   if (aBlockOrComp.IsNull()) {
797     SetErrorCode("Block or compound is null");
798     return NULL;
799   }
800
801   TopoDS_Shape anArg1 = thePoint1->GetValue();
802   TopoDS_Shape anArg2 = thePoint2->GetValue();
803   TopoDS_Shape anArg3 = thePoint3->GetValue();
804   TopoDS_Shape anArg4 = thePoint4->GetValue();
805   if (anArg1.IsNull() || anArg2.IsNull() ||
806       anArg3.IsNull() || anArg4.IsNull()) {
807     SetErrorCode("Null shape is given as argument");
808     return NULL;
809   }
810   if (anArg1.ShapeType() != TopAbs_VERTEX ||
811       anArg2.ShapeType() != TopAbs_VERTEX ||
812       anArg3.ShapeType() != TopAbs_VERTEX ||
813       anArg4.ShapeType() != TopAbs_VERTEX) {
814     SetErrorCode("Element for face identification is not a vertex");
815     return NULL;
816   }
817
818   //Compute the Face value
819   try {
820     TopoDS_Shape aShape;
821
822     TopTools_IndexedDataMapOfShapeListOfShape MVF;
823     GEOMImpl_Block6Explorer::MapShapesAndAncestors(aBlockOrComp, TopAbs_VERTEX, TopAbs_FACE, MVF);
824
825     TopoDS_Shape V1,V2,V3,V4;
826     Standard_Integer ish, ext = MVF.Extent();
827
828     if (MVF.Contains(anArg1)) {
829       V1 = anArg1;
830     } else {
831       for (ish = 1; ish <= ext; ish++) {
832         TopoDS_Shape aShi = MVF.FindKey(ish);
833         if (BRepTools::Compare(TopoDS::Vertex(anArg1), TopoDS::Vertex(aShi))) {
834           V1 = aShi;
835           break;
836         }
837       }
838     }
839
840     if (MVF.Contains(anArg2)) {
841       V2 = anArg2;
842     } else {
843       for (ish = 1; ish <= ext; ish++) {
844         TopoDS_Shape aShi = MVF.FindKey(ish);
845         if (BRepTools::Compare(TopoDS::Vertex(anArg2), TopoDS::Vertex(aShi))) {
846           V2 = aShi;
847           break;
848         }
849       }
850     }
851
852     if (MVF.Contains(anArg3)) {
853       V3 = anArg3;
854     } else {
855       for (ish = 1; ish <= ext; ish++) {
856         TopoDS_Shape aShi = MVF.FindKey(ish);
857         if (BRepTools::Compare(TopoDS::Vertex(anArg3), TopoDS::Vertex(aShi))) {
858           V3 = aShi;
859           break;
860         }
861       }
862     }
863
864     if (MVF.Contains(anArg4)) {
865       V4 = anArg4;
866     } else {
867       for (ish = 1; ish <= ext; ish++) {
868         TopoDS_Shape aShi = MVF.FindKey(ish);
869         if (BRepTools::Compare(TopoDS::Vertex(anArg4), TopoDS::Vertex(aShi))) {
870           V4 = aShi;
871           break;
872         }
873       }
874     }
875
876     if (V1.IsNull() || V2.IsNull() || V3.IsNull() || V4.IsNull()) {
877       SetErrorCode("The given vertex does not belong to the shape");
878       return NULL;
879     }
880
881     Standard_Integer isFound =
882       GEOMImpl_Block6Explorer::FindFace(aShape, V1, V2, V3, V4, MVF, Standard_True);
883     if (isFound == 0) {
884       SetErrorCode("The given vertices do not belong to one face of the given shape");
885       return NULL;
886     } else if (isFound > 1) {
887       SetErrorCode("The given vertices belong to several faces of the given shape");
888       return NULL;
889     } else {
890       TopTools_IndexedMapOfShape anIndices;
891       TopExp::MapShapes(aBlockOrComp, anIndices);
892       Handle(TColStd_HArray1OfInteger) anArray = new TColStd_HArray1OfInteger(1,1);
893       anArray->SetValue(1, anIndices.FindIndex(aShape));
894       aResult = GetEngine()->AddSubShape(theShape, anArray);
895     }
896   }
897   catch (Standard_Failure) {
898     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
899     SetErrorCode(aFail->GetMessageString());
900     return NULL;
901   }
902
903   Handle(GEOM_Function) aFunction = aResult->GetLastFunction();
904
905   //Make a Python command
906   GEOM::TPythonDump(aFunction) << aResult << " = geompy.GetFaceByPoints("
907     << theShape << ", " << thePoint1 << ", " << thePoint2
908       << ", " << thePoint3 << ", " << thePoint4 << ")";
909
910   SetErrorCode(OK);
911   return aResult;
912 }
913
914 //=============================================================================
915 /*!
916  *  GetFaceByEdges
917  */
918 //=============================================================================
919 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::GetFaceByEdges
920                                                 (Handle(GEOM_Object) theShape,
921                                                  Handle(GEOM_Object) theEdge1,
922                                                  Handle(GEOM_Object) theEdge2)
923 {
924   SetErrorCode(KO);
925
926   //New object
927   Handle(GEOM_Object) aResult;
928
929   // Arguments
930   if (theShape.IsNull() || theEdge1.IsNull() || theEdge2.IsNull()) return NULL;
931
932   TopoDS_Shape aBlockOrComp = theShape->GetValue();
933   if (aBlockOrComp.IsNull()) {
934     SetErrorCode("Block or compound is null");
935     return NULL;
936   }
937
938   TopoDS_Shape anArg1 = theEdge1->GetValue();
939   TopoDS_Shape anArg2 = theEdge2->GetValue();
940   if (anArg1.IsNull() || anArg2.IsNull()) {
941     SetErrorCode("Null shape is given as argument");
942     return NULL;
943   }
944   if (anArg1.ShapeType() != TopAbs_EDGE ||
945       anArg2.ShapeType() != TopAbs_EDGE) {
946     SetErrorCode("Element for face identification is not an edge");
947     return NULL;
948   }
949
950   //Compute the Face value
951   try {
952     TopoDS_Shape aShape;
953
954     TopTools_IndexedDataMapOfShapeListOfShape MEF;
955     GEOMImpl_Block6Explorer::MapShapesAndAncestors(aBlockOrComp, TopAbs_EDGE, TopAbs_FACE, MEF);
956
957     TopoDS_Shape E1,E2;
958     Standard_Integer ish, ext = MEF.Extent();
959
960     if (MEF.Contains(anArg1)) {
961       E1 = anArg1;
962     } else {
963       for (ish = 1; ish <= ext; ish++) {
964         TopoDS_Shape aShi = MEF.FindKey(ish);
965         if (GEOMImpl_Block6Explorer::IsSimilarEdges(anArg1, aShi)) {
966           E1 = aShi;
967         }
968       }
969     }
970
971     if (MEF.Contains(anArg2)) {
972       E2 = anArg2;
973     } else {
974       for (ish = 1; ish <= ext; ish++) {
975         TopoDS_Shape aShi = MEF.FindKey(ish);
976         if (GEOMImpl_Block6Explorer::IsSimilarEdges(anArg2, aShi)) {
977           E2 = aShi;
978         }
979       }
980     }
981
982     if (E1.IsNull() || E2.IsNull()) {
983       SetErrorCode("The given edge does not belong to the shape");
984       return NULL;
985     }
986
987     const TopTools_ListOfShape& aFacesOfE1 = MEF.FindFromKey(E1);
988     const TopTools_ListOfShape& aFacesOfE2 = MEF.FindFromKey(E2);
989
990     Standard_Integer isFound = 0;
991     TopTools_ListIteratorOfListOfShape anIterF1 (aFacesOfE1);
992     for (; anIterF1.More(); anIterF1.Next()) {
993
994       TopTools_ListIteratorOfListOfShape anIterF2 (aFacesOfE2);
995       for (; anIterF2.More(); anIterF2.Next()) {
996
997         if (anIterF1.Value().IsSame(anIterF2.Value())) {
998           isFound++;
999
1000           // Store the face, defined by two edges
1001           aShape = anIterF1.Value();
1002         }
1003       }
1004     }
1005     if (isFound == 0) {
1006       SetErrorCode("The given edges do not belong to one face of the given shape");
1007       return NULL;
1008     } else if (isFound > 1) {
1009       SetErrorCode("The given edges belong to several faces of the given shape");
1010       return NULL;
1011     } else {
1012       TopTools_IndexedMapOfShape anIndices;
1013       TopExp::MapShapes(aBlockOrComp, anIndices);
1014       Handle(TColStd_HArray1OfInteger) anArray = new TColStd_HArray1OfInteger(1,1);
1015       anArray->SetValue(1, anIndices.FindIndex(aShape));
1016       aResult = GetEngine()->AddSubShape(theShape, anArray);
1017     }
1018   }
1019   catch (Standard_Failure) {
1020     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
1021     SetErrorCode(aFail->GetMessageString());
1022     return NULL;
1023   }
1024
1025   Handle(GEOM_Function) aFunction = aResult->GetLastFunction();
1026
1027   //Make a Python command
1028   GEOM::TPythonDump(aFunction) << aResult << " = geompy.GetFaceByEdges("
1029     << theShape << ", " << theEdge1 << ", " << theEdge2 << ")";
1030
1031   SetErrorCode(OK);
1032   return aResult;
1033 }
1034
1035 //=============================================================================
1036 /*!
1037  *  GetOppositeFace
1038  */
1039 //=============================================================================
1040 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::GetOppositeFace
1041                                                 (Handle(GEOM_Object) theShape,
1042                                                  Handle(GEOM_Object) theFace)
1043 {
1044   SetErrorCode(KO);
1045
1046   //New object
1047   Handle(GEOM_Object) aResult;
1048
1049   // Arguments
1050   if (theShape.IsNull() || theFace.IsNull()) return NULL;
1051
1052   TopoDS_Shape aBlockOrComp = theShape->GetValue();
1053   if (aBlockOrComp.IsNull()) {
1054     SetErrorCode("Block is null");
1055     return NULL;
1056   }
1057   if (aBlockOrComp.ShapeType() != TopAbs_SOLID) {
1058     SetErrorCode("Shape is not a block");
1059     return NULL;
1060   }
1061
1062   TopoDS_Shape anArg = theFace->GetValue();
1063   if (anArg.IsNull()) {
1064     SetErrorCode("Null shape is given as argument");
1065     return NULL;
1066   }
1067   if (anArg.ShapeType() != TopAbs_FACE) {
1068     SetErrorCode("Element for face identification is not a face");
1069     return NULL;
1070   }
1071
1072   //Compute the Face value
1073   try {
1074     TopoDS_Shape aShape;
1075
1076     GEOMImpl_Block6Explorer aBlockTool;
1077     aBlockTool.InitByBlockAndFace(aBlockOrComp, anArg);
1078     aShape = aBlockTool.GetFace(2);
1079
1080     TopTools_IndexedMapOfShape anIndices;
1081     TopExp::MapShapes(aBlockOrComp, anIndices);
1082     Handle(TColStd_HArray1OfInteger) anArray = new TColStd_HArray1OfInteger(1,1);
1083     anArray->SetValue(1, anIndices.FindIndex(aShape));
1084     aResult = GetEngine()->AddSubShape(theShape, anArray);
1085   }
1086   catch (Standard_Failure) {
1087     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
1088     SetErrorCode(aFail->GetMessageString());
1089     return NULL;
1090   }
1091
1092   Handle(GEOM_Function) aFunction = aResult->GetLastFunction();
1093
1094   //Make a Python command
1095   GEOM::TPythonDump(aFunction) << aResult << " = geompy.GetOppositeFace("
1096                                << theShape << ", " << theFace << ")";
1097
1098   SetErrorCode(OK);
1099   return aResult;
1100 }
1101
1102 //=============================================================================
1103 /*!
1104  *  GetFaceNearPoint
1105  */
1106 //=============================================================================
1107 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::GetFaceNearPoint
1108                                                 (Handle(GEOM_Object) theShape,
1109                                                  Handle(GEOM_Object) thePoint)
1110 {
1111   SetErrorCode(KO);
1112
1113   //New object
1114   Handle(GEOM_Object) aResult;
1115
1116   // Arguments
1117   if (theShape.IsNull() || thePoint.IsNull()) return NULL;
1118
1119   TopoDS_Shape aBlockOrComp = theShape->GetValue();
1120   if (aBlockOrComp.IsNull()) {
1121     SetErrorCode("Block or compound is null");
1122     return NULL;
1123   }
1124
1125   TopoDS_Shape anArg = thePoint->GetValue();
1126   if (anArg.IsNull()) {
1127     SetErrorCode("Null shape is given as argument");
1128     return NULL;
1129   }
1130   if (anArg.ShapeType() != TopAbs_VERTEX) {
1131     SetErrorCode("Element for face identification is not a vertex");
1132     return NULL;
1133   }
1134
1135   //Compute the Face value
1136   try {
1137     TopoDS_Shape aShape;
1138
1139     TopoDS_Vertex aVert = TopoDS::Vertex(anArg);
1140     gp_Pnt aPnt = BRep_Tool::Pnt(aVert);
1141     Standard_Real PX, PY, PZ;
1142     aPnt.Coord(PX, PY, PZ);
1143
1144     // 1. Classify the point relatively each face
1145     Standard_Integer nearest = 2, nbFound = 0;
1146     TopTools_DataMapOfShapeInteger mapShapeDist;
1147     TopExp_Explorer exp (aBlockOrComp, TopAbs_FACE);
1148     for (; exp.More(); exp.Next()) {
1149       TopoDS_Shape aFace = exp.Current();
1150
1151       if (!mapShapeDist.IsBound(aFace)) {
1152         Standard_Integer aDistance = 2;
1153
1154         // 1.a. Classify relatively Surface
1155         Handle(Geom_Surface) aSurf = BRep_Tool::Surface(TopoDS::Face(aFace));
1156         Handle(ShapeAnalysis_Surface) aSurfAna = new ShapeAnalysis_Surface (aSurf);
1157         gp_Pnt2d p2dOnSurf = aSurfAna->ValueOfUV(aPnt, Precision::Confusion());
1158         gp_Pnt p3dOnSurf = aSurfAna->Value(p2dOnSurf);
1159         Standard_Real aDist = p3dOnSurf.Distance(aPnt);
1160         if (aDist > Precision::Confusion()) {
1161           // OUT of Surface
1162           aDistance = 1;
1163         } else {
1164           // 1.b. Classify relatively the face itself
1165           BRepClass_FaceClassifier FC (TopoDS::Face(aFace), p2dOnSurf, Precision::Confusion());
1166           if (FC.State() == TopAbs_IN) {
1167             aDistance = -1;
1168           } else if (FC.State() == TopAbs_ON) {
1169             aDistance = 0;
1170           } else { // OUT
1171             aDistance = 1;
1172           }
1173         }
1174
1175         if (aDistance < nearest) {
1176           nearest = aDistance;
1177           aShape = aFace;
1178           nbFound = 1;
1179
1180           // A first found face, containing the point inside, will be returned.
1181           // It is the solution, if there are no
1182           // coincident or intersecting faces in the compound.
1183           if (nearest == -1) break;
1184
1185         } else if (aDistance == nearest) {
1186           nbFound++;
1187         } else {
1188         }
1189
1190         mapShapeDist.Bind(aFace, aDistance);
1191       } // if (!mapShapeDist.IsBound(aFace))
1192     }
1193
1194     // 2. Define face, containing the point or having minimum distance to it
1195     if (nbFound > 1) {
1196       if (nearest == 0) {
1197         // The point is on boundary of some faces and there are
1198         // no faces, having the point inside
1199         SetErrorCode("Multiple faces near the given point are found");
1200         return NULL;
1201
1202       } else if (nearest == 1) {
1203         // The point is outside some faces and there are
1204         // no faces, having the point inside or on boundary.
1205         // We will get a nearest face
1206         Standard_Real bigReal = RealLast();
1207         Standard_Real minDist = bigReal;
1208         TopTools_DataMapIteratorOfDataMapOfShapeInteger mapShapeDistIter (mapShapeDist);
1209         for (; mapShapeDistIter.More(); mapShapeDistIter.Next()) {
1210           if (mapShapeDistIter.Value() == 1) {
1211             TopoDS_Shape aFace = mapShapeDistIter.Key();
1212             Standard_Real aDist = bigReal;
1213
1214             // 2.a. Fast check of distance - if point projection on surface is on face
1215             Handle(Geom_Surface) aSurf = BRep_Tool::Surface(TopoDS::Face(aFace));
1216             Handle(ShapeAnalysis_Surface) aSurfAna = new ShapeAnalysis_Surface (aSurf);
1217             gp_Pnt2d p2dOnSurf = aSurfAna->ValueOfUV(aPnt, Precision::Confusion());
1218             gp_Pnt p3dOnSurf = aSurfAna->Value(p2dOnSurf);
1219             aDist = p3dOnSurf.Distance(aPnt);
1220
1221             BRepClass_FaceClassifier FC (TopoDS::Face(aFace), p2dOnSurf, Precision::Confusion());
1222             if (FC.State() == TopAbs_OUT) {
1223               if (aDist < minDist) {
1224                 // 2.b. Slow check - if point projection on surface is outside of face
1225                 BRepExtrema_DistShapeShape aDistTool (aVert, aFace);
1226                 if (!aDistTool.IsDone()) {
1227                   SetErrorCode("Can not find a distance from the given point to one of faces");
1228                   return NULL;
1229                 }
1230                 aDist = aDistTool.Value();
1231               } else {
1232                 aDist = bigReal;
1233               }
1234             }
1235
1236             if (aDist < minDist) {
1237               minDist = aDist;
1238               aShape = aFace;
1239             }
1240           }
1241         }
1242       } else { // nearest == -1
1243 //        // The point is inside some faces.
1244 //        // We will get a face with nearest center
1245 //        Standard_Real minDist = RealLast();
1246 //        TopTools_DataMapIteratorOfDataMapOfShapeInteger mapShapeDistIter (mapShapeDist);
1247 //        for (; mapShapeDistIter.More(); mapShapeDistIter.Next()) {
1248 //          if (mapShapeDistIter.Value() == -1) {
1249 //            TopoDS_Shape aFace = mapShapeDistIter.Key();
1250 //            GProp_GProps aSystem;
1251 //            BRepGProp::SurfaceProperties(aFace, aSystem);
1252 //            gp_Pnt aCenterMass = aSystem.CentreOfMass();
1253 //
1254 //            Standard_Real aDist = aCenterMass.Distance(aPnt);
1255 //            if (aDist < minDist) {
1256 //              minDist = aDist;
1257 //              aShape = aFace;
1258 //            }
1259 //          }
1260 //        }
1261       }
1262     } // if (nbFound > 1)
1263
1264     if (nbFound == 0) {
1265       SetErrorCode("There are no faces near the given point");
1266       return NULL;
1267     } else {
1268       TopTools_IndexedMapOfShape anIndices;
1269       TopExp::MapShapes(aBlockOrComp, anIndices);
1270       Handle(TColStd_HArray1OfInteger) anArray = new TColStd_HArray1OfInteger(1,1);
1271       anArray->SetValue(1, anIndices.FindIndex(aShape));
1272       aResult = GetEngine()->AddSubShape(theShape, anArray);
1273     }
1274   }
1275   catch (Standard_Failure) {
1276     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
1277     SetErrorCode(aFail->GetMessageString());
1278     return NULL;
1279   }
1280
1281   Handle(GEOM_Function) aFunction = aResult->GetLastFunction();
1282
1283   //Make a Python command
1284   GEOM::TPythonDump(aFunction) << aResult << " = geompy.GetFaceNearPoint("
1285                                << theShape << ", " << thePoint << ")";
1286
1287   SetErrorCode(OK);
1288   return aResult;
1289 }
1290
1291 //=============================================================================
1292 /*!
1293  *  GetFaceByNormale
1294  */
1295 //=============================================================================
1296 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::GetFaceByNormale
1297                                                 (Handle(GEOM_Object) theShape,
1298                                                  Handle(GEOM_Object) theVector)
1299 {
1300   SetErrorCode(KO);
1301
1302   //New object
1303   Handle(GEOM_Object) aResult;
1304
1305   // Arguments
1306   if (theShape.IsNull() || theVector.IsNull()) return NULL;
1307
1308   TopoDS_Shape aBlockOrComp = theShape->GetValue();
1309   if (aBlockOrComp.IsNull()) {
1310     SetErrorCode("Block or compound is null");
1311     return NULL;
1312   }
1313
1314   TopoDS_Shape anArg = theVector->GetValue();
1315   if (anArg.IsNull()) {
1316     SetErrorCode("Null shape is given as argument");
1317     return NULL;
1318   }
1319   if (anArg.ShapeType() != TopAbs_EDGE) {
1320     SetErrorCode("Element for normale identification is not an edge");
1321     return NULL;
1322   }
1323
1324   //Compute the Face value
1325   try {
1326     TopoDS_Shape aShape;
1327
1328     TopoDS_Edge anEdge = TopoDS::Edge(anArg);
1329     TopoDS_Vertex V1, V2;
1330     TopExp::Vertices(anEdge, V1, V2, Standard_True);
1331     gp_Pnt P1 = BRep_Tool::Pnt(V1);
1332     gp_Pnt P2 = BRep_Tool::Pnt(V2);
1333     gp_Vec aVec (P1, P2);
1334     if (aVec.Magnitude() < Precision::Confusion()) {
1335       SetErrorCode("Vector with null magnitude is given");
1336       return NULL;
1337     }
1338
1339     Standard_Real minAngle = RealLast();
1340     TopTools_MapOfShape mapShape;
1341     TopExp_Explorer exp (aBlockOrComp, TopAbs_FACE);
1342     for (; exp.More(); exp.Next()) {
1343       if (mapShape.Add(exp.Current())) {
1344         TopoDS_Face aFace = TopoDS::Face(exp.Current());
1345         BRepAdaptor_Surface SF (aFace);
1346
1347         Standard_Real u, v, x;
1348
1349         // find a point on the surface to get normal direction in
1350         u = SF.FirstUParameter();
1351         x = SF.LastUParameter();
1352         if (Precision::IsInfinite(u)) {
1353           u =  (Precision::IsInfinite(x)) ? 0. : x;
1354         } else if (!Precision::IsInfinite(x)) {
1355           u = (u+x) / 2.;
1356         }
1357
1358         v = SF.FirstVParameter();
1359         x = SF.LastVParameter();
1360         if (Precision::IsInfinite(v)) {
1361           v =  (Precision::IsInfinite(x)) ? 0. : x;
1362         } else if (!Precision::IsInfinite(x)) {
1363           v = (v+x) / 2.;
1364         }
1365
1366         // compute the normal direction
1367         gp_Vec Vec1,Vec2;
1368         SF.D1(u,v,P1,Vec1,Vec2);
1369         gp_Vec V = Vec1.Crossed(Vec2);
1370         x = V.Magnitude();
1371         if (V.Magnitude() < Precision::Confusion()) {
1372           SetErrorCode("Normal vector of a face has null magnitude");
1373           return NULL;
1374         }
1375
1376         // consider the face orientation
1377         if (aFace.Orientation() == TopAbs_REVERSED ||
1378             aFace.Orientation() == TopAbs_INTERNAL) {
1379           V = - V;
1380         }
1381
1382         // compute the angle and compare with the minimal one
1383         Standard_Real anAngle = aVec.Angle(V);
1384         if (anAngle < minAngle) {
1385           minAngle = anAngle;
1386           aShape = aFace;
1387         }
1388       }
1389     }
1390
1391     if (aShape.IsNull()) {
1392       SetErrorCode("Failed to find a face by the given normale");
1393       return NULL;
1394     } else {
1395       TopTools_IndexedMapOfShape anIndices;
1396       TopExp::MapShapes(aBlockOrComp, anIndices);
1397       Handle(TColStd_HArray1OfInteger) anArray = new TColStd_HArray1OfInteger(1,1);
1398       anArray->SetValue(1, anIndices.FindIndex(aShape));
1399       aResult = GetEngine()->AddSubShape(theShape, anArray);
1400     }
1401   }
1402   catch (Standard_Failure) {
1403     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
1404     SetErrorCode(aFail->GetMessageString());
1405     return NULL;
1406   }
1407
1408   Handle(GEOM_Function) aFunction = aResult->GetLastFunction();
1409
1410   //Make a Python command
1411   GEOM::TPythonDump(aFunction) << aResult << " = geompy.GetFaceByNormale("
1412     << theShape << ", " << theVector << ")";
1413
1414   SetErrorCode(OK);
1415   return aResult;
1416 }
1417
1418 //=============================================================================
1419 /*!
1420  *  IsCompoundOfBlocks
1421  */
1422 //=============================================================================
1423 Standard_Boolean GEOMImpl_IBlocksOperations::IsCompoundOfBlocks
1424                                                 (Handle(GEOM_Object)    theCompound,
1425                                                  const Standard_Integer theMinNbFaces,
1426                                                  const Standard_Integer theMaxNbFaces,
1427                                                  Standard_Integer&      theNbBlocks)
1428 {
1429   SetErrorCode(KO);
1430   Standard_Boolean isCompOfBlocks = Standard_False;
1431   theNbBlocks = 0;
1432
1433   if (theCompound.IsNull()) return isCompOfBlocks;
1434   TopoDS_Shape aBlockOrComp = theCompound->GetValue();
1435
1436   //Check
1437   isCompOfBlocks = Standard_True;
1438   try {
1439     TopTools_MapOfShape mapShape;
1440     TopExp_Explorer exp (aBlockOrComp, TopAbs_SOLID);
1441     for (; exp.More(); exp.Next()) {
1442       if (mapShape.Add(exp.Current())) {
1443         TopoDS_Shape aSolid = exp.Current();
1444
1445         TopTools_MapOfShape mapFaces;
1446         TopExp_Explorer expF (aSolid, TopAbs_FACE);
1447         Standard_Integer nbFaces = 0;
1448         for (; expF.More(); expF.Next()) {
1449           if (mapFaces.Add(expF.Current())) {
1450             nbFaces++;
1451             if (nbFaces > theMaxNbFaces) {
1452               isCompOfBlocks = Standard_False;
1453               break;
1454             }
1455           }
1456         }
1457         if (nbFaces < theMinNbFaces || theMaxNbFaces < nbFaces) {
1458           isCompOfBlocks = Standard_False;
1459         } else {
1460           theNbBlocks++;
1461         }
1462       }
1463     }
1464   }
1465   catch (Standard_Failure) {
1466     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
1467     SetErrorCode(aFail->GetMessageString());
1468     return isCompOfBlocks;
1469   }
1470
1471   SetErrorCode(OK);
1472   return isCompOfBlocks;
1473 }
1474
1475 //=============================================================================
1476 /*!
1477  *  Set of functions, used by CheckCompoundOfBlocks() method
1478  */
1479 //=============================================================================
1480 void GEOMImpl_IBlocksOperations::AddBlocksFrom (const TopoDS_Shape&   theShape,
1481                                                 TopTools_ListOfShape& BLO,
1482                                                 TopTools_ListOfShape& NOT,
1483                                                 TopTools_ListOfShape& EXT)
1484 {
1485   TopAbs_ShapeEnum aType = theShape.ShapeType();
1486   switch (aType) {
1487   case TopAbs_COMPOUND:
1488   case TopAbs_COMPSOLID:
1489     {
1490       TopoDS_Iterator It (theShape);
1491       for (; It.More(); It.Next()) {
1492         AddBlocksFrom(It.Value(), BLO, NOT, EXT);
1493       }
1494     }
1495     break;
1496   case TopAbs_SOLID:
1497     {
1498       // Check, if there are seam or degenerated edges
1499       BlockFix_CheckTool aTool;
1500       aTool.SetShape(theShape);
1501       aTool.Perform();
1502       if (aTool.NbPossibleBlocks() > 0) {
1503         EXT.Append(theShape);
1504       } else {
1505         // Count faces and edges in each face to recognize blocks
1506         TopTools_MapOfShape mapFaces;
1507         Standard_Integer nbFaces = 0;
1508         Standard_Boolean hasNonQuadr = Standard_False;
1509         TopExp_Explorer expF (theShape, TopAbs_FACE);
1510
1511         for (; expF.More(); expF.Next()) {
1512           if (mapFaces.Add(expF.Current())) {
1513             nbFaces++;
1514             if (nbFaces > 6) break;
1515
1516             // get wire
1517             TopoDS_Shape aF = expF.Current();
1518             TopExp_Explorer wires (aF, TopAbs_WIRE);
1519             if (!wires.More()) {
1520               // no wire in the face
1521               hasNonQuadr = Standard_True;
1522               break;
1523             }
1524             TopoDS_Shape aWire = wires.Current();
1525             wires.Next();
1526             if (wires.More()) {
1527               // multiple wires in the face
1528               hasNonQuadr = Standard_True;
1529               break;
1530             }
1531
1532             // Check number of edges in the face
1533             Standard_Integer nbEdges = 0;
1534             TopTools_MapOfShape mapEdges;
1535             TopExp_Explorer expW (aWire, TopAbs_EDGE);
1536             for (; expW.More(); expW.Next()) {
1537               if (mapEdges.Add(expW.Current())) {
1538                 nbEdges++;
1539                 if (nbEdges > 4) break;
1540               }
1541             }
1542             if (nbEdges != 4) {
1543               hasNonQuadr = Standard_True;
1544             }
1545           }
1546         }
1547
1548         if (nbFaces == 6 && !hasNonQuadr) {
1549           BLO.Append(theShape);
1550         } else {
1551           NOT.Append(theShape);
1552         }
1553       }
1554     }
1555     break;
1556   default:
1557     NOT.Append(theShape);
1558   }
1559 }
1560
1561 void AddBlocksFromOld (const TopoDS_Shape&   theShape,
1562                        TopTools_ListOfShape& BLO,
1563                        TopTools_ListOfShape& NOT,
1564                        TopTools_ListOfShape& DEG,
1565                        TopTools_ListOfShape& SEA)
1566 {
1567   TopAbs_ShapeEnum aType = theShape.ShapeType();
1568   switch (aType) {
1569   case TopAbs_COMPOUND:
1570   case TopAbs_COMPSOLID:
1571     {
1572       TopoDS_Iterator It (theShape);
1573       for (; It.More(); It.Next()) {
1574         AddBlocksFromOld(It.Value(), BLO, NOT, DEG, SEA);
1575       }
1576     }
1577     break;
1578   case TopAbs_SOLID:
1579     {
1580       TopTools_MapOfShape mapFaces;
1581       TopExp_Explorer expF (theShape, TopAbs_FACE);
1582       Standard_Integer nbFaces = 0;
1583       Standard_Boolean hasNonQuadr = Standard_False;
1584       Standard_Boolean hasDegenerated = Standard_False;
1585       Standard_Boolean hasSeam = Standard_False;
1586       for (; expF.More(); expF.Next()) {
1587         if (mapFaces.Add(expF.Current())) {
1588           nbFaces++;
1589           if (nbFaces > 6) break;
1590
1591           // Check number of edges in the face
1592           Standard_Integer nbEdges = 0;
1593           TopTools_MapOfShape mapEdges;
1594
1595           // get wire
1596           TopoDS_Shape aF = expF.Current();
1597           TopExp_Explorer wires (aF, TopAbs_WIRE);
1598           if (!wires.More()) {
1599             // no wire in the face
1600             hasNonQuadr = Standard_True;
1601             break;
1602           }
1603           TopoDS_Shape aWire = wires.Current();
1604           wires.Next();
1605           if (wires.More()) {
1606             // multiple wires in the face
1607             hasNonQuadr = Standard_True;
1608             break;
1609           }
1610
1611           // iterate on wire
1612           BRepTools_WireExplorer aWE (TopoDS::Wire(aWire), TopoDS::Face(aF));
1613           for (; aWE.More(); aWE.Next(), nbEdges++) {
1614             if (BRep_Tool::Degenerated(aWE.Current())) {
1615               // degenerated edge found
1616               hasDegenerated = Standard_True;
1617 //              break;
1618             }
1619             if (mapEdges.Contains(aWE.Current())) {
1620               // seam edge found
1621               hasSeam = Standard_True;
1622 //              break;
1623             }
1624             mapEdges.Add(aWE.Current());
1625           }
1626           if (nbEdges != 4) {
1627             hasNonQuadr = Standard_True;
1628           }
1629         }
1630       }
1631       if (nbFaces == 6) {
1632         if (hasDegenerated || hasSeam) {
1633           if (hasDegenerated) {
1634             DEG.Append(theShape);
1635           }
1636           if (hasSeam) {
1637             SEA.Append(theShape);
1638           }
1639         } else if (hasNonQuadr) {
1640           NOT.Append(theShape);
1641         } else {
1642           BLO.Append(theShape);
1643         }
1644       } else {
1645         NOT.Append(theShape);
1646       }
1647     }
1648     break;
1649   default:
1650     NOT.Append(theShape);
1651   }
1652 }
1653
1654 #define REL_NOT_CONNECTED 0
1655 #define REL_OK            1
1656 #define REL_NOT_GLUED     2
1657 #define REL_COLLISION_VV  3
1658 #define REL_COLLISION_FF  4
1659 #define REL_COLLISION_EE  5
1660 #define REL_UNKNOWN       6
1661
1662 Standard_Integer BlocksRelation (const TopoDS_Shape& theBlock1,
1663                                  const TopoDS_Shape& theBlock2)
1664 {
1665   // Compare bounding boxes before calling BRepExtrema_DistShapeShape
1666   Standard_Real Xmin1, Ymin1, Zmin1, Xmax1, Ymax1, Zmax1;
1667   Standard_Real Xmin2, Ymin2, Zmin2, Xmax2, Ymax2, Zmax2;
1668   Bnd_Box B1, B2;
1669   BRepBndLib::Add(theBlock1, B1);
1670   BRepBndLib::Add(theBlock2, B2);
1671   B1.Get(Xmin1, Ymin1, Zmin1, Xmax1, Ymax1, Zmax1);
1672   B2.Get(Xmin2, Ymin2, Zmin2, Xmax2, Ymax2, Zmax2);
1673   if (Xmax2 < Xmin1 || Xmax1 < Xmin2 ||
1674       Ymax2 < Ymin1 || Ymax1 < Ymin2 ||
1675       Zmax2 < Zmin1 || Zmax1 < Zmin2) {
1676     return REL_NOT_CONNECTED;
1677   }
1678
1679   BRepExtrema_DistShapeShape dst (theBlock1, theBlock2);
1680   if (!dst.IsDone()) {
1681     return REL_UNKNOWN;
1682   }
1683
1684   if (dst.Value() > Precision::Confusion()) {
1685     return REL_NOT_CONNECTED;
1686   }
1687
1688   if (dst.InnerSolution()) {
1689     return REL_COLLISION_VV;
1690   }
1691
1692   Standard_Integer nbSol = dst.NbSolution();
1693   Standard_Integer relation = REL_OK;
1694   Standard_Integer nbVerts = 0;
1695   Standard_Integer nbEdges = 0;
1696   Standard_Integer sol = 1;
1697   for (; sol <= nbSol; sol++) {
1698     BRepExtrema_SupportType supp1 = dst.SupportTypeShape1(sol);
1699     BRepExtrema_SupportType supp2 = dst.SupportTypeShape2(sol);
1700     if (supp1 == BRepExtrema_IsVertex && supp2 == BRepExtrema_IsVertex) {
1701       nbVerts++;
1702     } else if (supp1 == BRepExtrema_IsInFace || supp2 == BRepExtrema_IsInFace) {
1703       return REL_COLLISION_FF;
1704     } else if (supp1 == BRepExtrema_IsOnEdge && supp2 == BRepExtrema_IsOnEdge) {
1705       nbEdges++;
1706     } else if ((supp1 == BRepExtrema_IsOnEdge && supp2 == BRepExtrema_IsVertex) ||
1707                (supp2 == BRepExtrema_IsOnEdge && supp1 == BRepExtrema_IsVertex)) {
1708       relation = REL_COLLISION_EE;
1709     } else {
1710     }
1711   }
1712
1713   if (relation != REL_OK) {
1714     return relation;
1715   }
1716
1717   TColStd_Array1OfInteger vertSol (1, nbVerts);
1718   TopTools_Array1OfShape V1 (1, nbVerts);
1719   TopTools_Array1OfShape V2 (1, nbVerts);
1720   Standard_Integer ivs = 0;
1721   for (sol = 1; sol <= nbSol; sol++) {
1722     if (dst.SupportTypeShape1(sol) == BRepExtrema_IsVertex &&
1723         dst.SupportTypeShape2(sol) == BRepExtrema_IsVertex) {
1724       TopoDS_Vertex Vcur = TopoDS::Vertex(dst.SupportOnShape1(sol));
1725       // Check, that this vertex is far enough from other solution vertices.
1726       Standard_Integer ii = 1;
1727       for (; ii <= ivs; ii++) {
1728         if (BRepTools::Compare(TopoDS::Vertex(V1(ii)), Vcur)) {
1729           continue;
1730         }
1731       }
1732       ivs++;
1733       vertSol(ivs) = sol;
1734       V1(ivs) = Vcur;
1735       V2(ivs) = dst.SupportOnShape2(sol);
1736     }
1737   }
1738
1739   // As we deal only with quadrangles,
1740   // 2, 3 or 4 vertex solutions can be found.
1741   if (ivs <= 1) {
1742     if (nbEdges > 0) {
1743       return REL_COLLISION_FF;
1744     }
1745     return REL_NOT_CONNECTED;
1746   }
1747   if (ivs > 4) {
1748     return REL_UNKNOWN;
1749   }
1750
1751   // Check sharing of coincident entities.
1752   if (ivs == 2 || ivs == 3) {
1753     // Map vertices and edges of the blocks
1754     TopTools_IndexedDataMapOfShapeListOfShape MVE1, MVE2;
1755     GEOMImpl_Block6Explorer::MapShapesAndAncestors
1756       (theBlock1, TopAbs_VERTEX, TopAbs_EDGE, MVE1);
1757     GEOMImpl_Block6Explorer::MapShapesAndAncestors
1758       (theBlock2, TopAbs_VERTEX, TopAbs_EDGE, MVE2);
1759
1760     if (ivs == 2) {
1761       // Find common edge
1762       TopoDS_Shape anEdge1, anEdge2;
1763       GEOMImpl_Block6Explorer::FindEdge(anEdge1, V1(1), V1(2), MVE1);
1764       if (anEdge1.IsNull()) return REL_UNKNOWN;
1765
1766       GEOMImpl_Block6Explorer::FindEdge(anEdge2, V2(1), V2(2), MVE2);
1767       if (anEdge2.IsNull()) return REL_UNKNOWN;
1768
1769       if (!anEdge1.IsSame(anEdge2)) return REL_NOT_GLUED;
1770
1771     } else { // ivs == 3
1772       // Find common edges
1773       Standard_Integer e1_v1 = 1;
1774       Standard_Integer e1_v2 = 2;
1775       Standard_Integer e2_v1 = 3;
1776       Standard_Integer e2_v2 = 1;
1777
1778       TopoDS_Shape anEdge11, anEdge12;
1779       GEOMImpl_Block6Explorer::FindEdge(anEdge11, V1(e1_v1), V1(e1_v2), MVE1);
1780       if (anEdge11.IsNull()) {
1781         e1_v2 = 3;
1782         e2_v1 = 2;
1783         GEOMImpl_Block6Explorer::FindEdge(anEdge11, V1(e1_v1), V1(e1_v2), MVE1);
1784         if (anEdge11.IsNull()) return REL_UNKNOWN;
1785       }
1786       GEOMImpl_Block6Explorer::FindEdge(anEdge12, V1(e2_v1), V1(e2_v2), MVE1);
1787       if (anEdge12.IsNull()) {
1788         e2_v2 = 5 - e2_v1;
1789         GEOMImpl_Block6Explorer::FindEdge(anEdge12, V1(e2_v1), V1(e2_v2), MVE1);
1790         if (anEdge12.IsNull()) return REL_UNKNOWN;
1791       }
1792
1793       TopoDS_Shape anEdge21, anEdge22;
1794       GEOMImpl_Block6Explorer::FindEdge(anEdge21, V2(e1_v1), V2(e1_v2), MVE2);
1795       if (anEdge21.IsNull()) return REL_UNKNOWN;
1796       GEOMImpl_Block6Explorer::FindEdge(anEdge22, V2(e2_v1), V2(e2_v2), MVE2);
1797       if (anEdge22.IsNull()) return REL_UNKNOWN;
1798
1799       // Check of edges coincidence (with some precision) have to be done here
1800       // if (!anEdge11.IsEqual(anEdge21)) return REL_UNKNOWN;
1801       // if (!anEdge12.IsEqual(anEdge22)) return REL_UNKNOWN;
1802
1803       // Check of edges sharing
1804       if (!anEdge11.IsSame(anEdge21)) return REL_NOT_GLUED;
1805       if (!anEdge12.IsSame(anEdge22)) return REL_NOT_GLUED;
1806     }
1807   }
1808
1809   if (ivs == 4) {
1810     // Map vertices and faces of the blocks
1811     TopTools_IndexedDataMapOfShapeListOfShape MVF1, MVF2;
1812     GEOMImpl_Block6Explorer::MapShapesAndAncestors
1813       (theBlock1, TopAbs_VERTEX, TopAbs_FACE, MVF1);
1814     GEOMImpl_Block6Explorer::MapShapesAndAncestors
1815       (theBlock2, TopAbs_VERTEX, TopAbs_FACE, MVF2);
1816
1817     TopoDS_Shape aFace1, aFace2;
1818     GEOMImpl_Block6Explorer::FindFace(aFace1, V1(1), V1(2), V1(3), V1(4), MVF1);
1819     if (aFace1.IsNull()) return REL_UNKNOWN;
1820     GEOMImpl_Block6Explorer::FindFace(aFace2, V2(1), V2(2), V2(3), V2(4), MVF2);
1821     if (aFace2.IsNull()) return REL_UNKNOWN;
1822
1823     // Check of faces coincidence (with some precision) have to be done here
1824     // if (!aFace1.IsEqual(aFace2)) return REL_UNKNOWN;
1825
1826     // Check of faces sharing
1827     if (!aFace1.IsSame(aFace2)) return REL_NOT_GLUED;
1828   }
1829
1830   return REL_OK;
1831 }
1832
1833 void FindConnected (const Standard_Integer         theBlockIndex,
1834                     const TColStd_Array2OfInteger& theRelations,
1835                     TColStd_MapOfInteger&          theProcessedMap,
1836                     TColStd_MapOfInteger&          theConnectedMap)
1837 {
1838   theConnectedMap.Add(theBlockIndex);
1839   theProcessedMap.Add(theBlockIndex);
1840
1841   Standard_Integer nbBlocks = theRelations.ColLength();
1842   Standard_Integer col = 1;
1843   for (; col <= nbBlocks; col++) {
1844     if (theRelations(theBlockIndex, col) == REL_OK ||
1845         theRelations(theBlockIndex, col) == REL_NOT_GLUED) {
1846       if (!theProcessedMap.Contains(col)) {
1847         FindConnected(col, theRelations, theProcessedMap, theConnectedMap);
1848       }
1849     }
1850   }
1851 }
1852
1853 Standard_Boolean HasAnyConnection (const Standard_Integer         theBlockIndex,
1854                                    const TColStd_MapOfInteger&    theWith,
1855                                    const TColStd_Array2OfInteger& theRelations,
1856                                    TColStd_MapOfInteger&          theProcessedMap)
1857 {
1858   theProcessedMap.Add(theBlockIndex);
1859
1860   Standard_Integer nbBlocks = theRelations.ColLength();
1861   Standard_Integer col = 1;
1862   for (; col <= nbBlocks; col++) {
1863     if (theRelations(theBlockIndex, col) != REL_NOT_CONNECTED) {
1864       if (!theProcessedMap.Contains(col)) {
1865         if (theWith.Contains(col))
1866           return Standard_True;
1867         if (HasAnyConnection(col, theWith, theRelations, theProcessedMap))
1868           return Standard_True;
1869       }
1870     }
1871   }
1872
1873   return Standard_False;
1874 }
1875
1876 //=============================================================================
1877 /*!
1878  *  CheckCompoundOfBlocksOld
1879  */
1880 //=============================================================================
1881 Standard_Boolean GEOMImpl_IBlocksOperations::CheckCompoundOfBlocksOld
1882                                                 (Handle(GEOM_Object) theCompound,
1883                                                  list<BCError>&      theErrors)
1884 {
1885   SetErrorCode(KO);
1886
1887   if (theCompound.IsNull()) return Standard_False;
1888   TopoDS_Shape aBlockOrComp = theCompound->GetValue();
1889
1890   Standard_Boolean isCompOfBlocks = Standard_True;
1891
1892   // Map sub-shapes and their indices
1893   TopTools_IndexedMapOfShape anIndices;
1894   TopExp::MapShapes(aBlockOrComp, anIndices);
1895
1896   // 1. Report non-blocks
1897   TopTools_ListOfShape NOT; // Not blocks
1898   TopTools_ListOfShape DEG; // Hexahedral solids, having degenerated edges
1899   TopTools_ListOfShape SEA; // Hexahedral solids, having seam edges
1900   TopTools_ListOfShape BLO; // All blocks from the given compound
1901   AddBlocksFromOld(aBlockOrComp, BLO, NOT, DEG, SEA);
1902
1903   if (NOT.Extent() > 0) {
1904     isCompOfBlocks = Standard_False;
1905     BCError anErr;
1906     anErr.error = NOT_BLOCK;
1907     TopTools_ListIteratorOfListOfShape it (NOT);
1908     for (; it.More(); it.Next()) {
1909       anErr.incriminated.push_back(anIndices.FindIndex(it.Value()));
1910     }
1911     theErrors.push_back(anErr);
1912   }
1913
1914   if (DEG.Extent() > 0 || SEA.Extent() > 0) {
1915     isCompOfBlocks = Standard_False;
1916     BCError anErr;
1917     anErr.error = EXTRA_EDGE;
1918
1919     TopTools_ListIteratorOfListOfShape itDEG (DEG);
1920     for (; itDEG.More(); itDEG.Next()) {
1921       anErr.incriminated.push_back(anIndices.FindIndex(itDEG.Value()));
1922     }
1923
1924     TopTools_ListIteratorOfListOfShape itSEA (SEA);
1925     for (; itSEA.More(); itSEA.Next()) {
1926       anErr.incriminated.push_back(anIndices.FindIndex(itSEA.Value()));
1927     }
1928
1929     theErrors.push_back(anErr);
1930   }
1931
1932   Standard_Integer nbBlocks = BLO.Extent();
1933   if (nbBlocks == 0) {
1934     isCompOfBlocks = Standard_False;
1935     SetErrorCode(OK);
1936     return isCompOfBlocks;
1937   }
1938   if (nbBlocks == 1) {
1939     SetErrorCode(OK);
1940     return isCompOfBlocks;
1941   }
1942
1943   // Convert list of blocks into array for easy and fast access
1944   Standard_Integer ibl = 1;
1945   TopTools_Array1OfShape aBlocks (1, nbBlocks);
1946   TopTools_ListIteratorOfListOfShape BLOit (BLO);
1947   for (; BLOit.More(); BLOit.Next(), ibl++) {
1948     aBlocks.SetValue(ibl, BLOit.Value());
1949   }
1950
1951   // 2. Find relations between all blocks,
1952   //    report connection errors (NOT_GLUED and INVALID_CONNECTION)
1953   TColStd_Array2OfInteger aRelations (1, nbBlocks, 1, nbBlocks);
1954   aRelations.Init(REL_NOT_CONNECTED);
1955
1956   Standard_Integer row = 1;
1957   for (row = 1; row <= nbBlocks; row++) {
1958     TopoDS_Shape aBlock = aBlocks.Value(row);
1959
1960     Standard_Integer col = row + 1;
1961     for (; col <= nbBlocks; col++) {
1962       Standard_Integer aRel = BlocksRelation(aBlock, aBlocks.Value(col));
1963       if (aRel != REL_NOT_CONNECTED) {
1964         aRelations.SetValue(row, col, aRel);
1965         aRelations.SetValue(col, row, aRel);
1966         if (aRel == REL_NOT_GLUED) {
1967           // report connection error
1968           isCompOfBlocks = Standard_False;
1969           BCError anErr;
1970           anErr.error = NOT_GLUED;
1971           anErr.incriminated.push_back(anIndices.FindIndex(aBlocks.Value(row)));
1972           anErr.incriminated.push_back(anIndices.FindIndex(aBlocks.Value(col)));
1973           theErrors.push_back(anErr);
1974         } else if (aRel == REL_COLLISION_VV ||
1975                    aRel == REL_COLLISION_FF ||
1976                    aRel == REL_COLLISION_EE ||
1977                    aRel == REL_UNKNOWN) {
1978           // report connection error
1979           isCompOfBlocks = Standard_False;
1980           BCError anErr;
1981           anErr.error = INVALID_CONNECTION;
1982           anErr.incriminated.push_back(anIndices.FindIndex(aBlocks.Value(row)));
1983           anErr.incriminated.push_back(anIndices.FindIndex(aBlocks.Value(col)));
1984           theErrors.push_back(anErr);
1985         } else {
1986         }
1987       }
1988     }
1989   }
1990
1991   // 3. Find largest set of connected (good connection or not glued) blocks
1992   TColStd_MapOfInteger aProcessedMap;
1993   TColStd_MapOfInteger aLargestSet;
1994   TColStd_MapOfInteger aCurrentSet;
1995   for (ibl = 1; ibl <= nbBlocks; ibl++) {
1996     if (!aProcessedMap.Contains(ibl)) {
1997       aCurrentSet.Clear();
1998       FindConnected(ibl, aRelations, aProcessedMap, aCurrentSet);
1999       if (aCurrentSet.Extent() > aLargestSet.Extent()) {
2000         aLargestSet = aCurrentSet;
2001       }
2002     }
2003   }
2004
2005   // 4. Report all blocks, isolated from <aLargestSet>
2006   BCError anErr;
2007   anErr.error = NOT_CONNECTED;
2008   Standard_Boolean hasIsolated = Standard_False;
2009   for (ibl = 1; ibl <= nbBlocks; ibl++) {
2010     if (!aLargestSet.Contains(ibl)) {
2011       aProcessedMap.Clear();
2012       if (!HasAnyConnection(ibl, aLargestSet, aRelations, aProcessedMap)) {
2013         // report connection absence
2014         hasIsolated = Standard_True;
2015         anErr.incriminated.push_back(anIndices.FindIndex(aBlocks.Value(ibl)));
2016       }
2017     }
2018   }
2019   if (hasIsolated) {
2020     isCompOfBlocks = Standard_False;
2021     theErrors.push_back(anErr);
2022   }
2023
2024   SetErrorCode(OK);
2025   return isCompOfBlocks;
2026 }
2027
2028 //=============================================================================
2029 /*!
2030  *  PrintBCErrors
2031  */
2032 //=============================================================================
2033 TCollection_AsciiString GEOMImpl_IBlocksOperations::PrintBCErrors
2034                                                 (Handle(GEOM_Object)  theCompound,
2035                                                  const list<BCError>& theErrors)
2036 {
2037   TCollection_AsciiString aDescr;
2038
2039   list<BCError>::const_iterator errIt = theErrors.begin();
2040   int i = 0;
2041   for (; errIt != theErrors.end(); i++, errIt++) {
2042     BCError errStruct = *errIt;
2043
2044     switch (errStruct.error) {
2045     case NOT_BLOCK:
2046       aDescr += "\n\tNot a Blocks: ";
2047       break;
2048     case EXTRA_EDGE:
2049       aDescr += "\n\tHexahedral solids with degenerated and/or seam edges: ";
2050       break;
2051     case INVALID_CONNECTION:
2052       aDescr += "\n\tInvalid connection between two blocks: ";
2053       break;
2054     case NOT_CONNECTED:
2055       aDescr += "\n\tBlocks, not connected with main body: ";
2056       break;
2057     case NOT_GLUED:
2058       aDescr += "\n\tNot glued blocks: ";
2059       break;
2060     default:
2061       break;
2062     }
2063
2064     list<int> sshList = errStruct.incriminated;
2065     list<int>::iterator sshIt = sshList.begin();
2066     int jj = 0;
2067     for (; sshIt != sshList.end(); jj++, sshIt++) {
2068       if (jj > 0)
2069         aDescr += ", ";
2070       aDescr += TCollection_AsciiString(*sshIt);
2071     }
2072   }
2073
2074   return aDescr;
2075 }
2076
2077 //=============================================================================
2078 /*!
2079  *  CheckCompoundOfBlocks
2080  */
2081 //=============================================================================
2082 Standard_Boolean GEOMImpl_IBlocksOperations::CheckCompoundOfBlocks
2083                                               (Handle(GEOM_Object) theCompound,
2084                                                list<BCError>&      theErrors)
2085 {
2086   SetErrorCode(KO);
2087
2088   if (theCompound.IsNull()) return Standard_False;
2089   TopoDS_Shape aBlockOrComp = theCompound->GetValue();
2090
2091   Standard_Boolean isCompOfBlocks = Standard_True;
2092
2093   // Map sub-shapes and their indices
2094   TopTools_IndexedMapOfShape anIndices;
2095   TopExp::MapShapes(aBlockOrComp, anIndices);
2096
2097   // 1. Separate blocks from non-blocks
2098   TopTools_ListOfShape NOT; // Not blocks
2099   TopTools_ListOfShape EXT; // Hexahedral solids, having degenerated and/or seam edges
2100   TopTools_ListOfShape BLO; // All blocks from the given compound
2101   AddBlocksFrom(aBlockOrComp, BLO, NOT, EXT);
2102
2103   // Report non-blocks
2104   if (NOT.Extent() > 0) {
2105     isCompOfBlocks = Standard_False;
2106     BCError anErr;
2107     anErr.error = NOT_BLOCK;
2108     TopTools_ListIteratorOfListOfShape it (NOT);
2109     for (; it.More(); it.Next()) {
2110       anErr.incriminated.push_back(anIndices.FindIndex(it.Value()));
2111     }
2112     theErrors.push_back(anErr);
2113   }
2114
2115   // Report solids, having degenerated and/or seam edges
2116   if (EXT.Extent() > 0) {
2117     isCompOfBlocks = Standard_False;
2118     BCError anErr;
2119     anErr.error = EXTRA_EDGE;
2120     TopTools_ListIteratorOfListOfShape it (EXT);
2121     for (; it.More(); it.Next()) {
2122       anErr.incriminated.push_back(anIndices.FindIndex(it.Value()));
2123     }
2124     theErrors.push_back(anErr);
2125   }
2126
2127   Standard_Integer nbBlocks = BLO.Extent();
2128   if (nbBlocks == 0) {
2129     isCompOfBlocks = Standard_False;
2130     SetErrorCode(OK);
2131     return isCompOfBlocks;
2132   }
2133   if (nbBlocks == 1) {
2134     SetErrorCode(OK);
2135     return isCompOfBlocks;
2136   }
2137
2138   // Prepare data for 2. and 3.
2139   TColStd_Array2OfInteger aRelations (1, nbBlocks, 1, nbBlocks);
2140   aRelations.Init(REL_NOT_CONNECTED);
2141
2142   TopTools_IndexedMapOfShape mapBlocks;
2143
2144   BRep_Builder BB;
2145   TopoDS_Compound aComp;
2146   BB.MakeCompound(aComp);
2147
2148   TopTools_ListIteratorOfListOfShape BLOit (BLO);
2149   for (; BLOit.More(); BLOit.Next()) {
2150     mapBlocks.Add(BLOit.Value());
2151     BB.Add(aComp, BLOit.Value());
2152   }
2153
2154   // 2. Find glued blocks (having shared faces)
2155   TopTools_IndexedDataMapOfShapeListOfShape mapFaceBlocks;
2156   GEOMImpl_Block6Explorer::MapShapesAndAncestors
2157     (aComp, TopAbs_FACE, TopAbs_SOLID, mapFaceBlocks);
2158
2159   Standard_Integer prevInd = 0, curInd = 0;
2160   Standard_Integer ind = 1, nbFaces = mapFaceBlocks.Extent();
2161   for (; ind <= nbFaces; ind++) {
2162     const TopTools_ListOfShape& aGluedBlocks = mapFaceBlocks.FindFromIndex(ind);
2163     if (aGluedBlocks.Extent() > 1) { // Shared face found
2164       TopTools_ListIteratorOfListOfShape aGluedBlocksIt (aGluedBlocks);
2165       TopoDS_Shape prevBlock, curBlock;
2166       for (; aGluedBlocksIt.More(); aGluedBlocksIt.Next()) {
2167         curBlock = aGluedBlocksIt.Value();
2168         if (!prevBlock.IsNull()) {
2169           prevInd = mapBlocks.FindIndex(prevBlock);
2170           curInd  = mapBlocks.FindIndex(curBlock);
2171           aRelations.SetValue(prevInd, curInd, REL_OK);
2172           aRelations.SetValue(curInd, prevInd, REL_OK);
2173         }
2174         prevBlock = curBlock;
2175       }
2176     }
2177   }
2178
2179   // 3. Find not glued blocks
2180   GEOMAlgo_GlueAnalyser aGD; 
2181
2182   aGD.SetShape(aComp);
2183   aGD.SetTolerance(Precision::Confusion());
2184   aGD.SetCheckGeometry(Standard_True);
2185   aGD.Perform();
2186
2187   Standard_Integer iErr, iWrn;
2188   iErr = aGD.ErrorStatus();
2189   if (iErr) {
2190     SetErrorCode("Error in GEOMAlgo_GlueAnalyser");
2191     return isCompOfBlocks;
2192   }
2193   iWrn = aGD.WarningStatus();
2194   if (iWrn) {
2195     MESSAGE("Warning in GEOMAlgo_GlueAnalyser");
2196   }
2197
2198   // Report not glued blocks
2199   if (aGD.HasSolidsToGlue()) {
2200     isCompOfBlocks = Standard_False;
2201     Standard_Integer aSx1Ind, aSx2Ind;
2202
2203     const GEOMAlgo_ListOfCoupleOfShapes& aLCS = aGD.SolidsToGlue();
2204     GEOMAlgo_ListIteratorOfListOfCoupleOfShapes aItCS (aLCS);
2205     for (; aItCS.More(); aItCS.Next()) {
2206       const GEOMAlgo_CoupleOfShapes& aCS = aItCS.Value();
2207       const TopoDS_Shape& aSx1 = aCS.Shape1();
2208       const TopoDS_Shape& aSx2 = aCS.Shape2();
2209
2210       aSx1Ind = mapBlocks.FindIndex(aSx1);
2211       aSx2Ind = mapBlocks.FindIndex(aSx2);
2212       aRelations.SetValue(aSx1Ind, aSx2Ind, NOT_GLUED);
2213       aRelations.SetValue(aSx2Ind, aSx1Ind, NOT_GLUED);
2214
2215       BCError anErr;
2216       anErr.error = NOT_GLUED;
2217       anErr.incriminated.push_back(anIndices.FindIndex(aSx1));
2218       anErr.incriminated.push_back(anIndices.FindIndex(aSx2));
2219       theErrors.push_back(anErr);
2220     }
2221   }
2222
2223   // 4. Find largest set of connected (good connection or not glued) blocks
2224   Standard_Integer ibl = 1;
2225   TColStd_MapOfInteger aProcessedMap;
2226   TColStd_MapOfInteger aLargestSet;
2227   TColStd_MapOfInteger aCurrentSet;
2228   for (ibl = 1; ibl <= nbBlocks; ibl++) {
2229     if (!aProcessedMap.Contains(ibl)) {
2230       aCurrentSet.Clear();
2231       FindConnected(ibl, aRelations, aProcessedMap, aCurrentSet);
2232       if (aCurrentSet.Extent() > aLargestSet.Extent()) {
2233         aLargestSet = aCurrentSet;
2234       }
2235     }
2236   }
2237
2238   // 5. Report all blocks, isolated from <aLargestSet>
2239   BCError anErr;
2240   anErr.error = NOT_CONNECTED;
2241   Standard_Boolean hasIsolated = Standard_False;
2242   for (ibl = 1; ibl <= nbBlocks; ibl++) {
2243     if (!aLargestSet.Contains(ibl)) {
2244       aProcessedMap.Clear();
2245       if (!HasAnyConnection(ibl, aLargestSet, aRelations, aProcessedMap)) {
2246         // report connection absence
2247         hasIsolated = Standard_True;
2248         anErr.incriminated.push_back(anIndices.FindIndex(mapBlocks.FindKey(ibl)));
2249       }
2250     }
2251   }
2252   if (hasIsolated) {
2253     isCompOfBlocks = Standard_False;
2254     theErrors.push_back(anErr);
2255   }
2256
2257   SetErrorCode(OK);
2258   return isCompOfBlocks;
2259 }
2260
2261 //=============================================================================
2262 /*!
2263  *  RemoveExtraEdges
2264  */
2265 //=============================================================================
2266 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::RemoveExtraEdges
2267                                              (Handle(GEOM_Object) theObject)
2268 {
2269   SetErrorCode(KO);
2270
2271   if (theObject.IsNull()) return NULL;
2272
2273   Handle(GEOM_Function) aLastFunction = theObject->GetLastFunction();
2274   if (aLastFunction.IsNull()) return NULL; //There is no function which creates an object to be fixed
2275
2276   //Add a new Copy object
2277   Handle(GEOM_Object) aCopy = GetEngine()->AddObject(GetDocID(), GEOM_COPY);
2278
2279   //Add a function
2280   Handle(GEOM_Function) aFunction =
2281     aCopy->AddFunction(GEOMImpl_BlockDriver::GetID(), BLOCK_REMOVE_EXTRA);
2282
2283   //Check if the function is set correctly
2284   if (aFunction->GetDriverGUID() != GEOMImpl_BlockDriver::GetID()) return NULL;
2285
2286   GEOMImpl_IBlockTrsf aTI (aFunction);
2287   aTI.SetOriginal(aLastFunction);
2288
2289   //Compute the fixed shape
2290   try {
2291     if (!GetSolver()->ComputeFunction(aFunction)) {
2292       SetErrorCode("Block driver failed to remove extra edges of the given shape");
2293       return NULL;
2294     }
2295   }
2296   catch (Standard_Failure) {
2297     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
2298     SetErrorCode(aFail->GetMessageString());
2299     return NULL;
2300   }
2301
2302   //Make a Python command
2303   GEOM::TPythonDump(aFunction) << aCopy
2304     << " = geompy.RemoveExtraEdges(" << theObject << ")";
2305
2306   SetErrorCode(OK);
2307   return aCopy;
2308 }
2309
2310 //=============================================================================
2311 /*!
2312  *  CheckAndImprove
2313  */
2314 //=============================================================================
2315 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::CheckAndImprove
2316                                              (Handle(GEOM_Object) theObject)
2317 {
2318   SetErrorCode(KO);
2319
2320   if (theObject.IsNull()) return NULL;
2321
2322   Handle(GEOM_Function) aLastFunction = theObject->GetLastFunction();
2323   if (aLastFunction.IsNull()) return NULL; //There is no function which creates an object to be fixed
2324
2325   //Add a new Copy object
2326   Handle(GEOM_Object) aCopy = GetEngine()->AddObject(GetDocID(), GEOM_COPY);
2327
2328   //Add a function
2329   Handle(GEOM_Function) aFunction =
2330     aCopy->AddFunction(GEOMImpl_BlockDriver::GetID(), BLOCK_COMPOUND_IMPROVE);
2331
2332   //Check if the function is set correctly
2333   if (aFunction->GetDriverGUID() != GEOMImpl_BlockDriver::GetID()) return NULL;
2334
2335   GEOMImpl_IBlockTrsf aTI (aFunction);
2336   aTI.SetOriginal(aLastFunction);
2337
2338   //Compute the fixed shape
2339   try {
2340     if (!GetSolver()->ComputeFunction(aFunction)) {
2341       SetErrorCode("Block driver failed to improve the given blocks compound");
2342       return NULL;
2343     }
2344   }
2345   catch (Standard_Failure) {
2346     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
2347     SetErrorCode(aFail->GetMessageString());
2348     return NULL;
2349   }
2350
2351   //Make a Python command
2352   GEOM::TPythonDump(aFunction) << aCopy
2353     << " = geompy.CheckAndImprove(" << theObject << ")";
2354
2355   SetErrorCode(OK);
2356   return aCopy;
2357 }
2358
2359 //=============================================================================
2360 /*!
2361  *  ExplodeCompoundOfBlocks
2362  */
2363 //=============================================================================
2364 Handle(TColStd_HSequenceOfTransient) GEOMImpl_IBlocksOperations::ExplodeCompoundOfBlocks
2365                                                 (Handle(GEOM_Object)    theCompound,
2366                                                  const Standard_Integer theMinNbFaces,
2367                                                  const Standard_Integer theMaxNbFaces)
2368 {
2369   SetErrorCode(KO);
2370
2371   if (theCompound.IsNull()) return NULL;
2372   TopoDS_Shape aBlockOrComp = theCompound->GetValue();
2373   if (aBlockOrComp.IsNull()) return NULL;
2374
2375   Handle(TColStd_HSequenceOfTransient) aBlocks = new TColStd_HSequenceOfTransient;
2376   Handle(GEOM_Object) anObj;
2377   Handle(GEOM_Function) aFunction;
2378
2379   TopTools_MapOfShape mapShape;
2380   TCollection_AsciiString anAsciiList, anEntry;
2381
2382   // Map shapes
2383   TopTools_IndexedMapOfShape anIndices;
2384   TopExp::MapShapes(aBlockOrComp, anIndices);
2385   Handle(TColStd_HArray1OfInteger) anArray;
2386
2387   // Explode
2388   try {
2389     TopExp_Explorer exp (aBlockOrComp, TopAbs_SOLID);
2390     for (; exp.More(); exp.Next()) {
2391       if (mapShape.Add(exp.Current())) {
2392         TopoDS_Shape aSolid = exp.Current();
2393
2394         TopTools_MapOfShape mapFaces;
2395         TopExp_Explorer expF (aSolid, TopAbs_FACE);
2396         Standard_Integer nbFaces = 0;
2397         for (; expF.More(); expF.Next()) {
2398           if (mapFaces.Add(expF.Current())) {
2399             nbFaces++;
2400           }
2401         }
2402
2403         if (theMinNbFaces <= nbFaces && nbFaces <= theMaxNbFaces) {
2404           anArray = new TColStd_HArray1OfInteger(1,1);
2405           anArray->SetValue(1, anIndices.FindIndex(aSolid));
2406           anObj = GetEngine()->AddSubShape(theCompound, anArray);
2407           aBlocks->Append(anObj);
2408
2409           //Make a Python command
2410           TDF_Tool::Entry(anObj->GetEntry(), anEntry);
2411           anAsciiList += anEntry + ", ";
2412         }
2413       }
2414     }
2415   }
2416   catch (Standard_Failure) {
2417     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
2418     SetErrorCode(aFail->GetMessageString());
2419     return aBlocks;
2420   }
2421
2422   if (aBlocks->IsEmpty()) {
2423     SetErrorCode("There are no specified blocks in the given shape");
2424     return aBlocks;
2425   }
2426
2427   anAsciiList.Trunc(anAsciiList.Length() - 2);
2428
2429   //The explode doesn't change object so no new function is required.
2430   aFunction = theCompound->GetLastFunction();
2431
2432   //Make a Python command
2433   GEOM::TPythonDump(aFunction, /*append=*/true)
2434     << "[" << anAsciiList.ToCString() << "] = geompy.MakeBlockExplode("
2435     << theCompound << ", " << theMinNbFaces << ", " << theMaxNbFaces << ")";
2436
2437   SetErrorCode(OK);
2438   return aBlocks;
2439 }
2440
2441 //=============================================================================
2442 /*!
2443  *  GetBlockNearPoint
2444  */
2445 //=============================================================================
2446 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::GetBlockNearPoint
2447                                                 (Handle(GEOM_Object) theCompound,
2448                                                  Handle(GEOM_Object) thePoint)
2449 {
2450   SetErrorCode(KO);
2451
2452   //New object
2453   Handle(GEOM_Object) aResult;
2454
2455   // Arguments
2456   if (theCompound.IsNull() || thePoint.IsNull()) return NULL;
2457
2458   TopoDS_Shape aBlockOrComp = theCompound->GetValue();
2459   if (aBlockOrComp.IsNull()) {
2460     SetErrorCode("Compound is null");
2461     return NULL;
2462   }
2463   if (aBlockOrComp.ShapeType() != TopAbs_COMPOUND &&
2464       aBlockOrComp.ShapeType() != TopAbs_COMPSOLID) {
2465     SetErrorCode("Shape to find block in is not a compound");
2466     return NULL;
2467   }
2468
2469   TopoDS_Shape anArg = thePoint->GetValue();
2470   if (anArg.IsNull()) {
2471     SetErrorCode("Point is null");
2472     return NULL;
2473   }
2474   if (anArg.ShapeType() != TopAbs_VERTEX) {
2475     SetErrorCode("Shape for block identification is not a vertex");
2476     return NULL;
2477   }
2478
2479   //Compute the Block value
2480   try {
2481     TopoDS_Shape aShape;
2482
2483     TopoDS_Vertex aVert = TopoDS::Vertex(anArg);
2484     gp_Pnt aPnt = BRep_Tool::Pnt(aVert);
2485     Standard_Real PX, PY, PZ;
2486     aPnt.Coord(PX, PY, PZ);
2487
2488     // 1. Classify the point relatively each block
2489     Standard_Integer nearest = 2, nbFound = 0;
2490     TopTools_DataMapOfShapeInteger mapShapeDist;
2491     TopExp_Explorer exp (aBlockOrComp, TopAbs_SOLID);
2492     for (; exp.More(); exp.Next()) {
2493       TopoDS_Shape aSolid = exp.Current();
2494
2495       if (!mapShapeDist.IsBound(aSolid)) {
2496         Standard_Integer aDistance = 2;
2497
2498         // 1.a. Classify relatively Bounding box
2499         Standard_Real Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
2500         Bnd_Box BB;
2501         BRepBndLib::Add(aSolid, BB);
2502         BB.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
2503         if (PX < Xmin || Xmax < PX ||
2504             PY < Ymin || Ymax < PY ||
2505             PZ < Zmin || Zmax < PZ) {
2506           // OUT of bounding box
2507           aDistance = 1;
2508         } else {
2509           // 1.b. Classify relatively the solid itself
2510           BRepClass3d_SolidClassifier SC (aSolid, aPnt, Precision::Confusion());
2511           if (SC.State() == TopAbs_IN) {
2512             aDistance = -1;
2513           } else if (SC.State() == TopAbs_ON) {
2514             aDistance = 0;
2515           } else { // OUT
2516             aDistance = 1;
2517           }
2518         }
2519
2520         if (aDistance < nearest) {
2521           nearest = aDistance;
2522           aShape = aSolid;
2523           nbFound = 1;
2524
2525           // A first found block, containing the point inside, will be returned.
2526           // It is the solution, if there are no intersecting blocks in the compound.
2527           if (nearest == -1) break;
2528
2529         } else if (aDistance == nearest) {
2530           nbFound++;
2531         } else {
2532         }
2533
2534         mapShapeDist.Bind(aSolid, aDistance);
2535       } // if (!mapShapeDist.IsBound(aSolid))
2536     }
2537
2538     // 2. Define block, containing the point or having minimum distance to it
2539     if (nbFound > 1) {
2540       if (nearest == 0) {
2541         // The point is on boundary of some blocks and there are
2542         // no blocks, having the point inside their volume
2543         SetErrorCode("Multiple blocks near the given point are found");
2544         return NULL;
2545
2546       } else if (nearest == 1) {
2547         // The point is outside some blocks and there are
2548         // no blocks, having the point inside or on boundary.
2549         // We will get a nearest block
2550         Standard_Real minDist = RealLast();
2551         TopTools_DataMapIteratorOfDataMapOfShapeInteger mapShapeDistIter (mapShapeDist);
2552         for (; mapShapeDistIter.More(); mapShapeDistIter.Next()) {
2553           if (mapShapeDistIter.Value() == 1) {
2554             TopoDS_Shape aSolid = mapShapeDistIter.Key();
2555             BRepExtrema_DistShapeShape aDistTool (aVert, aSolid);
2556             if (!aDistTool.IsDone()) {
2557               SetErrorCode("Can not find a distance from the given point to one of blocks");
2558               return NULL;
2559             }
2560             Standard_Real aDist = aDistTool.Value();
2561             if (aDist < minDist) {
2562               minDist = aDist;
2563               aShape = aSolid;
2564             }
2565           }
2566         }
2567       } else { // nearest == -1
2568 //        // The point is inside some blocks.
2569 //        // We will get a block with nearest center
2570 //        Standard_Real minDist = RealLast();
2571 //        TopTools_DataMapIteratorOfDataMapOfShapeInteger mapShapeDistIter (mapShapeDist);
2572 //        for (; mapShapeDistIter.More(); mapShapeDistIter.Next()) {
2573 //          if (mapShapeDistIter.Value() == -1) {
2574 //            TopoDS_Shape aSolid = mapShapeDistIter.Key();
2575 //            GProp_GProps aSystem;
2576 //            BRepGProp::VolumeProperties(aSolid, aSystem);
2577 //            gp_Pnt aCenterMass = aSystem.CentreOfMass();
2578 //
2579 //            Standard_Real aDist = aCenterMass.Distance(aPnt);
2580 //            if (aDist < minDist) {
2581 //              minDist = aDist;
2582 //              aShape = aSolid;
2583 //            }
2584 //          }
2585 //        }
2586       }
2587     } // if (nbFound > 1)
2588
2589     if (nbFound == 0) {
2590       SetErrorCode("There are no blocks near the given point");
2591       return NULL;
2592     } else {
2593       TopTools_IndexedMapOfShape anIndices;
2594       TopExp::MapShapes(aBlockOrComp, anIndices);
2595       Handle(TColStd_HArray1OfInteger) anArray = new TColStd_HArray1OfInteger(1,1);
2596       anArray->SetValue(1, anIndices.FindIndex(aShape));
2597       aResult = GetEngine()->AddSubShape(theCompound, anArray);
2598     }
2599   }
2600   catch (Standard_Failure) {
2601     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
2602     SetErrorCode(aFail->GetMessageString());
2603     return NULL;
2604   }
2605
2606   Handle(GEOM_Function) aFunction = aResult->GetLastFunction();
2607
2608   //Make a Python command
2609   GEOM::TPythonDump(aFunction) << aResult << " = geompy.GetBlockNearPoint("
2610                                << theCompound << ", " << thePoint << ")";
2611
2612   SetErrorCode(OK);
2613   return aResult;
2614 }
2615
2616 //=============================================================================
2617 /*!
2618  *  GetBlockByParts
2619  */
2620 //=============================================================================
2621 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::GetBlockByParts
2622                       (Handle(GEOM_Object)                         theCompound,
2623                        const Handle(TColStd_HSequenceOfTransient)& theParts)
2624 {
2625   SetErrorCode(KO);
2626
2627   Handle(GEOM_Object) aResult;
2628
2629   if (theCompound.IsNull() || theParts.IsNull()) return NULL;
2630   TopoDS_Shape aBlockOrComp = theCompound->GetValue();
2631   if (aBlockOrComp.IsNull()) return NULL;
2632
2633   //Get the parts
2634   Standard_Integer argi, aLen = theParts->Length();
2635   TopTools_Array1OfShape anArgs (1, aLen);
2636   TCollection_AsciiString anEntry, aPartsDescr;
2637   for (argi = 1; argi <= aLen; argi++) {
2638     Handle(GEOM_Object) anObj = Handle(GEOM_Object)::DownCast(theParts->Value(argi));
2639     Handle(GEOM_Function) aRef = anObj->GetLastFunction();
2640     if (aRef.IsNull()) return NULL;
2641
2642     TopoDS_Shape anArg = aRef->GetValue();
2643     if (anArg.IsNull()) {
2644       SetErrorCode("Null shape is given as argument");
2645       return NULL;
2646     }
2647     anArgs(argi) = anArg;
2648
2649     // For Python command
2650     TDF_Tool::Entry(anObj->GetEntry(), anEntry);
2651     if (argi > 1) aPartsDescr += ", ";
2652     aPartsDescr += anEntry;
2653   }
2654
2655   //Compute the Block value
2656   try {
2657     // 1. Explode compound on solids
2658     TopTools_MapOfShape mapShape;
2659     Standard_Integer nbSolids = 0;
2660     TopExp_Explorer exp (aBlockOrComp, TopAbs_SOLID);
2661     for (; exp.More(); exp.Next()) {
2662       if (mapShape.Add(exp.Current())) {
2663         nbSolids++;
2664       }
2665     }
2666
2667     mapShape.Clear();
2668     Standard_Integer ind = 1;
2669     TopTools_Array1OfShape aSolids (1, nbSolids);
2670     TColStd_Array1OfInteger aNbParts (1, nbSolids);
2671     for (exp.Init(aBlockOrComp, TopAbs_SOLID); exp.More(); exp.Next(), ind++) {
2672       if (mapShape.Add(exp.Current())) {
2673         TopoDS_Shape aSolid = exp.Current();
2674         aSolids(ind) = aSolid;
2675         aNbParts(ind) = 0;
2676
2677         // 2. Define quantity of parts, contained in each solid
2678         TopTools_IndexedMapOfShape aSubShapes;
2679         TopExp::MapShapes(aSolid, aSubShapes);
2680         for (argi = 1; argi <= aLen; argi++) {
2681           if (aSubShapes.Contains(anArgs(argi))) {
2682             aNbParts(ind)++;
2683           }
2684         }
2685       }
2686     }
2687
2688     // 3. Define solid, containing maximum quantity of parts
2689     Standard_Integer maxNb = 0, nbFound = 0;
2690     TopoDS_Shape aShape;
2691     for (ind = 1; ind <= nbSolids; ind++) {
2692       if (aNbParts(ind) > maxNb) {
2693         maxNb = aNbParts(ind);
2694         aShape = aSolids(ind);
2695         nbFound = 1;
2696       } else if (aNbParts(ind) == maxNb) {
2697         nbFound++;
2698       } else {
2699       }
2700     }
2701     if (nbFound > 1) {
2702       SetErrorCode("Multiple blocks, containing maximum quantity of the given parts, are found");
2703       return NULL;
2704     } else if (nbFound == 0) {
2705       SetErrorCode("There are no blocks, containing the given parts");
2706       return NULL;
2707     } else {
2708       TopTools_IndexedMapOfShape anIndices;
2709       TopExp::MapShapes(aBlockOrComp, anIndices);
2710       Handle(TColStd_HArray1OfInteger) anArray = new TColStd_HArray1OfInteger(1,1);
2711       anArray->SetValue(1, anIndices.FindIndex(aShape));
2712       aResult = GetEngine()->AddSubShape(theCompound, anArray);
2713     }
2714   } catch (Standard_Failure) {
2715     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
2716     SetErrorCode(aFail->GetMessageString());
2717     return NULL;
2718   }
2719
2720   Handle(GEOM_Function) aFunction = aResult->GetLastFunction();
2721
2722   //Make a Python command
2723   GEOM::TPythonDump(aFunction) << aResult << " = geompy.GetBlockByParts("
2724     << theCompound << ", [" << aPartsDescr.ToCString() << "])";
2725
2726   SetErrorCode(OK);
2727   return aResult;
2728 }
2729
2730 //=============================================================================
2731 /*!
2732  *  GetBlocksByParts
2733  */
2734 //=============================================================================
2735 Handle(TColStd_HSequenceOfTransient) GEOMImpl_IBlocksOperations::GetBlocksByParts
2736                       (Handle(GEOM_Object)                         theCompound,
2737                        const Handle(TColStd_HSequenceOfTransient)& theParts)
2738 {
2739   SetErrorCode(KO);
2740
2741   if (theCompound.IsNull() || theParts.IsNull()) return NULL;
2742   TopoDS_Shape aBlockOrComp = theCompound->GetValue();
2743   if (aBlockOrComp.IsNull()) return NULL;
2744
2745   Handle(TColStd_HSequenceOfTransient) aBlocks = new TColStd_HSequenceOfTransient;
2746   Handle(GEOM_Object) anObj;
2747   Handle(GEOM_Function) aFunction;
2748
2749   //Get the parts
2750   Standard_Integer argi, aLen = theParts->Length();
2751   TopTools_Array1OfShape anArgs (1, aLen);
2752   TCollection_AsciiString anEntry, aPartsDescr, anAsciiList;
2753
2754   for (argi = 1; argi <= aLen; argi++) {
2755     Handle(GEOM_Object) anObj = Handle(GEOM_Object)::DownCast(theParts->Value(argi));
2756     Handle(GEOM_Function) aRef = anObj->GetLastFunction();
2757     if (aRef.IsNull()) return NULL;
2758
2759     TopoDS_Shape anArg = aRef->GetValue();
2760     if (anArg.IsNull()) {
2761       SetErrorCode("Null shape is given as argument");
2762       return NULL;
2763     }
2764     anArgs(argi) = anArg;
2765
2766     // For Python command
2767     TDF_Tool::Entry(anObj->GetEntry(), anEntry);
2768     aPartsDescr += anEntry + ", ";
2769   }
2770
2771   //Get the Blocks
2772   try {
2773     TopTools_MapOfShape mapShape;
2774     Standard_Integer nbSolids = 0;
2775     TopExp_Explorer exp (aBlockOrComp, TopAbs_SOLID);
2776     for (; exp.More(); exp.Next()) {
2777       if (mapShape.Add(exp.Current())) {
2778         nbSolids++;
2779       }
2780     }
2781
2782     mapShape.Clear();
2783     Standard_Integer ind = 1;
2784     TopTools_Array1OfShape aSolids (1, nbSolids);
2785     TColStd_Array1OfInteger aNbParts (1, nbSolids);
2786     for (exp.Init(aBlockOrComp, TopAbs_SOLID); exp.More(); exp.Next(), ind++) {
2787       if (mapShape.Add(exp.Current())) {
2788         TopoDS_Shape aSolid = exp.Current();
2789         aSolids(ind) = aSolid;
2790         aNbParts(ind) = 0;
2791
2792         // 2. Define quantity of parts, contained in each solid
2793         TopTools_IndexedMapOfShape aSubShapes;
2794         TopExp::MapShapes(aSolid, aSubShapes);
2795         for (argi = 1; argi <= aLen; argi++) {
2796           if (aSubShapes.Contains(anArgs(argi))) {
2797             aNbParts(ind)++;
2798           }
2799         }
2800       }
2801     }
2802
2803     // 3. Define solid, containing maximum quantity of parts
2804     Standard_Integer maxNb = 0, nbFound = 0;
2805     for (ind = 1; ind <= nbSolids; ind++) {
2806       if (aNbParts(ind) > maxNb) {
2807         maxNb = aNbParts(ind);
2808         nbFound = 1;
2809       } else if (aNbParts(ind) == maxNb) {
2810         nbFound++;
2811       } else {
2812       }
2813     }
2814     if (nbFound == 0) {
2815       SetErrorCode("There are no blocks, containing the given parts");
2816       return NULL;
2817     }
2818
2819     // Map shapes
2820     TopTools_IndexedMapOfShape anIndices;
2821     TopExp::MapShapes(aBlockOrComp, anIndices);
2822     Handle(TColStd_HArray1OfInteger) anArray;
2823
2824     for (ind = 1; ind <= nbSolids; ind++) {
2825       if (aNbParts(ind) == maxNb) {
2826         anArray = new TColStd_HArray1OfInteger(1,1);
2827         anArray->SetValue(1, anIndices.FindIndex(aSolids(ind)));
2828         anObj = GetEngine()->AddSubShape(theCompound, anArray);
2829         aBlocks->Append(anObj);
2830
2831         // For Python command
2832         TDF_Tool::Entry(anObj->GetEntry(), anEntry);
2833         anAsciiList += anEntry + ", ";
2834         if (aFunction.IsNull())
2835           aFunction = anObj->GetLastFunction();
2836       }
2837     }
2838   }
2839   catch (Standard_Failure) {
2840     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
2841     SetErrorCode(aFail->GetMessageString());
2842     return NULL;
2843   }
2844
2845   //Make a Python command
2846   aPartsDescr.Trunc(aPartsDescr.Length() - 2);
2847   anAsciiList.Trunc(anAsciiList.Length() - 2);
2848
2849   GEOM::TPythonDump(aFunction) << "[" << anAsciiList.ToCString()
2850     << "] = geompy.GetBlocksByParts(" << theCompound
2851       << ", [" << aPartsDescr.ToCString() << "])";
2852
2853   SetErrorCode(OK);
2854   return aBlocks;
2855 }
2856
2857 //=============================================================================
2858 /*!
2859  *  MakeMultiTransformation1D
2860  */
2861 //=============================================================================
2862 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::MakeMultiTransformation1D
2863                                              (Handle(GEOM_Object)    theObject,
2864                                               const Standard_Integer theDirFace1,
2865                                               const Standard_Integer theDirFace2,
2866                                               const Standard_Integer theNbTimes)
2867 {
2868   SetErrorCode(KO);
2869
2870   if (theObject.IsNull()) return NULL;
2871
2872   Handle(GEOM_Function) aLastFunction = theObject->GetLastFunction();
2873   if (aLastFunction.IsNull()) return NULL; //There is no function which creates an object to be moved
2874
2875   //Add a new Copy object
2876   Handle(GEOM_Object) aCopy = GetEngine()->AddObject(GetDocID(), GEOM_COPY);
2877
2878   //Add a translate function
2879   Handle(GEOM_Function) aFunction =
2880     aCopy->AddFunction(GEOMImpl_BlockDriver::GetID(), BLOCK_MULTI_TRANSFORM_1D);
2881
2882   //Check if the function is set correctly
2883   if (aFunction->GetDriverGUID() != GEOMImpl_BlockDriver::GetID()) return NULL;
2884
2885   GEOMImpl_IBlockTrsf aTI (aFunction);
2886   aTI.SetOriginal(aLastFunction);
2887   aTI.SetFace1U(theDirFace1);
2888   aTI.SetFace2U(theDirFace2);
2889   aTI.SetNbIterU(theNbTimes);
2890
2891   //Compute the transformation
2892   try {
2893     if (!GetSolver()->ComputeFunction(aFunction)) {
2894       SetErrorCode("Block driver failed to make multi-transformation");
2895       return NULL;
2896     }
2897   }
2898   catch (Standard_Failure) {
2899     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
2900     SetErrorCode(aFail->GetMessageString());
2901     return NULL;
2902   }
2903
2904   //Make a Python command
2905   GEOM::TPythonDump(aFunction) << aCopy << " = geompy.MakeMultiTransformation1D("
2906     << theObject << ", " << theDirFace1 << ", " << theDirFace2 << ", " << theNbTimes << ")";
2907
2908   SetErrorCode(OK);
2909   return aCopy;
2910 }
2911
2912 //=============================================================================
2913 /*!
2914  *  MakeMultiTransformation2D
2915  */
2916 //=============================================================================
2917 Handle(GEOM_Object) GEOMImpl_IBlocksOperations::MakeMultiTransformation2D
2918                                              (Handle(GEOM_Object)    theObject,
2919                                               const Standard_Integer theDirFace1U,
2920                                               const Standard_Integer theDirFace2U,
2921                                               const Standard_Integer theNbTimesU,
2922                                               const Standard_Integer theDirFace1V,
2923                                               const Standard_Integer theDirFace2V,
2924                                               const Standard_Integer theNbTimesV)
2925 {
2926   SetErrorCode(KO);
2927
2928   if (theObject.IsNull()) return NULL;
2929
2930   Handle(GEOM_Function) aLastFunction = theObject->GetLastFunction();
2931   if (aLastFunction.IsNull()) return NULL; //There is no function which creates an object to be moved
2932
2933   //Add a new Copy object
2934   Handle(GEOM_Object) aCopy = GetEngine()->AddObject(GetDocID(), GEOM_COPY);
2935
2936   //Add a translate function
2937   Handle(GEOM_Function) aFunction =
2938     aCopy->AddFunction(GEOMImpl_BlockDriver::GetID(), BLOCK_MULTI_TRANSFORM_2D);
2939
2940   //Check if the function is set correctly
2941   if (aFunction->GetDriverGUID() != GEOMImpl_BlockDriver::GetID()) return NULL;
2942
2943   GEOMImpl_IBlockTrsf aTI (aFunction);
2944   aTI.SetOriginal(aLastFunction);
2945   aTI.SetFace1U(theDirFace1U);
2946   aTI.SetFace2U(theDirFace2U);
2947   aTI.SetNbIterU(theNbTimesU);
2948   aTI.SetFace1V(theDirFace1V);
2949   aTI.SetFace2V(theDirFace2V);
2950   aTI.SetNbIterV(theNbTimesV);
2951
2952   //Compute the transformation
2953   try {
2954     if (!GetSolver()->ComputeFunction(aFunction)) {
2955       SetErrorCode("Block driver failed to make multi-transformation");
2956       return NULL;
2957     }
2958   }
2959   catch (Standard_Failure) {
2960     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
2961     SetErrorCode(aFail->GetMessageString());
2962     return NULL;
2963   }
2964
2965   //Make a Python command
2966   GEOM::TPythonDump(aFunction) << aCopy << " = geompy.MakeMultiTransformation2D("
2967     << theObject << ", " << theDirFace1U << ", " << theDirFace2U << ", " << theNbTimesU
2968       << ", " << theDirFace1V << ", " << theDirFace2V << ", " << theNbTimesV << ")";
2969
2970   SetErrorCode(OK);
2971   return aCopy;
2972 }
2973
2974 //=============================================================================
2975 /*!
2976  *  Propagate
2977  */
2978 //=============================================================================
2979 Handle(TColStd_HSequenceOfTransient) GEOMImpl_IBlocksOperations::Propagate
2980                                                  (Handle(GEOM_Object) theShape)
2981 {
2982   SetErrorCode(KO);
2983
2984   if (theShape.IsNull()) return NULL;
2985
2986   TopoDS_Shape aShape = theShape->GetValue();
2987   if (aShape.IsNull()) return NULL;
2988
2989   TopTools_IndexedMapOfShape anIndices;
2990   TopExp::MapShapes(aShape, anIndices);
2991
2992   TopTools_IndexedDataMapOfShapeListOfShape MEW;
2993   GEOMImpl_Block6Explorer::MapShapesAndAncestors
2994     (aShape, TopAbs_EDGE, TopAbs_WIRE, MEW);
2995   Standard_Integer ie, nbEdges = MEW.Extent();
2996
2997   // Result
2998   Handle(TColStd_HSequenceOfTransient) aSeq = new TColStd_HSequenceOfTransient;
2999
3000   TopTools_MapOfShape mapAcceptedEdges;
3001   TCollection_AsciiString aListRes, anEntry;
3002
3003   for (ie = 1; ie <= nbEdges; ie++) {
3004     TopoDS_Shape curE = MEW.FindKey(ie);
3005
3006     if (mapAcceptedEdges.Contains(curE)) continue;
3007
3008     // Build the chain
3009     TopTools_ListOfShape currentChain;
3010     TopTools_ListOfShape listPrevEdges;
3011
3012     currentChain.Append(curE);
3013     listPrevEdges.Append(curE);
3014     mapAcceptedEdges.Add(curE);
3015
3016     // Collect all edges pass by pass
3017     while (listPrevEdges.Extent() > 0) {
3018       // List of edges, added to chain on this cycle pass
3019       TopTools_ListOfShape listCurEdges;
3020
3021       // Find the next portion of edges
3022       TopTools_ListIteratorOfListOfShape itE (listPrevEdges);
3023       for (; itE.More(); itE.Next()) {
3024         TopoDS_Shape anE = itE.Value();
3025
3026         // Iterate on faces, having edge <anE>
3027         TopTools_ListIteratorOfListOfShape itW (MEW.FindFromKey(anE));
3028         for (; itW.More(); itW.Next()) {
3029           TopoDS_Shape aW = itW.Value();
3030           TopoDS_Shape anOppE;
3031
3032           BRepTools_WireExplorer aWE (TopoDS::Wire(aW));
3033           Standard_Integer nb = 1, found = 0;
3034           TopTools_Array1OfShape anEdges (1,4);
3035           for (; aWE.More(); aWE.Next(), nb++) {
3036             if (nb > 4) {
3037               found = 0;
3038               break;
3039             }
3040             anEdges(nb) = aWE.Current();
3041             if (anEdges(nb).IsSame(anE)) found = nb;
3042           }
3043
3044           if (nb == 5 && found > 0) {
3045             // Quadrangle face found, get an opposite edge
3046             Standard_Integer opp = found + 2;
3047             if (opp > 4) opp -= 4;
3048             anOppE = anEdges(opp);
3049
3050             if (!mapAcceptedEdges.Contains(anOppE)) {
3051               // Add found edge to the chain
3052               currentChain.Append(anOppE);
3053               listCurEdges.Append(anOppE);
3054               mapAcceptedEdges.Add(anOppE);
3055             }
3056           } // if (nb == 5 && found > 0)
3057         } // for (; itF.More(); itF.Next())
3058       } // for (; itE.More(); itE.Next())
3059
3060       listPrevEdges = listCurEdges;
3061     } // while (listPrevEdges.Extent() > 0)
3062
3063     // Store the chain in the document
3064     Handle(TColStd_HArray1OfInteger) anArray =
3065       new TColStd_HArray1OfInteger (1, currentChain.Extent());
3066
3067     // Fill array of sub-shape indices
3068     TopTools_ListIteratorOfListOfShape itSub (currentChain);
3069     for (int index = 1; itSub.More(); itSub.Next(), ++index) {
3070       int id = anIndices.FindIndex(itSub.Value());
3071       anArray->SetValue(index, id);
3072     }
3073
3074     // Add a new group object
3075     Handle(GEOM_Object) aChain = GetEngine()->AddSubShape(theShape, anArray);
3076
3077     // Set a GROUP type
3078     aChain->SetType(GEOM_GROUP);
3079
3080     // Set a sub shape type
3081     TDF_Label aFreeLabel = aChain->GetFreeLabel();
3082     TDataStd_Integer::Set(aFreeLabel, (Standard_Integer)TopAbs_EDGE);
3083
3084     // Add the chain to the result
3085     aSeq->Append(aChain);
3086
3087     //Make a Python command
3088     TDF_Tool::Entry(aChain->GetEntry(), anEntry);
3089     aListRes += anEntry + ", ";
3090   }
3091
3092   if (aSeq->IsEmpty()) {
3093     SetErrorCode("There are no quadrangle faces in the shape");
3094     return aSeq;
3095   }
3096
3097   aListRes.Trunc(aListRes.Length() - 2);
3098
3099   // The Propagation doesn't change object so no new function is required.
3100   Handle(GEOM_Function) aFunction = theShape->GetLastFunction();
3101
3102   // Make a Python command
3103   GEOM::TPythonDump(aFunction, /*append=*/true)
3104     << "[" << aListRes.ToCString() << "] = geompy.Propagate(" << theShape << ")";
3105
3106   SetErrorCode(OK);
3107   return aSeq;
3108 }