]> SALOME platform Git repositories - modules/geom.git/blob - src/GEOM/GEOM_Gen_i.cc
Salome HOME
529b2b87d0174d047b3f0e2ad9e3c226816f7bed
[modules/geom.git] / src / GEOM / GEOM_Gen_i.cc
1 //  GEOM GEOM : implementaion of GEOM_Gen.idl and GEOM_Shape.idl
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
5 // 
6 //  This library is free software; you can redistribute it and/or 
7 //  modify it under the terms of the GNU Lesser General Public 
8 //  License as published by the Free Software Foundation; either 
9 //  version 2.1 of the License. 
10 // 
11 //  This library is distributed in the hope that it will be useful, 
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of 
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
14 //  Lesser General Public License for more details. 
15 // 
16 //  You should have received a copy of the GNU Lesser General Public 
17 //  License along with this library; if not, write to the Free Software 
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
19 // 
20 //  See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
21 //
22 //
23 //
24 //  File   : GEOM_GEN_i.cc file
25 //  Author : Lucien PIGNOLONI
26 //  Module : GEOM
27 //  $Header$
28
29 using namespace std;
30 #include "GEOM_Gen_i.hh"
31
32 #include "Partition_Spliter.hxx"
33 #include "Archimede_VolumeSection.hxx"
34
35 #include "Utils_CorbaException.hxx"
36 #include "utilities.h"
37
38 #include <stdio.h>
39
40 // Cascade headers
41
42 #include <Standard_Failure.hxx>
43
44 #include <gp_Circ.hxx>
45 #include <gp_Pln.hxx>
46 #include <gp_Elips.hxx>
47 #include <Geom_Plane.hxx>
48 #include <Geom_Line.hxx>
49 #include <Geom_BezierCurve.hxx>
50 #include <Geom_BSplineCurve.hxx>
51 #include <GeomFill_Line.hxx>
52 #include <GeomFill_AppSurf.hxx>
53 #include <GeomFill_SectionGenerator.hxx>
54 #include <Geom_BSplineSurface.hxx>
55 #include <Geom_TrimmedCurve.hxx>
56 #include <GC_MakeArcOfCircle.hxx>
57 #include <GeomAPI_PointsToBSpline.hxx>
58 #include <GC_Root.hxx>
59
60 #include <BRepCheck_Analyzer.hxx>
61 #if OCC_VERSION_MAJOR >= 5
62 #include <BRepAlgo.hxx>
63 #else
64 #include <BRepAlgoAPI.hxx>
65 #endif
66 #include <BRepAdaptor_Surface.hxx>
67 #include <BRepBuilderAPI_Copy.hxx>
68 #include <BRepAlgoAPI_Common.hxx>
69 #include <BRepAlgoAPI_Cut.hxx>
70 #include <BRepAlgoAPI_Fuse.hxx>
71 #include <BRepAlgoAPI_Section.hxx>
72 #include <BRepOffsetAPI_Sewing.hxx>
73 #include <BRepOffsetAPI_MakePipe.hxx>
74
75 #include <BRepBuilderAPI_MakeVertex.hxx>
76 #include <BRepBuilderAPI_MakeEdge.hxx>
77 #include <BRepBuilderAPI_MakeFace.hxx>
78
79 #include <BRepLib.hxx>
80 #include <BRepBndLib.hxx>
81 #include <Bnd_Box.hxx>
82
83 #include <BRepBuilderAPI_MakeShell.hxx>
84 #include <BRepPrim_Builder.hxx>
85 #include <BRepBuilderAPI_MakeSolid.hxx>
86 #include <BRepClass3d_SolidClassifier.hxx>
87
88 #include <BRepBuilderAPI_MakeWire.hxx>
89 #include <BRepBuilderAPI_Transform.hxx>
90 #include <BRepPrimAPI_MakeRevol.hxx>
91 #include <BRepPrimAPI_MakePrism.hxx>
92 #include <BRepPrimAPI_MakeTorus.hxx>
93 #include <BRepPrimAPI_MakeBox.hxx>
94 #include <BRepPrimAPI_MakeSphere.hxx>
95 #include <BRepPrimAPI_MakeCylinder.hxx>
96 #include <BRepPrimAPI_MakeCone.hxx>
97 #include <BRepFilletAPI_MakeFillet.hxx>
98 #include <BRepFilletAPI_MakeChamfer.hxx>
99 #include <BRepTools.hxx>
100 #include <BRepTools_Quilt.hxx>
101 #include <BRep_Tool.hxx>
102
103 #include <GeomAPI_ProjectPointOnCurve.hxx>
104
105 #include <BRepGProp.hxx>
106 #include <GProp_GProps.hxx>
107 #include <Precision.hxx>
108
109 //VRV: OCC 4.0 migration
110 #include <STEPControl_Reader.hxx>
111 #include <IGESControl_Reader.hxx>
112 //VRV: OCC 4.0 migration
113
114 #include <IFSelect_ReturnStatus.hxx>
115 #include <TColStd_HSequenceOfTransient.hxx>
116
117 //VRV: OCC 4.0 migration
118 #include <IGESControl_Writer.hxx>
119 #include <IGESControl_Controller.hxx>
120 #include <STEPControl_Writer.hxx>
121 #include <Interface_Static.hxx>
122 //#include <STEPControlStd_StepModelType.hxx>
123 //VRV: OCC 4.0 migration
124
125 #include <TopoDS_Shape.hxx>
126 #include <TopAbs.hxx>
127 #include <TopoDS_Wire.hxx>
128 #include <TopoDS_Edge.hxx>
129 #include <TopoDS_Compound.hxx>
130 #include <TopoDS_Solid.hxx>
131
132 #include <TopExp.hxx>
133 #include <TopExp_Explorer.hxx>
134 #include <TCollection_ExtendedString.hxx>
135 #include <TColgp_Array1OfPnt.hxx>
136 #include <TopoDS_Iterator.hxx>
137 #include <TopTools_MapOfShape.hxx>
138 #include <TopTools_MapIteratorOfMapOfShape.hxx>
139 #include <TopTools_ListIteratorOfListOfShape.hxx>
140 #include <TopTools_Array1OfShape.hxx>
141
142 #include <IGESData_IGESEntity.hxx>
143
144 #include <TDF_Tool.hxx>
145 #include <TDF_Label.hxx>
146 #include <TDataStd_Name.hxx>
147 #include <TDataStd_Comment.hxx>
148 #include <TDF_Reference.hxx>
149 #include <TDF_Data.hxx>
150 #include <TNaming_Builder.hxx>
151 #include <TNaming_NamedShape.hxx>
152 #include <TNaming_Tool.hxx>
153 //  #include <TDocStd_Owner.hxx>
154
155 #include "SALOMEDS_Tool.hxx"
156 #include "GEOMDS_Commands.hxx"
157 #include "GEOMDS_Explorer.hxx"
158
159 #include CORBA_SERVER_HEADER(SALOMEDS_Attributes)
160
161 #include "Utils_ExceptHandlers.hxx"
162
163 Standard_EXPORT static Standard_Boolean IsValid(const TopoDS_Shape& S) {
164 #if OCC_VERSION_MAJOR >= 5
165   return BRepAlgo::IsValid(S);
166 #else
167   return BRepAlgoAPI::IsValid(S);
168 #endif
169 }
170
171 //============================================================================
172 // function : GEOM_Gen_i()
173 // purpose  : constructor to be called for servant creation. 
174 //============================================================================
175 GEOM_Gen_i::GEOM_Gen_i(CORBA::ORB_ptr orb,
176                        PortableServer::POA_ptr poa,
177                        PortableServer::ObjectId * contId, 
178                        const char *instanceName, 
179                        const char *interfaceName) :
180   Engines_Component_i(orb, poa, contId, instanceName, interfaceName)
181 {
182   _thisObj = this ;
183   _id = _poa->activate_object(_thisObj);
184   // SCRUTE(this)
185   name_service = new SALOME_NamingService(_orb);
186   myOCAFApp    = new GEOMDS_Application();
187   myStudyID    = -1;
188   GetCurrentStudy(0);//for correct work of SuperVisor
189 }
190
191
192
193 //============================================================================
194 // function : ~GEOM_Gen_i()
195 // purpose  : destructor
196 //============================================================================
197 GEOM_Gen_i::~GEOM_Gen_i() {
198   delete name_service;
199 }
200
201
202 //============================================================================
203 // function : IORToLocalPersistentID()
204 // purpose  :
205 //============================================================================
206 char* GEOM_Gen_i::IORToLocalPersistentID(SALOMEDS::SObject_ptr theSObject,
207                                          const char* IORString,
208                                          CORBA::Boolean isMultiFile,
209                                          CORBA::Boolean isASCII)
210 {
211   GEOM::GEOM_Shape_var aShape = GEOM::GEOM_Shape::_narrow(_orb->string_to_object(IORString));
212   if (!CORBA::is_nil(aShape)) {
213     return strdup(aShape->ShapeId());
214   }
215   return 0;
216 }
217
218
219 //============================================================================
220 // function : LocalPersistentIDToIOR()
221 // purpose  : Create/Load CORBA object from a persistent ref (an entry)
222 //          : Used when a study is loaded
223 //          : The IOR (IORName) of object created is returned
224 //============================================================================
225 char* GEOM_Gen_i::LocalPersistentIDToIOR(SALOMEDS::SObject_ptr theSObject,
226                                          const char* aLocalPersistentID,
227                                          CORBA::Boolean isMultiFile,
228                                          CORBA::Boolean isASCII) 
229
230   SALOMEDS::Study_var myStudy = theSObject->GetStudy();
231   GetCurrentStudy(myStudy->StudyId());
232   Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(myStudyIDToDoc(myStudy->StudyId()));
233   CORBA::String_var aPersRefString = aLocalPersistentID;
234
235   /* For a GEOM::GEOM_Shape the pers_ref is the Entry in the OCAF document */
236   TCollection_ExtendedString MainIOR;
237   TDF_Label Lab;
238   TDF_Tool::Label(aDoc->GetData(), aPersRefString, Lab );
239   
240   Handle(TNaming_NamedShape) NS;
241   Lab.FindAttribute( TNaming_NamedShape::GetID(), NS );
242   TopoDS_Shape S = TNaming_Tool::GetShape(NS);
243
244   /* shapetype, index=0, topo, orb, shapetype, ismain=true and name are setted and modified later ? */
245   GEOM::GEOM_Shape_var result = CreateObject(S);
246   GEOMDS_Commands GC( aDoc->Main() ) ;
247   
248   if ( GC.HasIOR(Lab) ) { /* shape already created/loaded */
249     return 0 ;
250   }
251
252   /******************* Dependent object (not a main shape) *********************/
253   if( GC.IsDependentShape(Lab) ) {
254     
255     TDF_Label mainLabel ;
256     Standard_Boolean mainShapeOk = GC.GetMainShapeLabel(Lab, mainLabel) ;
257     
258     /* Main object not yet loaded we load/create it */
259     if( !GC.HasIOR(mainLabel) ) {
260       
261       TCollection_AsciiString entry;
262       TDF_Tool::Entry(mainLabel,entry);
263       CORBA::String_var ent = strdup(entry.ToCString());
264       
265       /* Create the main object recursively */
266       MainIOR = LocalPersistentIDToIOR(theSObject, ent, isMultiFile, isASCII) ;
267     } else {
268       GC.ReturnNameIOR( mainLabel, MainIOR ); 
269     }
270     
271     result->MainName( TCollection_AsciiString(MainIOR).ToCString() ) ;      
272     result->IsMainShape(false) ;
273     result->ShapeId(aPersRefString);
274     
275     Handle(TDF_Reference) aRef;
276     Lab.FindAttribute( TDF_Reference::GetID(), aRef );
277     TDF_Label myL = aRef->Get() ;
278     Handle(TNaming_NamedShape) NN;
279     myL.FindAttribute( TNaming_NamedShape::GetID(), NN );
280     TopoDS_Shape mainTopo = TNaming_Tool::GetShape(NN);
281
282     GEOM::GEOM_Shape::ListOfSubShapeID_var ListOfID = new GEOM::GEOM_Shape::ListOfSubShapeID;
283     
284     if(S.ShapeType() != TopAbs_COMPOUND) {
285       /* to set the index of a unique sub shape (Explode All ONLY for the moment !) */
286       ListOfID->length(1);
287       int index = 1;
288       TopTools_MapOfShape M;
289       TopExp_Explorer Exp ;
290       for( Exp.Init(mainTopo, TopAbs_ShapeEnum( result->ShapeType() )) ; Exp.More(); Exp.Next() )  {
291         if ( M.Add(Exp.Current()) ) {
292           if(Exp.Current().IsSame(S) ) {
293             ListOfID[0] = index;
294             break;
295           }
296           index++ ;
297         }       
298       }
299       result->Index(ListOfID) ;
300       return result->Name(); 
301     }
302     else {
303       /* Here is a TopAbs_COMPOUND : we set the list/index for a compound : containing two or more sub shapes  */
304       /* Warning : the Corba shape has a shapetype Compound : in GEOMDS_Client we have to retrieve the kind of */
305       /* subshapes contained in this compound !                                                                */
306       TopTools_SequenceOfShape SS;
307       TopoDS_Iterator it ;
308       TopExp_Explorer exp ;
309       TopAbs_ShapeEnum subType ;
310       
311       /* Set all sub shapes in a sequence of shapes  */
312       for ( it.Initialize( S, true, true ) ; it.More(); it.Next() ) {
313         subType = it.Value().ShapeType() ;
314         SS.Append( it.Value() ) ;
315       }
316       
317       ListOfID->length( SS.Length() ) ;
318       int j, k ;  /* in TopTools_SequenceOfShape index start at 1 */
319       
320       for( k=1; k<=SS.Length(); k++ ) {
321         j = 1 ;
322         for( exp.Init( mainTopo, subType ); exp.More(); exp.Next() ) {  
323           if( exp.Current().IsSame( SS.Value(k) ) ) {
324             ListOfID[k-1] = j ;
325           }
326           j++ ;
327         }
328       }
329       result->Index(ListOfID) ;
330       return result->Name();
331     }
332     
333   }
334   /******************* Independent object (not a sub shape) *********************/
335   else {
336     result->IsMainShape(true) ;
337     if( !GC.AddIORNameAttribute(Lab, result->Name() ) )  {
338       MESSAGE("in LocalPersistentIDToIOR, NAME/IOR attribute already exist." << endl ) ;
339     }
340     Handle(TNaming_NamedShape) NamedShape ;  
341     bool notTested = Lab.FindAttribute(TNaming_NamedShape::GetID(), NamedShape) ;
342     result->ShapeId(aPersRefString);
343     return result->Name(); 
344   }
345 }
346
347 //============================================================================
348 // function : CanPublishInStudy
349 // purpose  : 
350 //============================================================================
351 bool GEOM_Gen_i::CanPublishInStudy(CORBA::Object_ptr theIOR)
352 {
353   GEOM::GEOM_Shape_var aShape = GEOM::GEOM_Shape::_narrow(theIOR);
354   return !(aShape->_is_nil());
355 }
356
357
358 //============================================================================
359 // function : PublishInStudy
360 // purpose  : 
361 //============================================================================
362 SALOMEDS::SObject_ptr GEOM_Gen_i::PublishInStudy(SALOMEDS::Study_ptr theStudy,
363                                                  SALOMEDS::SObject_ptr theSObject,
364                                                  CORBA::Object_ptr theObject,
365                                                  const char* theName) throw (SALOME::SALOME_Exception)
366 {
367   Unexpect aCatch(SALOME_SalomeException);
368   SALOMEDS::SObject_var aResultSO;
369   if(CORBA::is_nil(theObject)) return aResultSO;
370
371   GEOM::GEOM_Shape_var aShape = GEOM::GEOM_Shape::_narrow(theObject);
372   if(aShape->_is_nil()) return aResultSO;
373
374   if(theStudy->_is_nil()) return aResultSO;
375
376   SALOMEDS::GenericAttribute_var anAttr;
377   SALOMEDS::StudyBuilder_var     aStudyBuilder = theStudy->NewBuilder(); 
378
379   SALOMEDS::SComponent_var       aFather = theStudy->FindComponent("GEOM"); 
380   if (aFather->_is_nil()) {
381     aFather = aStudyBuilder->NewComponent("GEOM");
382     anAttr = aStudyBuilder->FindOrCreateAttribute(aFather, "AttributeName");
383     SALOMEDS::AttributeName_var aName = SALOMEDS::AttributeName::_narrow(anAttr);
384     aName->SetValue("Geometry");
385     anAttr = aStudyBuilder->FindOrCreateAttribute(aFather, "AttributePixMap");
386     SALOMEDS::AttributePixMap::_narrow(anAttr)->SetPixMap("ICON_OBJBROWSER_Geometry");
387     aStudyBuilder->DefineComponentInstance(aFather, GEOM_Gen::_this());
388   }
389   if (aFather->_is_nil()) return aResultSO;
390   
391   if (CORBA::is_nil(theSObject)) {
392     aResultSO = aStudyBuilder->NewObject(aFather);
393   } else {
394     if (!theSObject->ReferencedObject(aResultSO)) 
395       THROW_SALOME_CORBA_EXCEPTION("Publish in study supervision graph error",SALOME::BAD_PARAM);
396   }
397   anAttr = aStudyBuilder->FindOrCreateAttribute(aResultSO, "AttributeIOR");
398   SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
399   anIOR->SetValue(aShape->Name());
400
401   anAttr = aStudyBuilder->FindOrCreateAttribute(aResultSO, "AttributePixMap");
402   SALOMEDS::AttributePixMap_var aPixmap = SALOMEDS::AttributePixMap::_narrow(anAttr);
403   TCollection_AsciiString aShapeName("Shape_");  
404
405   if ( aShape->ShapeType() == GEOM::COMPOUND ) {
406     aPixmap->SetPixMap( "ICON_OBJBROWSER_COMPOUND" );
407     aShapeName = "Compound_";
408   } else if ( aShape->ShapeType() == GEOM::COMPSOLID ) {
409     aPixmap->SetPixMap( "ICON_OBJBROWSER_COMPSOLID" );
410     aShapeName = "Compsolid_";
411   } else if ( aShape->ShapeType() == GEOM::SOLID ) {
412     aPixmap->SetPixMap( "ICON_OBJBROWSER_SOLID" );
413     aShapeName = "Solid_";
414   } else if ( aShape->ShapeType() == GEOM::SHELL ) {
415     aPixmap->SetPixMap( "ICON_OBJBROWSER_SHELL" );
416     aShapeName = "Shell_";
417   } else if ( aShape->ShapeType() == GEOM::FACE ) {
418     aPixmap->SetPixMap( "ICON_OBJBROWSER_FACE" );
419     aShapeName = "Face_";
420   } else if ( aShape->ShapeType() == GEOM::WIRE ) {
421     aPixmap->SetPixMap( "ICON_OBJBROWSER_WIRE" );
422     aShapeName = "Wire_";
423   } else if ( aShape->ShapeType() == GEOM::EDGE ) {
424     aPixmap->SetPixMap( "ICON_OBJBROWSER_EDGE" );
425     aShapeName = "Edge_";
426   } else if ( aShape->ShapeType() == GEOM::VERTEX ) {
427     aPixmap->SetPixMap( "ICON_OBJBROWSER_VERTEX" );
428     aShapeName = "Vertex_";
429   }                                          
430   if (strlen(theName) == 0) aShapeName += TCollection_AsciiString(aResultSO->Tag());
431   else aShapeName = TCollection_AsciiString(strdup(theName));
432
433   //Set a name of the added shape
434   anAttr = aStudyBuilder->FindOrCreateAttribute(aResultSO, "AttributeName");
435   SALOMEDS::AttributeName_var aNameAttrib = SALOMEDS::AttributeName::_narrow(anAttr);
436   aNameAttrib->SetValue(aShapeName.ToCString());
437
438   //Add a reference to published object
439 //    aStudyBuilder->Addreference(theObject, aResultSO);
440   return aResultSO._retn();
441 }
442
443  
444 //============================================================================
445 // function : Save()
446 // purpose  : save OCAF/Geom document
447 //============================================================================
448 SALOMEDS::TMPFile* GEOM_Gen_i::Save(SALOMEDS::SComponent_ptr theComponent,
449                                     const char* theURL,
450                                     bool isMultiFile) {
451   SALOMEDS::TMPFile_var aStreamFile;
452   // Get a temporary directory to store a file
453   TCollection_AsciiString aTmpDir = (isMultiFile)?TCollection_AsciiString((char*)theURL):SALOMEDS_Tool::GetTmpDir();
454   // Create a list to store names of created files
455   SALOMEDS::ListOfFileNames_var aSeq = new SALOMEDS::ListOfFileNames;
456   aSeq->length(1);
457   // Prepare a file name to open
458   TCollection_AsciiString aNameWithExt("");
459   if (isMultiFile)
460     aNameWithExt = TCollection_AsciiString(SALOMEDS_Tool::GetNameFromPath(theComponent->GetStudy()->URL()));
461   aNameWithExt += TCollection_AsciiString("_GEOM.sgd");
462   aSeq[0] = CORBA::string_dup(aNameWithExt.ToCString());
463   // Build a full file name of temporary file
464   TCollection_AsciiString aFullName = aTmpDir + aNameWithExt;
465   // Save GEOM component in this file
466   myOCAFApp->SaveAs(myCurrentOCAFDoc, aFullName);
467   // Conver a file to the byte stream
468   aStreamFile = SALOMEDS_Tool::PutFilesToStream(aTmpDir.ToCString(), aSeq.in(), isMultiFile);
469   // Remove the created file and tmp directory
470   if (!isMultiFile) SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.ToCString(), aSeq.in(), true);
471   // Return the created byte stream
472   return aStreamFile._retn();
473 }
474
475 SALOMEDS::TMPFile* GEOM_Gen_i::SaveASCII(SALOMEDS::SComponent_ptr theComponent,
476                                          const char* theURL,
477                                          bool isMultiFile) {
478   SALOMEDS::TMPFile_var aStreamFile = Save(theComponent, theURL, isMultiFile);
479   return aStreamFile._retn();
480 }
481
482
483 CORBA::Boolean GEOM_Gen_i::Load(SALOMEDS::SComponent_ptr theComponent,
484                                 const SALOMEDS::TMPFile& theStream,
485                                 const char* theURL,
486                                 bool isMultiFile) {
487
488   if (theStream.length() <= 9) {
489     MESSAGE("The TMPFile is too short : " << theStream.length() << " bytes ");
490     return false;
491   }
492
493   // Get a temporary directory for a file
494   TCollection_AsciiString aTmpDir = isMultiFile?TCollection_AsciiString((char*)theURL):SALOMEDS_Tool::GetTmpDir();
495   // Conver the byte stream theStream to a file and place it in tmp directory
496   SALOMEDS::ListOfFileNames_var aSeq = SALOMEDS_Tool::PutStreamToFiles(theStream,
497                                                                        aTmpDir.ToCString(),
498                                                                        isMultiFile);
499
500   // Prepare a file name to open
501   TCollection_AsciiString aNameWithExt("");
502   if (isMultiFile)
503     aNameWithExt = TCollection_AsciiString(SALOMEDS_Tool::GetNameFromPath(theComponent->GetStudy()->URL()));
504   aNameWithExt += TCollection_AsciiString("_GEOM.sgd");
505   TCollection_AsciiString aFullName = aTmpDir + aNameWithExt;
506
507   // Open document
508   if (myOCAFApp->Open(aFullName, myCurrentOCAFDoc) != CDF_RS_OK) return false;
509
510   // Remove the created file and tmp directory
511   if (!isMultiFile) SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.ToCString(), aSeq.in(), true);
512
513   SALOMEDS::Study_var Study = theComponent->GetStudy();
514   TCollection_AsciiString name( strdup(Study->Name()) );
515
516   int StudyID = Study->StudyId();
517   myStudyIDToDoc.Bind( StudyID, myCurrentOCAFDoc );  
518   myStudyID = StudyID;
519     
520   /* We clear all IOR (nameIOR) attributes of all objects before reconstruction */
521   /* This information will be setted when each object is reconstructed          */
522   GEOMDS_Commands GC( myCurrentOCAFDoc->Main() ) ;
523   GC.ClearAllIOR(myCurrentOCAFDoc->Main());
524
525   return true;
526 }
527
528 CORBA::Boolean GEOM_Gen_i::LoadASCII(SALOMEDS::SComponent_ptr theComponent,
529                                      const SALOMEDS::TMPFile& theStream,
530                                      const char* theURL,
531                                      bool isMultiFile) {
532   return Load(theComponent, theStream, theURL, isMultiFile);
533 }
534
535 //  //============================================================================
536 //  // function : Save()
537 //  // purpose  : save OCAF/Geom document
538 //  //============================================================================
539 //  void GEOM_Gen_i::Save(const char *IORSComponent, const char *aUrlOfFile) 
540 //  {
541
542 //    TCollection_ExtendedString path(strdup(aUrlOfFile));
543 //    TCollection_ExtendedString pathWithExt = path + TCollection_ExtendedString(".sgd");
544 //    myOCAFApp->SaveAs(myCurrentOCAFDoc,pathWithExt);
545 //  }
546
547
548 //  //============================================================================
549 //  // function : Load()
550 //  // purpose  : Load OCAF/Geom document
551 //  //============================================================================
552 //  void GEOM_Gen_i::Load(const char *IORSComponent, const char *aUrlOfFile) 
553 //  {
554
555 //    TCollection_ExtendedString path(strdup(aUrlOfFile));
556 //    TCollection_ExtendedString pathWithExt = path + TCollection_ExtendedString(".sgd");
557
558 //    myOCAFApp->Open(pathWithExt,myCurrentOCAFDoc);
559
560 //    SALOMEDS::SComponent_var SC = SALOMEDS::SComponent::_narrow(_orb->string_to_object(IORSComponent));
561 //    SALOMEDS::Study_var Study = SC->GetStudy();
562 //    TCollection_AsciiString name( strdup(Study->Name()) );
563
564 //    int StudyID = Study->StudyId();
565 //    myStudyIDToDoc.Bind( StudyID, myCurrentOCAFDoc );  
566 //    myStudyID = StudyID;
567
568 //    /* We clear all IOR (nameIOR) attributes of all objects before reconstruction */
569 //    /* This information will be setted when each object is reconstructed          */
570 //    GEOMDS_Commands GC( myCurrentOCAFDoc->Main() ) ;
571 //    GC.ClearAllIOR(myCurrentOCAFDoc->Main());
572
573 //    return ;
574 //  }
575
576
577 //============================================================================
578 // function : Close()
579 // purpose  :
580 //============================================================================
581 void GEOM_Gen_i::Close(SALOMEDS::SComponent_ptr theComponent)
582 {
583   int anID = theComponent->GetStudy()->StudyId();
584   if (anID == myStudyID) GetCurrentStudy(0); // set default value of current study ID, if current is deleted
585   if (myStudyIDToDoc.IsBound(anID)) {
586     // close document in the application
587 //      Handle(TDocStd_Owner) anOwner;
588     Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(myStudyIDToDoc.Find(anID));
589 //      Handle(TDocStd_Document) anEmptyDoc;
590 //      if (aDoc->Main().Root().FindAttribute(TDocStd_Owner::GetID(), anOwner)) {
591 //        anOwner->SetDocument(anEmptyDoc);
592 //        cout<<"********** Nullify owner of document"<<endl;
593 //      }
594     myOCAFApp->Close(aDoc);
595     myStudyIDToDoc.UnBind(anID); // remove document from GEOM documents data map
596     }
597 }
598
599 //============================================================================
600 // function : CanCopy()
601 // purpose  :
602 //============================================================================
603 CORBA::Boolean GEOM_Gen_i::CanCopy(SALOMEDS::SObject_ptr theObject) {
604   // Try to retrieve known by Geometry component GEOM_shape by given IOR
605   SALOMEDS::GenericAttribute_var anAttr;
606   if (!theObject->FindAttribute(anAttr, "AttributeIOR")) return false;
607   GEOM::GEOM_Shape_var aShape = GetIORFromString(SALOMEDS::AttributeIOR::_narrow(anAttr)->Value());
608   // If the object is null one it can't be copied: return false
609   if (aShape->_is_nil()) return false;
610   return true;
611 }
612
613 //============================================================================
614 // function : CopyFrom()
615 // purpose  :
616 //============================================================================
617 SALOMEDS::TMPFile* GEOM_Gen_i::CopyFrom(SALOMEDS::SObject_ptr theObject, CORBA::Long& theObjectID) {
618   // Declare a sequence of the byte to store the copied object
619   SALOMEDS::TMPFile_var aStreamFile = new SALOMEDS::TMPFile;
620
621   // Try to get GEOM_Shape object by given SObject
622   SALOMEDS::GenericAttribute_var anAttr;
623   if (!theObject->FindAttribute(anAttr, "AttributeIOR")) return false;
624   GEOM::GEOM_Shape_var aShape = GetIORFromString(SALOMEDS::AttributeIOR::_narrow(anAttr)->Value());
625   // If the object is null one it can't be copied: return false
626   if (aShape->_is_nil()) return aStreamFile._retn();
627  
628   GetCurrentStudy(theObject->GetStudy()->StudyId());
629
630   // Convert a TopoDS_Shape to a stream of bytes
631   TopoDS_Shape aTopology = GetTopoShape(aShape);
632   if (aTopology.IsNull()) return aStreamFile._retn();
633   ostrstream aStreamedShape;
634   BRepTools::Write(aTopology, aStreamedShape);
635   int aSize = aStreamedShape.pcount();
636   char* aBuffer = new char[aSize];
637   memcpy(aBuffer, aStreamedShape.str(), aSize);
638   aStreamedShape.rdbuf()->freeze(0);
639
640   aStreamFile = new SALOMEDS::TMPFile(aSize, aSize, (CORBA::Octet*)aBuffer, 1);
641   
642   // Assign an ID = 1 the the type GEOM_Shape
643   theObjectID = 1;
644
645   // Return created TMPFile
646   return aStreamFile._retn();
647 }
648
649 //============================================================================
650 // function : CanPaste()
651 // purpose  :
652 //============================================================================
653 CORBA::Boolean GEOM_Gen_i::CanPaste(const char* theComponentName, CORBA::Long theObjectID) {
654   // The Geometry component can paste only objects copied by Geometry component
655   // and with the object type = 1
656 //    cout<<"********** GEOM_Gen_i::CanPaste ("<<theComponentName<<","<<theObjectID<<")"<<endl;
657   if (strcmp(theComponentName, ComponentDataType()) != 0 || theObjectID != 1) return false;
658   return true;
659 }
660
661 //============================================================================
662 // function : PasteInto()
663 // purpose  :
664 //============================================================================
665 SALOMEDS::SObject_ptr GEOM_Gen_i::PasteInto(const SALOMEDS::TMPFile& theStream,
666                                             CORBA::Long theObjectID,
667                                             SALOMEDS::SObject_ptr theObject) {
668   // Find the current Study and StudyBuilder
669   SALOMEDS::Study_var aStudy = theObject->GetStudy();
670   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
671
672   // Retrieve a TopoDS_Shape from byte stream
673   TopoDS_Shape aTopology;
674   istrstream aStreamedBrep((char*) &theStream[0], theStream.length());
675   BRep_Builder aBuilder;
676   try {
677     BRepTools::Read(aTopology, aStreamedBrep, aBuilder);
678   } catch (Standard_Failure) {
679 //      cout<<"GEOM_Gen_i::PasteInto exception"<<endl;
680     return false;
681   }
682   
683   // Create new object in Geometry component using retrieved topology
684   GEOM::GEOM_Shape_var aShape = CreateObject(aTopology);
685   GetCurrentStudy(aStudy->StudyId());
686   const char *anEntry = InsertInLabel(aTopology, aShape->Name(), myCurrentOCAFDoc) ;
687   aShape->ShapeId(anEntry) ;
688
689   // SObject of the created shape is theObject or new Child of Component if theObject == geom component
690   SALOMEDS::SObject_var aNewSO;
691   if (strcmp(theObject->GetFatherComponent()->GetID(),theObject->GetID()) == 0) {
692     aNewSO = aStudyBuilder->NewObject(theObject);
693   } else aNewSO = SALOMEDS::SObject::_duplicate(theObject);
694   // Add IORAttribute to the Study and set IOR of the created GEOM_Shape to it
695   SALOMEDS::GenericAttribute_var anAttr = aStudyBuilder->FindOrCreateAttribute(aNewSO, "AttributeIOR");
696   SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
697   anIOR->SetValue(aShape->Name());
698
699   // Return the created in the Study SObject
700   return aNewSO._retn();
701 }
702
703 //============================================================================
704 // function : ComponentDataType()
705 // purpose  :
706 //============================================================================
707 char* GEOM_Gen_i::ComponentDataType()
708 {
709   return strdup("GEOM");
710 }
711
712 //============================================================================
713 // function : register() 
714 // purpose  : register 'name' in 'name_service'
715 //============================================================================
716 void GEOM_Gen_i::register_name(char * name)
717 {
718   GEOM::GEOM_Gen_ptr g = GEOM::GEOM_Gen::_narrow(POA_GEOM::GEOM_Gen::_this());
719   name_service->Register(g, strdup(name)); 
720 }
721
722
723
724 //================================================================================
725 // function : SequenceOfShapeFromListOfGeomShape()
726 // purpose  : Define a sequence of shapes from 'listShapes' and return its length.
727 //          : No control is made on shapes !
728 //================================================================================
729 int GEOM_Gen_i::SequenceOfShapeFromListOfGeomShape( const GEOM::GEOM_Gen::ListOfGeomShapes& listShapes,
730                                                     TopTools_SequenceOfShape& SS )
731 {
732   int nbShapes = listShapes.length() ;
733   if( nbShapes < 1)
734     return 0 ;
735   
736   for(int i=0; i<nbShapes; i++) {
737     GEOM::GEOM_Shape_var aGeomShape = listShapes[i] ;
738     TopoDS_Shape aShape = GetTopoShape(aGeomShape) ;
739     SS.Append(aShape) ;
740   }
741   return nbShapes ;
742 }
743
744
745
746
747 //=================================================================================
748 // function : GetTopoShape()
749 // purpose  : Returns a TopoDS_Shape from a GEOM::GEOM_Shape_ptr in 'myCurrentOCAFDoc'
750 //          : A null shape is returned if not possible
751 //=================================================================================
752 TopoDS_Shape GEOM_Gen_i::GetTopoShape(GEOM::GEOM_Shape_ptr shape_ptr)
753
754   TopoDS_Shape tds ;
755
756   TDF_Label lab ;
757   Handle(TDF_Data) D = myCurrentOCAFDoc->GetData() ;
758   TDF_Tool::Label( D, strdup(shape_ptr->ShapeId()), lab, true ) ;
759   Handle(TNaming_NamedShape) NamedShape ;  
760   bool res = lab.FindAttribute(TNaming_NamedShape::GetID(), NamedShape) ;
761
762   if( !res ) {
763     return tds ; /* a null shape is returned */
764   }
765   else {
766     return TNaming_Tool::GetShape(NamedShape) ;
767   }
768 }
769
770
771
772 //=================================================================================
773 // function : GetStringFromIOR()
774 // purpose  : returns a string that represents  a 'GEOM::GEOM_Shape_var'
775 //=================================================================================
776 const char* GEOM_Gen_i::GetStringFromIOR(GEOM::GEOM_Shape_var shapeIOR) {
777   const char * ret = _orb->object_to_string(shapeIOR) ;
778   return ret ;
779 }
780
781
782
783 //=================================================================================
784 // function : GetIORFromString()
785 // purpose  : returns a 'GEOM::GEOM_Shape_var' from a string representing it
786 //=================================================================================
787 GEOM::GEOM_Shape_ptr GEOM_Gen_i::GetIORFromString(const char* stringIOR) {
788   GEOM::GEOM_Shape_var shapeIOR;
789   if(strcmp(stringIOR,"") != 0){
790     CORBA::Object_var anObject = _orb->string_to_object(stringIOR);
791     if(!CORBA::is_nil(anObject))
792       shapeIOR =  GEOM::GEOM_Shape::_narrow(anObject.in()) ;
793   }
794   return shapeIOR._retn() ;
795 }
796
797
798
799 //==================================================================================
800 // function : InsertInLabel()
801 // purpose  : Insert S = Shape and mystr = name in a new Label of Geom/OCAF document
802 //          : and returns the corresponding OCAF entry
803 //==================================================================================
804 const char * GEOM_Gen_i::InsertInLabel(TopoDS_Shape S, const char *mystr, Handle(TDocStd_Document) OCAFDoc)
805 {
806   GEOMDS_Commands GC(OCAFDoc->Main());
807   /* add attributs S and mystr in a new label */
808   TDF_Label Lab = GC.AddShape (S, strdup(mystr));
809
810   TCollection_AsciiString entry;
811   TDF_Tool::Entry(Lab,entry);
812   const char *ent = entry.ToCString() ;
813   return ent ;
814 }
815
816
817 //==================================================================================
818 // function : InsertInLabelDependentShape()
819 // purpose  : Insert S = Shape and its nameIor in a new Label of Geom/OCAF document
820 //          : insert also a reference attribute (a label) to the main shape 'mainshap_ptr'.
821 //          : and returns the corresponding OCAF entry of the new label.
822 //==================================================================================
823 const char * GEOM_Gen_i::InsertInLabelDependentShape( TopoDS_Shape S,
824                                                       const char *nameIor,
825                                                       GEOM::GEOM_Shape_ptr mainshape_ptr,
826                                                       Handle(TDocStd_Document) OCAFDoc )
827 {
828   GEOMDS_Commands GC(OCAFDoc->Main());
829   /* add attributs S and nameIor in a new label */
830
831   /* retrieve the label of the main shape in the document */
832   TDF_Label mainRefLab;
833   TDF_Tool::Label(OCAFDoc->GetData(), mainshape_ptr->ShapeId(), mainRefLab);
834
835   /* add attributs : S, nameIor and ref to main */
836   TDF_Label Lab = GC.AddDependentShape(S, strdup(nameIor), mainRefLab);
837
838   TCollection_AsciiString entry;
839   TDF_Tool::Entry(Lab, entry);
840   const char *ent = entry.ToCString() ;
841   return ent ;
842 }
843
844
845 //=================================================================================
846 // function : InsertInLabelOneArgument()
847 // purpose  :
848 //=================================================================================
849 void GEOM_Gen_i::InsertInLabelOneArgument(TopoDS_Shape main_topo,
850                                           GEOM::GEOM_Shape_ptr shape_ptr,
851                                           TopoDS_Shape result_topo,     
852                                           GEOM::GEOM_Shape_ptr result,  
853                                           Handle(TDocStd_Document) OCAFDoc)
854 {
855   /* Put shape and name into geom/OCAF doc */
856   GEOMDS_Commands GC(OCAFDoc->Main());
857   /* Add attributs 'shape' and 'name_ior' in a new label */
858   TDF_Label Lab = GC.Generated( main_topo, result_topo, result->Name() );
859   TCollection_AsciiString entry;
860   TDF_Tool::Entry(Lab, entry);
861   result->ShapeId( entry.ToCString() ) ;
862   
863   /* Create a new label */
864   TDF_Label NewLab = Lab.NewChild();
865   TCollection_ExtendedString Value("Arguments");
866   TDataStd_Name::Set(NewLab,Value);
867   
868   TDF_Label NewLab1 = NewLab.NewChild();
869   TDF_Label RefLab;
870   TDF_Tool::Label(OCAFDoc->GetData(), shape_ptr->ShapeId(), RefLab);
871   TDF_Reference::Set(NewLab1, RefLab);
872 }
873
874
875 //=================================================================================
876 // function : InsertInLabelMoreArguments()
877 // purpose  :
878 //=================================================================================
879 void GEOM_Gen_i::InsertInLabelMoreArguments(TopoDS_Shape main_topo,
880                                             GEOM::GEOM_Shape_ptr result,
881                                             const GEOM::GEOM_Gen::ListOfIOR& ListShapes,                                
882                                             Handle(TDocStd_Document) OCAFDoc)
883 {
884   /* Put shape and name into geom/OCAF doc */
885   GEOMDS_Commands GC(OCAFDoc->Main());
886   /* Add attributs TopoDS and name_ior in a new label */
887   TDF_Label Lab = GC.AddShape(main_topo, result->Name() );
888   TCollection_AsciiString entry;
889   TDF_Tool::Entry(Lab, entry);
890   
891   /* Create a new label */
892   TDF_Label NewLab = Lab.NewChild();
893   TCollection_ExtendedString Value("Arguments");
894   TDataStd_Name::Set(NewLab, Value);
895
896   for (unsigned int ind = 0; ind < ListShapes.length(); ind++) {
897     
898     TDF_Label NewLab1 = NewLab.NewChild();    
899     GEOM::GEOM_Shape_var aShape = GetIORFromString( ListShapes[ind] );
900     
901     TDF_Label RefLab;
902     TDF_Tool::Label(OCAFDoc->GetData(), aShape->ShapeId(), RefLab);
903     TDF_Reference::Set(NewLab1, RefLab);
904   }
905   result->ShapeId(entry.ToCString());
906 }
907
908
909
910 //=================================================================================
911 // function: NbLabels()
912 // purpose : 
913 //=================================================================================
914 CORBA::Short GEOM_Gen_i::NbLabels()
915 {
916   TDF_ChildIterator ChildIterator(myCurrentOCAFDoc->Main());
917   unsigned int i = 1;
918   
919   while (ChildIterator.More()) {
920     i++;
921     ChildIterator.Next();
922   }
923   return i;
924   //  return TDF_Tool::NbLabels( myCurrentOCAFDoc->Main() );
925 }
926
927
928
929 //=================================================================================
930 // function: GetCurrentStudy()
931 // purpose : Finds or creates the geom/OCAF document corresponding to the index
932 // 'StudyID'
933 //=================================================================================
934 void GEOM_Gen_i::GetCurrentStudy(CORBA::Long StudyID)
935 {
936   /* If StudyID is known we link myCurrentOCAFDoc to it */
937   if (myStudyIDToDoc.IsBound(StudyID)) {
938     myCurrentOCAFDoc =  Handle(TDocStd_Document)::DownCast(myStudyIDToDoc(StudyID));
939   }
940   /* Create a new OCAFDoc and link it to 'StudyID' argument */
941   else { 
942     myOCAFApp->NewDocument("SALOME_GEOM",myCurrentOCAFDoc);
943     myStudyIDToDoc.Bind(StudyID,myCurrentOCAFDoc);
944   } 
945   myStudyID = StudyID;
946 }
947
948
949 //================================================================================
950 // function : CreateObject() 
951 // purpose  : private function to create a complete CORBA object and return it
952 //================================================================================
953 GEOM::GEOM_Shape_ptr GEOM_Gen_i::CreateObject(TopoDS_Shape& tds)
954 {
955 //   if ( tds.ShapeType() == TopAbs_COMPOUND ) {
956 //     TopoDS_Iterator itr(tds);
957 //     TopoDS_Shape res;
958 //     int i = 0;
959 //     while (itr.More()) {
960 //       i++;
961 //       res = itr.Value();
962 //       itr.Next();
963 //     }
964     
965 //     if ( i == 1 )
966 //       tds = res;
967 //   }
968
969   GEOM::shape_type st = GEOM::shape_type(tds.ShapeType()) ; /* casting */
970   
971   /* Create the CORBA servant holding the TopoDS_Shape */
972   GEOM::GEOM_Gen_ptr engine = POA_GEOM::GEOM_Gen::_this();
973   GEOM::GEOM_Shape::ListOfSubShapeID_var index = new GEOM::GEOM_Shape::ListOfSubShapeID;
974   index->length(0);  
975   GEOM_Shape_i * shape_servant = new GEOM_Shape_i(tds, _orb, engine, index, st, true);
976   GEOM::GEOM_Shape_var shape = GEOM::GEOM_Shape::_narrow(shape_servant->_this()); 
977   
978   /* Create and set the name (IOR of shape converted into a string) */
979   string name_ior = _orb->object_to_string(shape) ;
980   shape->Name( name_ior.c_str() );  
981   shape->NameType( "" );
982   return shape;
983 }
984
985 //=======================================================================
986 //function : CreateSubObject
987 //purpose  : 
988 //=======================================================================
989
990 GEOM::GEOM_Shape_ptr GEOM_Gen_i::CreateSubObject(const TopoDS_Shape& SubShape,
991                                                  const GEOM::GEOM_Shape_ptr MainShape,
992                                                  const GEOM::GEOM_Shape::ListOfSubShapeID& ListOfID)
993 {
994   GEOM::shape_type st = GEOM::shape_type(SubShape.ShapeType()) ; /* casting */
995   
996   /* Create the CORBA servant holding the TopoDS_Shape */
997   GEOM::GEOM_Gen_ptr engine = POA_GEOM::GEOM_Gen::_this();
998   GEOM_Shape_i * shape_servant =
999     new GEOM_Shape_i(SubShape, _orb, engine, ListOfID, st, false);
1000   GEOM::GEOM_Shape_var shape = GEOM::GEOM_Shape::_narrow(shape_servant->_this()); 
1001   
1002     /* Create and set the name (IOR of shape converted into a string) */
1003   string name_ior = _orb->object_to_string(shape) ;
1004   shape->Name( name_ior.c_str() );
1005     /* create and set the mainname (IOR of shape converted into a string) */
1006   const char *mainname_ior = _orb->object_to_string(MainShape) ;
1007   shape->MainName(mainname_ior);
1008     /* precaution : NameType will be set precisely in GUI */    
1009   shape->NameType( "" );
1010     /* add 'SubShape' its 'nameIOR' and a reference to the main shape thanks to method below  */
1011   const char *entry =
1012     InsertInLabelDependentShape(SubShape, shape->Name(), MainShape, myCurrentOCAFDoc) ;
1013   shape->ShapeId( entry ) ;
1014  
1015   return shape;
1016 }
1017
1018 //=======================================================================
1019 // function : SuppressFacesGlue()
1020 // purpose  : Define a compound of shells after suppress of mapFaces in the 
1021 //          : shape S and return the number of shells of the compound.
1022 //=======================================================================
1023 int GEOM_Gen_i::SuppressFacesGlue( const TopoDS_Shape& S,
1024                                    const TopTools_MapOfShape& mapFaces,
1025                                    TopoDS_Shape& aCompoundOfShells )
1026   throw (SALOME::SALOME_Exception)
1027 {  
1028   Unexpect aCatch(SALOME_SalomeException);
1029   BRepTools_Quilt Glue;
1030   aCompoundOfShells.Nullify() ;
1031   
1032   for ( TopExp_Explorer exp( S, TopAbs_FACE); exp.More(); exp.Next() ) {
1033     const TopoDS_Face& F = TopoDS::Face(exp.Current());
1034     if ( !mapFaces.Contains(F) ) {
1035       /* this face must not to be suppressed */
1036       Glue.Add(F);
1037     }
1038   }
1039   
1040   /* Use specif method to calculate the compound of shells */
1041   aCompoundOfShells = Glue.Shells();
1042   
1043   if( aCompoundOfShells.ShapeType() != TopAbs_COMPOUND ) {
1044     THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::SuppressFacesGlue() : not a GEOM::COMPOUND", SALOME::BAD_PARAM);
1045   }
1046
1047   /* explore Compound for verification and return the number of shells */
1048   int numberOfShell = 0 ;
1049   for ( TopExp_Explorer exp1( aCompoundOfShells, TopAbs_SHELL); exp1.More(); exp1.Next() )
1050     numberOfShell++ ;
1051
1052   return numberOfShell ;
1053 }
1054
1055
1056 //=====================================================================================
1057 // function : GetIndexTopology()
1058 // purpose  : return the index of a sub shape in a shape (index starts at 1)
1059 //          : Return -1 if not found
1060 //=====================================================================================
1061 int GEOM_Gen_i::GetIndexTopology(const TopoDS_Shape& subshape, const TopoDS_Shape& mainShape) 
1062
1063   if( mainShape.IsNull() || subshape.IsNull() ) 
1064     return -1 ; 
1065
1066   int index = 1; 
1067   if (subshape.ShapeType() == TopAbs_COMPOUND) 
1068     { 
1069       TopoDS_Iterator it; 
1070       TopTools_ListOfShape CL; 
1071       CL.Append( mainShape ); 
1072       TopTools_ListIteratorOfListOfShape itC; 
1073       for (itC.Initialize( CL ); itC.More(); itC.Next()) 
1074         { 
1075           for (it.Initialize( itC.Value() );  it.More(); it.Next()) 
1076             { 
1077               if ( it.Value().ShapeType() == TopAbs_COMPOUND) 
1078                 {
1079                   if (it.Value().IsSame(subshape)) 
1080                     return index; 
1081                   else 
1082                     index++; 
1083                   CL.Append( it.Value() ); 
1084                 }
1085             } 
1086         } 
1087     } 
1088   else 
1089     { 
1090       TopExp_Explorer Exp ( mainShape,  subshape.ShapeType() ); 
1091       TopTools_MapOfShape M; 
1092       while ( Exp.More() ) 
1093         { 
1094           if ( M.Add(Exp.Current()) ) 
1095             { 
1096               if ( Exp.Current().IsSame(subshape) ) 
1097                 return index; 
1098               index++; 
1099             } 
1100           Exp.Next(); 
1101         } 
1102     } 
1103   return -1; 
1104
1105
1106
1107 //================================================================================
1108 // function : IndexOfFacesOfSubShell()
1109 // purpose  : Return a list of indices corresponding to the faces of a 'subShell'
1110 //          : in the main shape 'S'
1111 //================================================================================
1112 GEOM::GEOM_Shape::ListOfSubShapeID* GEOM_Gen_i::IndexOfFacesOfSubShell( const TopoDS_Shape& S,
1113                                                                   const TopoDS_Shape subShell )
1114   throw (SALOME::SALOME_Exception)
1115 {
1116
1117   Unexpect aCatch(SALOME_SalomeException);
1118   GEOM::GEOM_Shape::ListOfSubShapeID_var ListOfID = new GEOM::GEOM_Shape::ListOfSubShapeID;
1119   ListOfID->length(0) ;
1120   if( subShell.IsNull() || subShell.ShapeType() != TopAbs_SHELL ) {
1121     THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::IndexOfFacesOfSubShell() : null shape or not a GEOM::SHELL", SALOME::BAD_PARAM);
1122   }
1123
1124   /* put faces of subShell in a Map of faces */
1125   int j = 0 ;
1126   TopTools_MapOfShape mapFaces ;
1127   for( TopExp_Explorer Exp1( subShell, TopAbs_FACE );  Exp1.More(); Exp1.Next() ) {
1128     mapFaces.Add(Exp1.Current() ) ;
1129     j++ ;
1130   }
1131
1132   if( j<1 )
1133     THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::IndexOfFacesOfSubShell() : no faces in sub shell", SALOME::BAD_PARAM);
1134   
1135   /* Find index of each face of subshell in the main topology and put its index in ListOfID */
1136   int size = 0 ;
1137   for ( TopExp_Explorer Exp2(S, TopAbs_FACE); Exp2.More();  Exp2.Next() ) {
1138     
1139     const TopoDS_Face& F = TopoDS::Face( Exp2.Current() ) ;
1140
1141     if( mapFaces.Contains(F) )  {
1142       int n = GetIndexTopology( F, S ) ;
1143       if( n<=0 ) {
1144         THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::IndexOfFacesOfSubShell() : no index found", SALOME::BAD_PARAM);    
1145       }
1146       size++;
1147       ListOfID->length(size) ;
1148       ListOfID[size-1] = n ;
1149     }
1150   }
1151
1152   return ListOfID._retn() ;
1153 }
1154
1155
1156
1157 //================================================================================
1158 // function : ListOfIDIntoMapOfShapes()
1159 // purpose  : Define a MapOfShapes from a main topology 'S' a 'subShapeType'
1160 //          : and a list of indices 'L'.
1161 //          : Return true if 'aMap' is not empty
1162 //================================================================================
1163 bool GEOM_Gen_i::ListOfIDIntoMapOfShapes( const TopoDS_Shape& S,
1164                                           const GEOM::GEOM_Shape::ListOfSubShapeID& L,
1165                                           const int subShapeType,
1166                                           TopTools_MapOfShape& aMap )
1167 {
1168   if( L.length() < 1 || S.IsNull() ) {
1169     return false ;
1170   }
1171   
1172   aMap.Clear() ; 
1173   for( int k=0; k<L.length(); k++ ) {
1174     /* indices start at 1 in list L */
1175     int j = 1 ;
1176     TopExp_Explorer exp ;
1177     TopTools_MapOfShape M; 
1178     for(  exp.Init( S, TopAbs_ShapeEnum(subShapeType) ); exp.More(); exp.Next() ) {
1179       if ( M.Add(exp.Current()) ) 
1180         { 
1181           if( L[k] == j ) {
1182             aMap.Add( exp.Current() ) ;
1183           }
1184           j++ ;
1185         }
1186     }
1187   }
1188   return true ;
1189 }
1190
1191
1192
1193 //================================================================================
1194 // function : ListOfIDIntoSequenceOfShapes()
1195 // purpose  : Define 'aSequenceOfShapes' from a main topology 'S' a 'subShapeType'
1196 //          : and a list of indices 'L'.
1197 //          : Return true if 'aSequenceOfShapes' is not empty
1198 //================================================================================
1199 bool GEOM_Gen_i::ListOfIDIntoSequenceOfShapes( const TopoDS_Shape& S,
1200                                                const GEOM::GEOM_Shape::ListOfSubShapeID& L,
1201                                                const int subShapeType,
1202                                                TopTools_SequenceOfShape& aSequenceOfShapes )
1203 {
1204   if( L.length() < 1 || S.IsNull() ) {
1205     return false ;
1206   }
1207   
1208   aSequenceOfShapes.Clear() ; 
1209   for( int k=0; k<L.length(); k++ ) {
1210     /* indices start at 1 in list L */
1211     int j = 1 ;
1212     TopExp_Explorer exp ;
1213     for(  exp.Init( S, TopAbs_ShapeEnum(subShapeType) ); exp.More(); exp.Next() ) {
1214       if( L[k] == j ) {
1215         aSequenceOfShapes.Append( exp.Current() ) ;
1216       }
1217       j++ ;
1218     }
1219   }
1220   return true ;
1221 }
1222
1223
1224
1225 //================================================================================
1226 // function : SuppressFaces()
1227 // purpose  : Suppress faces contained in ListOfID from 'shape'.
1228 //          : Return a list of Geom shapes each one is a main shape GEOM::FACE or GEOM::SHELL
1229 //================================================================================
1230 GEOM::GEOM_Gen::ListOfGeomShapes* GEOM_Gen_i::SuppressFaces( GEOM::GEOM_Shape_ptr shape,
1231                                                                 const GEOM::GEOM_Shape::ListOfSubShapeID& ListOfID ) 
1232   throw (SALOME::SALOME_Exception)
1233 {
1234   Unexpect aCatch(SALOME_SalomeException);
1235   GEOM::GEOM_Gen::ListOfGeomShapes_var listOfGeomShapes = new GEOM::GEOM_Gen::ListOfGeomShapes;
1236   listOfGeomShapes->length(0) ;
1237
1238   TopoDS_Shape mainShape = GetTopoShape(shape);
1239   if( mainShape.IsNull() )
1240     THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::SuppressFaces() : null argument shape", SALOME::BAD_PARAM);
1241   
1242   if( ListOfID.length() < 1 )
1243     THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::SuppressFaces() : empty ListOfID", SALOME::BAD_PARAM);
1244   
1245   /* Define 'mapFaces' a map of faces to be suppressed in mainShape */
1246   TopTools_MapOfShape mapFaces ;
1247   if( !ListOfIDIntoMapOfShapes(mainShape, ListOfID, TopAbs_FACE, mapFaces ) ) {
1248     return listOfGeomShapes._retn();
1249   }
1250     
1251   /* Call algorithm to calculate a compound of shells resulting of face suppression */
1252   int numberOfShells = 0 ;
1253   TopoDS_Shape aCompoundOfShells ;
1254   numberOfShells = SuppressFacesGlue(mainShape, mapFaces, aCompoundOfShells) ;
1255   if(numberOfShells < 1) {
1256     THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::Suppressfaces() : no shells", SALOME::BAD_PARAM);
1257   }
1258  
1259   /* Create a shell for each shell contained in 'aCompoundOfShells' and             */ 
1260   /* put it in the list of GeomShapes to be returned.                               */
1261   /* But if the shell is composed of only a face we create a face and not a shell   */
1262   int i = 0 ;
1263   for( TopExp_Explorer exp(aCompoundOfShells, TopAbs_SHELL); exp.More(); exp.Next() ) {
1264
1265     const TopoDS_Shell& aShell = TopoDS::Shell( exp.Current() );    
1266     if( aShell.IsNull() ) {
1267       THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::Suppressfaces() : null shell", SALOME::BAD_PARAM);
1268     }
1269     
1270     GEOM::GEOM_Shape::ListOfSubShapeID_var aList = new GEOM::GEOM_Shape::ListOfSubShapeID;
1271     aList = IndexOfFacesOfSubShell(mainShape, aShell) ;
1272
1273      if( aList->length() < 1 ) {
1274       THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::SuppressFaces() : aList is empty", SALOME::BAD_PARAM);
1275     }
1276
1277     TopoDS_Shape aShellOrFace ;
1278     /* Only a face into the shell : we create a single face instead of a shell : 'aList' is unchanged  */
1279     if( aList->length() == 1 ) {
1280       TopExp_Explorer exp ;
1281       exp.Init( aShell, TopAbs_FACE ) ;
1282       exp.More() ;
1283       aShellOrFace = exp.Current() ;
1284     }
1285     else {
1286       aShellOrFace = aShell ;
1287     }
1288     
1289     /* Create CORBA object */
1290     GEOM::GEOM_Shape_var result = CreateObject(aShellOrFace) ;
1291     if( CORBA::is_nil(result) ) {
1292       THROW_SALOME_CORBA_EXCEPTION("Suppress Faces aborted : null result", SALOME::BAD_PARAM);
1293     }
1294
1295     InsertInLabelOneArgument(mainShape, shape, aShellOrFace, result, myCurrentOCAFDoc) ;
1296     i++ ;
1297     listOfGeomShapes->length(i) ;
1298     listOfGeomShapes[i-1] = result ;
1299   }
1300
1301   return listOfGeomShapes._retn() ;
1302 }
1303
1304
1305
1306 //================================================================================
1307 // function : IsShapeInSequence()
1308 // purpose  : return true is aShape is in SS. The test method is 'IsSame()'
1309 //================================================================================
1310 bool GEOM_Gen_i::IsShapeInSequence(const TopTools_SequenceOfShape& SS, const TopoDS_Shape& aShape)
1311 {
1312   if( aShape.IsNull() || SS.IsEmpty() ) 
1313     return false ;  
1314   for( int i=1; i<=SS.Length(); i++) {
1315     if( SS.Value(i).IsSame(aShape) )
1316       return true ;
1317   }
1318   return false ;
1319 }
1320
1321
1322 //================================================================================
1323 // function : FreeEdgesFromMapOfFace()
1324 // purpose  : Define MS a map of all edges of faces of 'MSfaces'
1325 //          : All multiple edges are removed !
1326 //================================================================================
1327 void GEOM_Gen_i::FreeEdgesFromMapOfFace( const TopTools_MapOfShape& MSfaces,
1328                                          TopTools_MapOfShape& MS )
1329 {
1330   MS.Clear() ;
1331   TopTools_MapOfShape Multiple ;
1332   TopTools_MapIteratorOfMapOfShape it ;
1333   for( it.Initialize(MSfaces); it.More(); it.Next() ) {
1334     TopoDS_Shape aFace = it.Key() ;
1335     TopExp_Explorer exp ;
1336     for( exp.Init( aFace, TopAbs_EDGE); exp.More(); exp.Next() ) {
1337       if( !Multiple.Contains( exp.Current() ) && !MS.Add( exp.Current() ) ) {
1338         MS.Remove( exp.Current() ) ;
1339         Multiple.Add( exp.Current() ) ;
1340       }
1341     }
1342   }
1343   return ;
1344 }
1345
1346
1347 //================================================================================
1348 // function : MapRemoveSequence()
1349 // purpose  : In term of shapes ST = MS - SSRemove
1350 //          :
1351 //================================================================================
1352 void GEOM_Gen_i::MapRemoveSequence( const TopTools_MapOfShape& MS,
1353                                     const TopTools_SequenceOfShape& SSRemove,
1354                                     TopTools_SequenceOfShape& ST ) 
1355 {
1356   ST.Clear() ;
1357   TopTools_MapIteratorOfMapOfShape it ;
1358   for( it.Initialize(MS); it.More(); it.Next() ) {
1359     TopoDS_Shape aShape = it.Key() ;
1360     if( !IsShapeInSequence( SSRemove, aShape ) )
1361       ST.Append( aShape ) ;
1362   }
1363   return ;
1364 }
1365
1366
1367
1368 //================================================================================
1369 // function : SuppressHoleSubRoutine()
1370 // purpose  : Define recursively 'MSfacesSuppress' a list of faces to suppress in a hole
1371 //================================================================================
1372 void GEOM_Gen_i::SuppressHoleSubRoutine( const TopoDS_Shape& mainShape,
1373                                          const TopoDS_Face& aFace,
1374                                          const TopTools_SequenceOfShape& SSedgesOfWire, 
1375                                          const TopTools_IndexedDataMapOfShapeListOfShape& aMapEdgesFaces,
1376                                          const TopTools_MapOfShape& MSfaces,                                     
1377                                          TopTools_MapOfShape& MSfacesSuppress,
1378                                          const Standard_Boolean withEndFace,
1379                                          const TopoDS_Face& endFace,
1380                                          TopTools_MapOfShape& MSwireEndEdges )
1381   throw (SALOME::SALOME_Exception)
1382 {  
1383   Unexpect aCatch(SALOME_SalomeException);
1384   TopTools_MapOfShape MS ;
1385   TopTools_SequenceOfShape SU ;
1386   FreeEdgesFromMapOfFace(MSfaces, MS) ;        /* MS = free edges of MSfaces */
1387   MapRemoveSequence(MS, SSedgesOfWire, SU) ;   /* SU = MS - SSedgesOfWire    */
1388
1389   if( SU.IsEmpty() ) {
1390     return ;
1391   }
1392
1393   /* Here SU contains new edges to find new faces to suppress                                          */
1394   /* Define the list of faces of SU edges that aren't in faces of MSfacesSuppress in order to add into */
1395   /* For each edge we have a map of all its faces : it's in 'aMapEdgesFaces'                           */
1396   TopTools_MapOfShape MSfacesTmp ;
1397   for( int v=1; v<=SU.Length(); v++ ) {
1398     TopoDS_Shape E = SU.Value(v) ;
1399     TopoDS_Shape F ;
1400     TopTools_ListOfShape LF ;
1401     int ind = aMapEdgesFaces.FindIndex(E) ;
1402     
1403     /* LF is the list of faces for an edge of SU : may be empty no matter */
1404     LF = aMapEdgesFaces.FindFromIndex(ind) ;
1405     
1406     TopTools_ListIteratorOfListOfShape it ;
1407     for( it.Initialize(LF); it.More(); it.Next() ) {
1408       F = it.Value() ;
1409       if( withEndFace == false ) {
1410         if( F.IsSame(aFace) )
1411           THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHoleSubRoutine() : hole traversing or ?", SALOME::BAD_PARAM);
1412         if( !MSfacesSuppress.Contains(F) ) {
1413           MSfacesSuppress.Add(F) ;
1414           MSfacesTmp.Add(F) ; // Dont remove the 'if' !
1415         }
1416       }
1417       else { /* withEndFace == true */
1418         if( F.IsSame(aFace) && !F.IsSame(endFace) )
1419           THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHoleSubRoutine() : hole traversing incoherent ?", SALOME::BAD_PARAM);
1420         
1421         if( F.IsSame(endFace) ) {
1422           /* We have reached endFace if selection was correct so we add  */
1423           /* edge in a map to find later the corresponding endWire (hole */
1424           MSwireEndEdges.Add(E) ;
1425         }
1426         else {
1427           if( !MSfacesSuppress.Contains(F) ) {
1428             MSfacesSuppress.Add(F) ;
1429             MSfacesTmp.Add(F) ;
1430           }
1431         }
1432       }
1433     }
1434   }
1435   /* Call recursively this routine */
1436   SuppressHoleSubRoutine( mainShape, aFace, SSedgesOfWire, aMapEdgesFaces, MSfacesTmp, MSfacesSuppress, withEndFace, endFace, MSwireEndEdges ) ; 
1437 }
1438
1439
1440
1441 //================================================================================
1442 // function : GetShapeFromIndex()
1443 // purpose  : Find 'tds' a sub shape of 'aShape' according to 'aList' that contains
1444 //          : a unique index !
1445 //          : Warning : index must be setted with the same exploration logic !
1446 //          : So 'index' is calculated with no shape doublons !
1447 //================================================================================
1448 bool GEOM_Gen_i::GetShapeFromIndex( const TopoDS_Shape& aShape,
1449                                     const TopAbs_ShapeEnum aType, 
1450                                     const int index,
1451                                     TopoDS_Shape& tds )
1452
1453 {
1454   if (aShape.IsNull() || index < 1) 
1455     return false ;
1456   /* Indices start at 1 */
1457   int j = 1 ;
1458   bool found = false ;
1459   TopExp_Explorer exp ;
1460   TopTools_MapOfShape M;
1461   for( exp.Init( aShape, aType ); exp.More(); exp.Next() ) {
1462     if( M.Add(exp.Current()) ) { /* if not a doublon : we compare */
1463       if( index == j ) {
1464         tds =  exp.Current() ;
1465         return true ;
1466       }
1467       j++ ;
1468     }
1469   }
1470   return false ;
1471 }
1472
1473
1474
1475 //================================================================================
1476 // function : SuppressHolesInFaceOrShell()  Main method.
1477 // purpose  : Suppress holes identified by wires in a single face or shell
1478 //
1479 //================================================================================
1480 GEOM::GEOM_Shape_ptr GEOM_Gen_i::SuppressHolesInFaceOrShell( GEOM::GEOM_Shape_ptr shapeFaceShell,
1481                                                        const GEOM::GEOM_Shape::ListOfSubShapeID& ListIdWires )
1482   throw (SALOME::SALOME_Exception)
1483 {
1484   Unexpect aCatch(SALOME_SalomeException);
1485   GEOM::GEOM_Shape_var result;
1486
1487   if( ListIdWires.length() < 1 )
1488     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHolesInFace : no holes selected", SALOME::BAD_PARAM);
1489   
1490   const TopoDS_Shape tds = GetTopoShape(shapeFaceShell) ;
1491   if( tds.IsNull() || !IsValid(tds) )
1492     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHolesInFace() : non valid main argument", SALOME::BAD_PARAM);
1493   
1494   /* Create a map of wires/holes to suppress */
1495   TopTools_MapOfShape MapHoles ;
1496   for ( int i = 0; i < ListIdWires.length(); i++ ) {
1497     TopoDS_Shape W ;    
1498     if( !GetShapeFromIndex( tds, TopAbs_WIRE, ListIdWires[i], W ) )
1499       THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHolesInFace() : bad index ?", SALOME::BAD_PARAM);
1500     MapHoles.Add( W ) ;
1501   }
1502
1503   /* Test if argument is a face or shell */
1504   bool isFace ;
1505   if( tds.ShapeType() == TopAbs_FACE )
1506     isFace = true ;
1507   else if ( tds.ShapeType() == TopAbs_SHELL )
1508     isFace = false ;
1509   else
1510     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHolesInFace() : not a face or a shell", SALOME::BAD_PARAM); 
1511
1512   /* Define two maps : all faces and faces to that will be modified */
1513   TopTools_MapOfShape MapFacesToModify ;
1514   TopTools_MapOfShape MapFacesAll ;
1515   TopExp_Explorer expF ;
1516   for( expF.Init( tds, TopAbs_FACE);  expF.More(); expF.Next() ) {
1517     TopoDS_Face F = TopoDS::Face( expF.Current() ) ;
1518     MapFacesAll.Add(F) ;
1519     TopExp_Explorer expW ;
1520     for( expW.Init( F, TopAbs_WIRE);  expW.More(); expW.Next() ) {
1521       TopoDS_Wire W = TopoDS::Wire( expW.Current() ) ;
1522       if( MapHoles.Contains(W) ) {
1523         MapFacesToModify.Add(F) ;
1524       }
1525     }
1526   }
1527
1528   /* Define faces not modified */
1529   TopTools_MapOfShape MapFacesNotModified ;
1530   TopTools_MapIteratorOfMapOfShape it ;
1531   for( it.Initialize(MapFacesAll); it.More(); it.Next() ) {
1532     TopoDS_Face FF = TopoDS::Face( it.Key() ) ;
1533     if( !MapFacesToModify.Contains(FF) )
1534       MapFacesNotModified.Add(FF) ;
1535   }
1536
1537   if( MapFacesToModify.IsEmpty() )
1538     THROW_SALOME_CORBA_EXCEPTION("Error : empty map of faces", SALOME::BAD_PARAM); 
1539   
1540   if( isFace && MapFacesToModify.Extent() != 1 )
1541     THROW_SALOME_CORBA_EXCEPTION("Incoherent", SALOME::BAD_PARAM);
1542   
1543   /* Main argument is a face */
1544   if( isFace && MapFacesToModify.Extent() == 1 ) {
1545     TopoDS_Face resultFace ;
1546     if( !RebuildFaceRemovingHoles( TopoDS::Face(tds), MapHoles, resultFace ) )
1547       THROW_SALOME_CORBA_EXCEPTION(" Problem : !RebuildFaceRemovingHoles()", SALOME::BAD_PARAM);
1548     /* Creation of CORBA object : face topology */
1549     result = CreateObject(resultFace);
1550     InsertInLabelOneArgument(tds, shapeFaceShell, resultFace, result, myCurrentOCAFDoc) ;
1551     return result ;
1552   }
1553
1554   /* Main argument is a shell : rebuild faces modified */
1555   TopTools_MapOfShape MapFacesModified ;
1556   for( it.Initialize(MapFacesToModify); it.More(); it.Next() ) {
1557     TopoDS_Face FF = TopoDS::Face( it.Key() ) ;
1558     TopoDS_Face resF ;
1559     if( !RebuildFaceRemovingHoles( FF, MapHoles, resF ) )
1560       THROW_SALOME_CORBA_EXCEPTION(" Problem shell : !RebuildFaceRemovingHoles()", SALOME::BAD_PARAM);
1561     MapFacesModified.Add(resF) ;
1562   }
1563
1564   /* Rebuild the shell with faces modified and non modified */
1565   TopoDS_Shell resultShell ;
1566   BRepPrim_Builder B;
1567   B.MakeShell(resultShell) ;
1568   TopTools_MapIteratorOfMapOfShape it1 ;
1569   for( it1.Initialize(MapFacesModified); it1.More(); it1.Next() )
1570     B.AddShellFace( resultShell,TopoDS::Face( it1.Key() ) ) ;
1571   for( it1.Initialize(MapFacesNotModified); it1.More(); it1.Next() )
1572     B.AddShellFace( resultShell,TopoDS::Face( it1.Key() ) ) ;
1573   
1574   B.CompleteShell(resultShell) ;
1575   
1576   if( resultShell.IsNull() )
1577     THROW_SALOME_CORBA_EXCEPTION("Null or not valid result Shell", SALOME::BAD_PARAM) ;
1578   
1579   /* Creation of CORBA object : shell topology */
1580   result = CreateObject(resultShell);
1581   InsertInLabelOneArgument(tds, shapeFaceShell, resultShell, result, myCurrentOCAFDoc) ;
1582   return result ;
1583 }
1584
1585
1586 //================================================================================
1587 // function : RebuildFaceRemovingHoles()
1588 // purpose  : Rebuild a face removing holes that are in 'mapHoles'.
1589 //          : NB : 'mapHoles' may content more holes than necessary
1590 //================================================================================
1591 bool GEOM_Gen_i::RebuildFaceRemovingHoles( const TopoDS_Face& aFace,
1592                                            const TopTools_MapOfShape& mapHoles,
1593                                            TopoDS_Shape& resultFace )
1594 {
1595   /* Get the outer wire of the face 'aFace' */
1596   TopoDS_Wire outW = BRepTools::OuterWire( aFace ) ;
1597   if( outW.IsNull() || !IsValid(outW) )
1598     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHolesInFace : bad outer wire of 'aFace'", SALOME::BAD_PARAM);
1599   
1600   /* Rebuild a face avoiding holes in the map 'mapHoles' */  
1601   Handle(Geom_Surface) Surface = BRep_Tool::Surface(aFace) ;
1602   TopoDS_Face F2 = BRepBuilderAPI_MakeFace( Surface, outW, true ) ;
1603   
1604   if( F2.Orientation() != aFace.Orientation() )
1605     F2.Orientation( aFace.Orientation() ) ;
1606   
1607   BRepBuilderAPI_MakeFace aBuilder( F2 ) ;
1608   bool foundAndKeepHoles = false ;
1609   TopExp_Explorer exp ;
1610   
1611   for( exp.Init( aFace, TopAbs_WIRE);  exp.More(); exp.Next() ) {
1612     TopoDS_Wire hole = TopoDS::Wire( exp.Current() ) ;
1613     if( !mapHoles.Contains(hole) && !exp.Current().IsEqual(outW) ) {
1614       aBuilder.Add( hole) ;      
1615       if( !aBuilder.IsDone() )
1616         THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHolesInFace : builder problem !", SALOME::BAD_PARAM);      
1617       
1618       resultFace = TopoDS::Face(aBuilder) ;
1619       foundAndKeepHoles = true ;
1620     }
1621   }
1622   
1623   if( !foundAndKeepHoles )
1624     resultFace = F2 ;
1625   else
1626     resultFace = TopoDS::Face(aBuilder) ;
1627   
1628   return true ;
1629 }
1630
1631
1632
1633
1634 //================================================================================
1635 // function : SuppressHole() Main method.
1636 // purpose  : Suppress an hole identified by a wire in a face of shape
1637 //          : ListIdFace contains a unique index of face in shape
1638 //          : ListIdWire contains a unique index of wire in face !!!
1639 //          : ListIdEndFace is used only when hole traverse.
1640 //================================================================================
1641 GEOM::GEOM_Shape_ptr GEOM_Gen_i::SuppressHole( GEOM::GEOM_Shape_ptr shape,
1642                                          const GEOM::GEOM_Shape::ListOfSubShapeID& ListIdFace,
1643                                          const GEOM::GEOM_Shape::ListOfSubShapeID& ListIdWire,
1644                                          const GEOM::GEOM_Shape::ListOfSubShapeID& ListIdEndFace )
1645   throw (SALOME::SALOME_Exception)
1646 {
1647   Unexpect aCatch(SALOME_SalomeException);
1648   GEOM::GEOM_Shape_var result;
1649   TopoDS_Face aFace ;
1650   TopoDS_Wire aWire ;  
1651   TopoDS_Face endFace ;
1652   bool withEndFace ;
1653   TopoDS_Shape tmp ;
1654   
1655   /* Retrieve 'aShape' the initial main shape selection */
1656   const TopoDS_Shape aShape = GetTopoShape(shape);
1657   
1658   if( !IsValid(aShape) )
1659     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHole() : non valid main shape", SALOME::BAD_PARAM);
1660   
1661   if( ListIdFace.length() != 1 || ListIdWire.length() != 1 )
1662     THROW_SALOME_CORBA_EXCEPTION("bad list", SALOME::BAD_PARAM);  
1663   
1664   /* Retrieve 'aFace' selection */
1665   if( !GetShapeFromIndex( aShape, TopAbs_FACE, ListIdFace[0], tmp ) ) {
1666     THROW_SALOME_CORBA_EXCEPTION("face not found", SALOME::BAD_PARAM);
1667   }
1668   else {
1669     aFace = TopoDS::Face(tmp) ;
1670   }
1671   if( !IsValid(aFace) )
1672     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHole() : face shape not valid", SALOME::BAD_PARAM);  
1673   
1674    /* Retrieve 'aWire' selection : Warning : index of wire refers to the face ! */
1675   TopoDS_Shape aTmp ;
1676   if( !GetShapeFromIndex( aFace, TopAbs_WIRE, ListIdWire[0], aTmp ) ) {
1677     THROW_SALOME_CORBA_EXCEPTION("wire not found", SALOME::BAD_PARAM);
1678   }
1679   else {
1680     aWire = TopoDS::Wire(aTmp) ;
1681   }
1682   if( !IsValid(aWire) )
1683     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHole() : bad wire" , SALOME::BAD_PARAM);
1684
1685   /* Get the outer wire of aFace */
1686   TopoDS_Wire outerW = BRepTools::OuterWire( aFace ) ;
1687   if( outerW.IsNull() || !IsValid(outerW) ) 
1688     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHole() : bad outer wire", SALOME::BAD_PARAM);
1689   
1690   /* Test bad user selection aWire */
1691   if( aWire.IsSame(outerW) )
1692     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHole() : outerW = aWire", SALOME::BAD_PARAM);
1693    
1694   /* Test if 'endFace' is used  as argument and seems to be a valid one          */
1695   /* NB : 'endFace' is optional and used when hole to suppress traverse 'aShape' */
1696   if( ListIdEndFace.length() == 0 ) {
1697     withEndFace = false ;
1698   }
1699   else {
1700     TopoDS_Shape aTemp ;
1701     if( !GetShapeFromIndex( aShape, TopAbs_FACE, ListIdEndFace[0], aTemp ) || tmp.IsNull() || !IsValid(aTemp) )
1702       THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHole() : non valid endFace", SALOME::BAD_PARAM);
1703
1704     /* Test if 'endFace' as at least one hole */    
1705     endFace = TopoDS::Face(aTemp) ;  
1706
1707     TopExp_Explorer fExp ;
1708     int nbWires = 0 ;
1709     for( fExp.Init(endFace, TopAbs_WIRE);  fExp.More(); fExp.Next() ) {
1710       TopoDS_Wire W = TopoDS::Wire( fExp.Current() ) ;
1711       if( !W.IsNull() && IsValid(W) )
1712         nbWires++ ;
1713     }
1714     if(nbWires > 1)
1715       withEndFace = true ; /* at least 2 wires : outer wire plus an hole or more */
1716     else
1717       THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SuppressHole() : end face selection ?", SALOME::BAD_PARAM);
1718   }
1719   
1720   /* Find edges of aWire and test if degenerated */
1721   TopTools_SequenceOfShape SSedgesOfWire ;
1722   TopExp_Explorer wireExp ;  
1723   for( wireExp.Init(aWire, TopAbs_EDGE);  wireExp.More(); wireExp.Next() ) {
1724     TopoDS_Edge E = TopoDS::Edge( wireExp.Current() ) ;
1725     if( E.IsNull() || BRep_Tool::Degenerated(E) ) {
1726       THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SupressHole() : found bad edge", SALOME::BAD_PARAM);
1727     }
1728     else {
1729       SSedgesOfWire.Append( wireExp.Current() ) ;
1730     }
1731   }
1732   if( SSedgesOfWire.Length() < 1 )
1733     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SupressHole() : no edge(s) for aWire", SALOME::BAD_PARAM); 
1734   
1735   /* Retrieve face ancestors of all edges of 'aWire' but avoiding 'aFace' */ 
1736   
1737   TopTools_IndexedDataMapOfShapeListOfShape aMapEdgesFaces;
1738   TopTools_MapIteratorOfMapOfShape anIt ;
1739   TopTools_MapOfShape MFSuppress ;
1740   TopTools_MapOfShape MFSuppressTmp ;
1741   bool wireOnFace = false ;
1742  
1743   TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, aMapEdgesFaces) ;  
1744   for( int h=1; h<=SSedgesOfWire.Length(); h++ ) {
1745     
1746     TopoDS_Shape anEdgeOfWire = SSedgesOfWire.Value(h) ;
1747     int ind = aMapEdgesFaces.FindIndex(anEdgeOfWire) ;
1748     if(ind < 1)
1749       THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SupressHole() : index of edge", SALOME::BAD_PARAM);
1750     
1751     TopTools_ListOfShape LF;
1752     LF = aMapEdgesFaces.FindFromIndex(ind) ; /* Contains all faces ancestors of an edge of wire */
1753     if( LF.IsEmpty() )
1754       THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SupressHole() : no face for an edge", SALOME::BAD_PARAM);
1755     
1756     /* Filter faces avoiding 'aFace' */
1757     TopTools_ListIteratorOfListOfShape it ;
1758     for( it.Initialize(LF); it.More(); it.Next() ) {
1759       TopoDS_Face F = TopoDS::Face( it.Value() ) ;
1760       if( !F.IsSame(aFace) ) { 
1761         MFSuppressTmp.Add(F) ;
1762         MFSuppress.Add(F) ;
1763       }
1764       else {
1765         wireOnFace = true ;
1766       }
1767     }
1768   }
1769   
1770   if( !wireOnFace ) {
1771     THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SupressHole() : wire not on selected face", SALOME::BAD_PARAM);  
1772   }
1773
1774   /* Call routine to define faces to suppress and and optional endWire on endFace */
1775   TopTools_MapOfShape MSwireEndEdges ; /* will contain edges of final wire (hole) */
1776   SuppressHoleSubRoutine( aShape, aFace, SSedgesOfWire, aMapEdgesFaces, MFSuppressTmp, MFSuppress, withEndFace, endFace, MSwireEndEdges ) ;
1777
1778   TopoDS_Wire endWire ;
1779   if( withEndFace ) {
1780     
1781     if( MSwireEndEdges.Extent() < 1 )
1782       THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SupressHole() : MSwireEndEdges.Extent() < 1", SALOME::BAD_PARAM);
1783
1784     if( !FindCompareWireHoleOnFace( endFace, MSwireEndEdges, endWire ) )           
1785       THROW_SALOME_CORBA_EXCEPTION("in GEOM_Gen_i::SupressHole() : no endWire found", SALOME::BAD_PARAM);    
1786    }
1787    
1788   /* Build 'resTds' : a shape containing a compound of faces */
1789   TopoDS_Shape resTds;
1790   if( !withEndFace && !BuildShapeHoleNotTraversing( aShape, aFace, aWire, MFSuppress, resTds ) )
1791     THROW_SALOME_CORBA_EXCEPTION("Rebuild result shape has aborted", SALOME::BAD_PARAM);
1792   
1793   if( withEndFace && !BuildShapeHoleTraversing( aShape, aFace, aWire, MFSuppress, endFace, endWire, resTds ) )
1794     THROW_SALOME_CORBA_EXCEPTION("Rebuild result shape has aborted (end hole)", SALOME::BAD_PARAM); 
1795   
1796   /* Reconstruction of final shape with 'resTds' : a compound of faces after hole suppressing */
1797   /* Actual limitation is : 'aShape' must not contain more than a solid or a shell !          */
1798   TopoDS_Shape finalShape ;
1799  
1800   TopExp_Explorer exp ;
1801   unsigned int nbSolid = 0 ;
1802   TopoDS_Solid aSolid ;
1803   for( exp.Init(aShape, TopAbs_SOLID); exp.More(); exp.Next() ) {
1804     aSolid = TopoDS::Solid( exp.Current() ) ;
1805     nbSolid++ ;
1806     if( nbSolid > 1 )
1807       THROW_SALOME_CORBA_EXCEPTION("Limitation : main shape contents more than one solid", SALOME::BAD_PARAM);  
1808   }
1809    
1810   unsigned int nbShell = 0 ;
1811   TopoDS_Shell aShell ;
1812   for( exp.Init(aShape, TopAbs_SHELL); exp.More(); exp.Next() ) {
1813     aShell = TopoDS::Shell( exp.Current() ) ;
1814     nbShell++ ;
1815     if( nbShell > 1 )
1816       THROW_SALOME_CORBA_EXCEPTION("Limitation : main shape contents more than one shell", SALOME::BAD_PARAM);
1817   }
1818   
1819   /* No shells and no solids : can send a compound even for a single face, see GUI ! */
1820   if( nbShell == 0 ) {
1821     finalShape = resTds ;
1822   }
1823   
1824   /* a shell */
1825   TopoDS_Shell shellResult ;
1826   if( nbShell == 1 ) {
1827     if ( !BuildShellWithFaceCompound( TopoDS::Compound(resTds), shellResult ) ) 
1828       THROW_SALOME_CORBA_EXCEPTION("Error after BuildShellWithFaceCompound()", SALOME::BAD_PARAM);
1829     finalShape = shellResult ;
1830   }
1831   
1832   /* a solid with a shell */
1833   if( nbSolid == 1 && nbShell == 1) {
1834     BRepBuilderAPI_MakeSolid B;
1835     B.Add(shellResult) ;
1836     if( !B.IsDone() )
1837       THROW_SALOME_CORBA_EXCEPTION("Error : !B.IsDone()", SALOME::BAD_PARAM);  
1838     finalShape = B.Solid() ;
1839   }
1840
1841   result = CreateObject(finalShape);
1842   InsertInLabelOneArgument(aShape, shape, finalShape, result, myCurrentOCAFDoc) ;
1843   return result ;
1844 }
1845
1846
1847
1848 //================================================================================
1849 // function : BuildShellWithFaceCompound()
1850 // purpose  : Build a shell with a compound of faces.
1851 //================================================================================
1852 bool GEOM_Gen_i::BuildShellWithFaceCompound( const TopoDS_Compound Comp,
1853                                              TopoDS_Shell& resultShell )
1854 {
1855   resultShell.Nullify() ;
1856   BRepPrim_Builder B ;
1857   B.MakeShell(resultShell) ;  
1858   TopExp_Explorer ex ;
1859   int i = 0 ;
1860   for( ex.Init( Comp, TopAbs_FACE); ex.More(); ex.Next() ) {
1861     TopoDS_Face F = TopoDS::Face( ex.Current() ) ;
1862     if( !IsValid(F) ) {
1863       return false ;
1864     }
1865     B.AddShellFace( resultShell, F ) ;
1866   }
1867   B.CompleteShell(resultShell) ;
1868   if( resultShell.IsNull() ) {
1869     return false ;
1870   }  
1871   return true ;
1872 }
1873
1874
1875 //================================================================================
1876 // function : FindCompareWireHoleOnFace()
1877 // purpose  : Try to find a wire on 'aFace' which edges are same than those
1878 //          : into 'MSwireEdges' map. 'aFoundWire' is defined and 'true' returned.
1879 //          : 'MSwireEdges' represents generally an hole an 'aFace'.
1880 //          : The outer wire of 'aFace' is avoided !
1881 //================================================================================
1882 bool GEOM_Gen_i::FindCompareWireHoleOnFace( const TopoDS_Face& F,
1883                                             const TopTools_MapOfShape& MSwireEdges,
1884                                             TopoDS_Wire& aFoundWire )
1885 {
1886   aFoundWire.Nullify() ;
1887   
1888   if( F.IsNull() )
1889     return false ;
1890   
1891   /* Get the outer wire of aFace */
1892   TopoDS_Wire outerW = BRepTools::OuterWire(F) ;
1893   if( outerW.IsNull() || !IsValid(outerW) ) {
1894     return false ;
1895   }
1896   
1897   int nbEdges = MSwireEdges.Extent() ;
1898   if( nbEdges < 1 ) {
1899     return false ;
1900   }
1901   
1902   TopExp_Explorer exp1 ;
1903   TopExp_Explorer exp2 ;
1904   for ( exp1.Init(F, TopAbs_WIRE) ; exp1.More(); exp1.Next() ) {
1905     TopoDS_Wire W = TopoDS::Wire( exp1.Current() ) ;
1906     int i = 0 ;
1907     if( !W.IsSame(outerW) ) {
1908       for ( exp2.Init( W, TopAbs_EDGE) ; exp2.More(); exp2.Next() ) {
1909         TopoDS_Edge E = TopoDS::Edge( exp2.Current() ) ;
1910         if( MSwireEdges.Contains(E) ) {
1911           i++ ;
1912           if( i == nbEdges ) {
1913             aFoundWire = W ;
1914             return true ;
1915           }
1916         }
1917       }
1918     }
1919   }
1920   return false ;
1921 }
1922
1923
1924 //================================================================================
1925 // function : BuildShapeHoleNotTraversing()
1926 // purpose  : Define 'resultTds' a reconstruction of 'aShape' after modification
1927 //          : on 'aFace' where 'aWire is removed' and suppression of faces 'MFSuppress'
1928 //          : ( Used as a sub routine of SuppressHole() )
1929 //================================================================================
1930 bool GEOM_Gen_i::BuildShapeHoleNotTraversing( const TopoDS_Shape& aShape,
1931                                               const TopoDS_Face& aFace,
1932                                               const TopoDS_Wire& aWire,
1933                                               const TopTools_MapOfShape& MFSuppress,
1934                                               TopoDS_Shape& resultTds )
1935   throw (SALOME::SALOME_Exception)
1936 {
1937   Unexpect aCatch(SALOME_SalomeException);
1938   BRep_Builder B;
1939   TopExp_Explorer exp ;
1940   TopoDS_Face newFace ;
1941   
1942   resultTds.Nullify() ;
1943   TopoDS_Compound Comp ;
1944   B.MakeCompound (Comp);
1945   
1946   try  {
1947     
1948     /* Explore all faces of 'aShape' to rebuild a compound */
1949     for ( exp.Init(aShape, TopAbs_FACE) ; exp.More(); exp.Next() ) {
1950       
1951       TopoDS_Face F1 = TopoDS::Face( exp.Current() );
1952       /* Rebuild face(s) not suppressed */
1953       if( !MFSuppress.Contains(F1) ) {
1954         
1955         if( F1.IsEqual( aFace ) ) {
1956           TopTools_MapOfShape MSwire ;
1957           MSwire.Add(aWire) ;
1958           if( !RebuildFaceRemovingHoles(aFace, MSwire, newFace) ) {
1959             return false ;
1960           }
1961           B.Add( Comp, newFace ) ;
1962         }
1963         else {
1964           /* For any other face not suppressed */
1965           B.Add( Comp, F1 ) ;
1966         }
1967       }
1968     }
1969   }
1970   catch(Standard_Failure) {
1971     THROW_SALOME_CORBA_EXCEPTION("in BuildShapeHoleNotTraversing() : Exception catched", SALOME::BAD_PARAM);
1972   }  
1973   resultTds = Comp ;
1974   return true ;
1975 }
1976
1977
1978
1979 //================================================================================
1980 // function : BuildShapeHoleTraversing()
1981 // purpose  : Define 'resultTds' a reconstruction of 'aShape' after modifications.
1982 //          : On 'aFace'    'aWire    is removed'
1983 //          : On 'endFace'  'endWire' is removed.
1984 //          : Faces of 'MFSuppress' are removed.
1985 //          : ( Used as a sub routine of SuppressHole() )
1986 //================================================================================
1987 bool GEOM_Gen_i::BuildShapeHoleTraversing( const TopoDS_Shape& aShape,
1988                                            const TopoDS_Face& aFace,
1989                                            const TopoDS_Wire& aWire,
1990                                            const TopTools_MapOfShape& MFSuppress,
1991                                            const TopoDS_Face& endFace,
1992                                            const TopoDS_Wire& endWire,
1993                                            TopoDS_Shape& resultTds )
1994   throw (SALOME::SALOME_Exception)
1995 {
1996   Unexpect aCatch(SALOME_SalomeException);
1997   BRep_Builder B;
1998   TopExp_Explorer exp ;
1999   TopoDS_Face newFace ;
2000
2001   resultTds.Nullify() ;
2002   TopoDS_Compound Comp ;
2003   B.MakeCompound (Comp);
2004   
2005   /* Necessary to use general method */
2006   TopTools_MapOfShape MSwire1  ;
2007   MSwire1.Add(aWire) ; 
2008   TopTools_MapOfShape MSwire2 ;
2009   MSwire2.Add(endWire) ;
2010
2011   try  {    
2012     
2013     /* Explore all faces of 'aShape' to rebuild a compound */
2014     for ( exp.Init(aShape, TopAbs_FACE) ; exp.More(); exp.Next() ) {
2015       TopoDS_Face F1 = TopoDS::Face( exp.Current() );      
2016       
2017       /* Rebuild face(s) not suppressed */
2018       if( !MFSuppress.Contains(F1) ) {
2019         
2020         /* Rebuild 'aFace' */
2021         if( F1.IsEqual( aFace ) && !F1.IsEqual( endFace ) ) {
2022           if( !RebuildFaceRemovingHoles(aFace, MSwire1, newFace) ) {
2023             return false ;
2024           }
2025           B.Add(Comp, newFace) ;
2026         }       
2027         
2028         /* Rebuild 'endFace' */
2029         if( !F1.IsEqual( aFace ) && F1.IsEqual( endFace ) ) {
2030           if( !RebuildFaceRemovingHoles(endFace, MSwire2, newFace) ) {
2031             return false ;
2032           }
2033           B.Add(Comp, newFace) ;
2034         }
2035         
2036         /* Hole in the same face : aFace = endFace */
2037         if( F1.IsEqual( aFace ) && F1.IsEqual( endFace ) ) {
2038           TopoDS_Face FF ;
2039           if( !RebuildFaceRemovingHoles(aFace, MSwire1, newFace) || !RebuildFaceRemovingHoles(newFace, MSwire2, FF) ) {
2040             return false ;
2041           }
2042           B.Add( Comp, FF ) ;
2043         }
2044         
2045         /* For any other face not suppressed */
2046         if( !F1.IsEqual(aFace) && !F1.IsEqual( endFace ) ) {      
2047           B.Add( Comp, F1 ) ;
2048         }
2049         
2050       }
2051     }
2052   }
2053   catch(Standard_Failure) {
2054     THROW_SALOME_CORBA_EXCEPTION("in BuildShapeHoleTraversing() : Exception catched", SALOME::BAD_PARAM);
2055   }  
2056   resultTds = Comp ;
2057   return true ;
2058 }
2059
2060 //=======================================================================
2061 //function : SortShapes
2062 //purpose  : 
2063 //=======================================================================
2064
2065 static void SortShapes(TopTools_ListOfShape& SL)
2066 {
2067   Standard_Integer MaxShapes = SL.Extent();
2068   TopTools_Array1OfShape  aShapes (1,MaxShapes);
2069   TColStd_Array1OfInteger OrderInd(1,MaxShapes);
2070   TColStd_Array1OfReal    MidXYZ  (1,MaxShapes); //X,Y,Z;
2071   TColStd_Array1OfReal    Length  (1,MaxShapes); //X,Y,Z;
2072   
2073   // Computing of CentreOfMass
2074   Standard_Integer Index;
2075   GProp_GProps GPr;
2076   gp_Pnt GPoint;
2077   TopTools_ListIteratorOfListOfShape it(SL);
2078   for (Index=1;  it.More();  Index++)
2079   {
2080     TopoDS_Shape S = it.Value();
2081     SL.Remove( it ); // == it.Next()
2082     aShapes(Index) = S;
2083     OrderInd.SetValue (Index, Index);
2084     if (S.ShapeType() == TopAbs_VERTEX)
2085     {
2086       GPoint = BRep_Tool::Pnt( TopoDS::Vertex( S ));
2087       Length.SetValue( Index, (Standard_Real) S.Orientation());
2088     }
2089     else
2090     {
2091       BRepGProp::LinearProperties (S, GPr);
2092       GPoint = GPr.CentreOfMass();
2093       Length.SetValue( Index, GPr.Mass() );
2094     }
2095     MidXYZ.SetValue(Index,
2096                     GPoint.X()*999 + GPoint.Y()*99 + GPoint.Z()*0.9);
2097   }
2098   // Sorting
2099   Standard_Integer aTemp;
2100   Standard_Boolean exchange, Sort = Standard_True;
2101   while (Sort)
2102   {
2103     Sort = Standard_False;
2104     for (Index=1; Index < MaxShapes; Index++)
2105     {
2106       if (MidXYZ(OrderInd(Index)) > MidXYZ(OrderInd(Index+1)))
2107         exchange = Standard_True;
2108       else if (MidXYZ(OrderInd(Index)) == MidXYZ(OrderInd(Index+1)) &&
2109                Length(OrderInd(Index)) >  Length(OrderInd(Index+1)) )
2110         exchange = Standard_True;
2111       else
2112         exchange = Standard_False;
2113       if (exchange)
2114       {
2115         aTemp = OrderInd(Index);
2116         OrderInd(Index) = OrderInd(Index+1);
2117         OrderInd(Index+1) = aTemp;
2118         Sort = Standard_True;
2119       }
2120     }
2121   }
2122   for (Index=1; Index <= MaxShapes; Index++)
2123     SL.Append( aShapes( OrderInd(Index) ));
2124 }
2125
2126 //================================================================================
2127 // function : SubShape()
2128 // purpose  : Method for GUI or TUI
2129 //================================================================================
2130
2131 GEOM::GEOM_Shape_ptr GEOM_Gen_i::SubShape(GEOM::GEOM_Shape_ptr shape,
2132                                           CORBA::Short ShapeType, 
2133                                           const GEOM::GEOM_Shape::ListOfSubShapeID& ListOfID)
2134      throw (SALOME::SALOME_Exception)
2135 {
2136   Unexpect aCatch(SALOME_SalomeException);
2137   return SubShapesOne(shape, (TopAbs_ShapeEnum) ShapeType, ListOfID);
2138 }
2139
2140 //================================================================================
2141 // function : SubShapeSorted()
2142 // purpose  : Method for GUI or TUI
2143 //================================================================================
2144
2145 GEOM::GEOM_Shape_ptr GEOM_Gen_i::SubShapeSorted(GEOM::GEOM_Shape_ptr shape,
2146                                                 CORBA::Short ShapeType, 
2147                                                 const GEOM::GEOM_Shape::ListOfSubShapeID& ListOfID)
2148      throw (SALOME::SALOME_Exception)
2149 {
2150   Unexpect aCatch(SALOME_SalomeException);
2151   return SubShapesOne(shape, (TopAbs_ShapeEnum) ShapeType, ListOfID, Standard_True);
2152 }
2153
2154 //================================================================================
2155 // function : SubShapesOne()
2156 // purpose  :
2157 //================================================================================
2158
2159 GEOM::GEOM_Shape_ptr GEOM_Gen_i::SubShapesOne( GEOM::GEOM_Shape_ptr shape,
2160                                               const TopAbs_ShapeEnum ShapeType, 
2161                                               const GEOM::GEOM_Shape::ListOfSubShapeID& ListOfID,
2162                                               const Standard_Boolean Sort)
2163   throw (SALOME::SALOME_Exception)
2164 {
2165   Unexpect aCatch(SALOME_SalomeException);
2166   GEOM::GEOM_Shape_var result;
2167   TopoDS_Shape mainShape;
2168   TopoDS_Shape mainTopo = GetTopoShape(shape);
2169
2170   bool main = false;
2171   while ( !main ) {
2172     if ( shape->IsMainShape() ) {
2173       mainShape = GetTopoShape(shape);
2174       main = true;
2175     } else
2176       shape = GetIORFromString( shape->MainName() );
2177   }
2178   
2179   if(ListOfID.length() < 1) {
2180     THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::SubShape() : bad list of shapes",
2181                                  SALOME::BAD_PARAM);
2182   }
2183   
2184   /* Create a sequence of all sub shapes */
2185   TopTools_ListOfShape listShape;
2186
2187   TopTools_MapOfShape mapShape;
2188   TopExp_Explorer exp ;
2189   for ( exp.Init( mainShape, TopAbs_ShapeEnum(ShapeType)) ; exp.More(); exp.Next() ) {
2190     if ( mapShape.Add( exp.Current() ) )
2191       listShape.Append ( exp.Current() );
2192   }
2193
2194   if (listShape.IsEmpty()) return shape;
2195
2196   if (Sort)
2197     SortShapes(listShape);
2198
2199   TopTools_SequenceOfShape SS;
2200   TopTools_ListIteratorOfListOfShape it (listShape);
2201   for (; it.More(); it.Next())
2202     SS.Append( it.Value() );
2203
2204   TopoDS_Shape SubShape;
2205   if (ListOfID.length() == 1)
2206     SubShape = SS.Value(ListOfID[0]);
2207   else
2208   {
2209     BRep_Builder B;
2210     TopoDS_Compound Comp;
2211     B.MakeCompound (Comp);
2212     unsigned int ind;
2213     for ( ind = 0; ind < ListOfID.length(); ind++ )
2214       B.Add( Comp, SS.Value(ListOfID[ind]) );
2215     SubShape = Comp;
2216   }
2217
2218   if ( !TNaming_Tool::HasLabel( myCurrentOCAFDoc->Main(), SubShape ) ) 
2219     result = CreateSubObject( SubShape, shape, ListOfID);
2220   else {
2221     int TransDef;
2222     TDF_Label Lab = TNaming_Tool::Label( myCurrentOCAFDoc->Main(), SubShape, TransDef );
2223     Handle(TDataStd_Name) Att;
2224     if ( Lab.FindAttribute( TDataStd_Name::GetID(), Att ) ) {
2225       TCollection_AsciiString nameIOR( Att->Get() );
2226       result = GEOM::GEOM_Shape::_narrow(_orb->string_to_object( nameIOR.ToCString() ));
2227       if ( strcmp( result->MainName(), _orb->object_to_string(shape) ) != 0 ) {
2228         result = CreateSubObject( SubShape, shape, ListOfID);
2229       }
2230     }
2231   }
2232
2233   return result;
2234 }
2235
2236
2237 //================================================================================
2238 // function : SubShapeAll()
2239 // purpose  : Explode a shape in all sub shapes with a type (Method for TUI or GUI)
2240 //================================================================================
2241
2242 GEOM::GEOM_Gen::ListOfGeomShapes* GEOM_Gen_i::SubShapeAll(GEOM::GEOM_Shape_ptr shape,
2243                                                           CORBA::Short ShapeType)
2244      throw (SALOME::SALOME_Exception)
2245 {
2246   Unexpect aCatch(SALOME_SalomeException);
2247   return SubShapesAll(shape, (TopAbs_ShapeEnum) ShapeType);
2248 }
2249
2250 //================================================================================
2251 // function : SubShapeAllSorted()
2252 // purpose  : Explode a shape in all sub shapes with a type (Method for TUI or GUI)
2253 //================================================================================
2254
2255 GEOM::GEOM_Gen::ListOfGeomShapes* GEOM_Gen_i::SubShapeAllSorted(GEOM::GEOM_Shape_ptr shape,
2256                                                                 CORBA::Short ShapeType)
2257      throw (SALOME::SALOME_Exception)
2258 {
2259   Unexpect aCatch(SALOME_SalomeException);
2260   return SubShapesAll(shape, (TopAbs_ShapeEnum) ShapeType, Standard_True);
2261 }
2262
2263 //================================================================================
2264 // function : SubShapeAllSorted()
2265 // purpose  :
2266 //================================================================================
2267
2268 GEOM::GEOM_Gen::ListOfGeomShapes* GEOM_Gen_i::SubShapesAll(GEOM::GEOM_Shape_ptr shape,
2269                                                            const TopAbs_ShapeEnum ShapeType,
2270                                                            const Standard_Boolean Sort)
2271   throw (SALOME::SALOME_Exception)
2272 {
2273   /* List of sub shapes returned */
2274   Unexpect aCatch(SALOME_SalomeException);
2275   GEOM::GEOM_Gen::ListOfGeomShapes_var listOfGeomShapes = new GEOM::GEOM_Gen::ListOfGeomShapes;
2276   listOfGeomShapes->length(0) ;
2277   
2278   TopoDS_Shape mainTopo = GetTopoShape(shape);
2279   TopoDS_Shape mainShape;
2280   bool main = false;
2281   while ( !main ) {
2282     if ( shape->IsMainShape() ) {
2283       mainShape = GetTopoShape(shape);
2284       main = true;
2285     } else
2286       shape = GetIORFromString( shape->MainName() );
2287   }
2288
2289   if( mainTopo.IsNull() ) {
2290     THROW_SALOME_CORBA_EXCEPTION("In GEOM_Gen_i::SubShapeAll() : null main shape",
2291                                  SALOME::BAD_PARAM);
2292   }
2293   
2294   /* List/index : field set for any sub shape */
2295   GEOM::GEOM_Shape::ListOfSubShapeID_var ListOfID = new GEOM::GEOM_Shape::ListOfSubShapeID;
2296   ListOfID->length(1) ;
2297
2298     // retrieve all subshapes
2299   TopTools_MapOfShape mapShape;
2300   TopTools_ListOfShape listShape;
2301     
2302   if (mainTopo.ShapeType()==TopAbs_COMPOUND  &&  ShapeType==TopAbs_SHAPE)
2303   {
2304     TopoDS_Iterator It(mainTopo,Standard_True,Standard_True );  
2305     for ( ; It.More(); It.Next() ) 
2306       if (mapShape.Add( It.Value() ))
2307         listShape.Append( It.Value() );
2308   }
2309   else
2310   {
2311     TopExp_Explorer exp ( mainTopo, ShapeType);
2312     for ( ; exp.More(); exp.Next() ) 
2313       if (mapShape.Add( exp.Current() ))
2314         listShape.Append( exp.Current() );
2315   }
2316
2317   if (Sort)
2318     SortShapes(listShape);
2319     
2320   /* Create all sub shapes */
2321   int index;
2322   GEOM::GEOM_Shape_var result;
2323     
2324   TopTools_ListIteratorOfListOfShape itSub (listShape);
2325   for (index = 1; itSub.More(); itSub.Next(), ++index)
2326   {
2327     const TopoDS_Shape& SubShape = itSub.Value();
2328     // check if SubShape is already in OCAFDS and ...
2329     if ( TNaming_Tool::HasLabel( myCurrentOCAFDoc->Main(), SubShape ) )
2330     {
2331       int TransDef;
2332       TDF_Label Lab = TNaming_Tool::Label( myCurrentOCAFDoc->Main(), SubShape, TransDef );
2333       Handle(TDataStd_Name) Att;
2334       if ( Lab.FindAttribute( TDataStd_Name::GetID(), Att ) )
2335       {
2336         TCollection_AsciiString nameIOR( Att->Get() );
2337         result = GEOM::GEOM_Shape::_narrow(_orb->string_to_object( nameIOR.ToCString() ));
2338         // ... it is subshape of <shape>
2339         if ( strcmp( result->MainName(), _orb->object_to_string(shape) ) == 0 ) 
2340         {
2341           listOfGeomShapes->length(index) ;
2342           listOfGeomShapes[index-1] = result ;
2343           continue;
2344         }
2345       }
2346     }
2347
2348 //      if (Sort)
2349 //        ListOfID[0] = index;
2350 //      else
2351     ListOfID[0] = GetIndexTopology( SubShape, mainShape ) ;
2352     result = CreateSubObject( SubShape, shape, ListOfID);
2353     /* Add each sub shape in the list returned */
2354     listOfGeomShapes->length(index) ;
2355     listOfGeomShapes[index-1] = result ;      
2356   }
2357
2358   return listOfGeomShapes._retn() ;
2359 }
2360
2361 //=================================================================================
2362 // function : MakeBoolean()
2363 // purpose  : Boolean operation according to the type 'operation'
2364 //=================================================================================
2365 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeBoolean(GEOM::GEOM_Shape_ptr shape1,
2366                                        GEOM::GEOM_Shape_ptr shape2,
2367                                        CORBA::Long operation) 
2368   throw (SALOME::SALOME_Exception)
2369 {
2370   Unexpect aCatch(SALOME_SalomeException);
2371   GEOM::GEOM_Shape_var result;
2372   TopoDS_Shape shape ;
2373   TopoDS_Shape aShape1  ;
2374   TopoDS_Shape aShape2  ;
2375
2376   try {
2377     aShape1 = GetTopoShape(shape1) ;
2378     aShape2 = GetTopoShape(shape2) ;
2379     
2380     if( aShape1.IsNull() || aShape2.IsNull() ) {
2381       THROW_SALOME_CORBA_EXCEPTION("Boolean aborted : argument shape is null", SALOME::BAD_PARAM);
2382     }
2383     
2384     switch (operation)
2385       {
2386       case 1 :   /* Common */
2387         shape = BRepAlgoAPI_Common(aShape1, aShape2).Shape();
2388         break ;
2389       case 2 :   /* Cut */
2390         shape = BRepAlgoAPI_Cut(aShape1, aShape2).Shape();
2391         break ;
2392       case 3 :   /* Fuse */
2393         shape = BRepAlgoAPI_Fuse(aShape1, aShape2).Shape();
2394         break ;
2395       case 4 :   /* Section */
2396         shape = BRepAlgoAPI_Section(aShape1, aShape2).Shape();
2397         break ;
2398       default :
2399         MESSAGE("Boolean operation not known : " << operation ) ;
2400         return result ;
2401       }
2402   }
2403   catch(Standard_Failure) {
2404     THROW_SALOME_CORBA_EXCEPTION("Exception catched in boolean operation", SALOME::BAD_PARAM);
2405   }
2406     
2407   /* We test the validity of resulting shape */
2408   if( !IsValid(shape) ) {
2409     THROW_SALOME_CORBA_EXCEPTION("Boolean aborted : non valid shape result", SALOME::BAD_PARAM);
2410   }
2411         
2412   result = CreateObject(shape) ;
2413       
2414   /* put shape and name into geom/OCAF doc */
2415   GEOMDS_Commands GC(myCurrentOCAFDoc->Main());
2416   /* add attributs 'shape' and' name_io'r in a new label */
2417   TDF_Label Lab = GC.Generated(aShape1, shape, result->Name() );
2418   TCollection_AsciiString entry;
2419   TDF_Tool::Entry(Lab, entry);
2420   result->ShapeId( entry.ToCString() ) ;
2421       
2422   /* Create a new label */
2423   TDF_Label NewLab = Lab.NewChild();
2424   TCollection_ExtendedString Value("Arguments");
2425   TDataStd_Name::Set(NewLab,Value);
2426   
2427   TDF_Label NewLab1 = NewLab.NewChild();
2428   TDF_Label RefLab;
2429   TDF_Tool::Label(myCurrentOCAFDoc->GetData(), shape1->ShapeId(), RefLab);
2430   TDF_Reference::Set(NewLab1, RefLab);
2431   
2432   TDF_Label NewLab2 = NewLab.NewChild();
2433   TDF_Tool::Label(myCurrentOCAFDoc->GetData(), shape2->ShapeId(), RefLab);
2434   TDF_Reference::Set(NewLab2, RefLab);
2435   return result ;
2436 }
2437
2438
2439 //=================================================================================
2440 // function : MakeFuse()
2441 // purpose  : Special purpose !
2442 //=================================================================================
2443 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeFuse(GEOM::GEOM_Shape_ptr shape1,
2444                                     GEOM::GEOM_Shape_ptr shape2)
2445   throw (SALOME::SALOME_Exception)
2446 {
2447   Unexpect aCatch(SALOME_SalomeException);
2448   GEOM::GEOM_Shape_var result;
2449   TopoDS_Shape aShape1 = GetTopoShape(shape1) ;
2450   TopoDS_Shape aShape2 = GetTopoShape(shape2) ;
2451   if( aShape1.IsNull() || aShape2.IsNull() ) {
2452     THROW_SALOME_CORBA_EXCEPTION("Fuse aborted : shape in argument is null", SALOME::BAD_PARAM);
2453   }
2454   TopoDS_Shape shape;
2455   try {
2456     shape  = BRepAlgoAPI_Fuse(aShape1, aShape2).Shape();
2457   }
2458   catch(Standard_Failure) {
2459     THROW_SALOME_CORBA_EXCEPTION("Exception catched in Fuse operation", SALOME::BAD_PARAM);
2460   }
2461
2462   /* We test the validity of resulting shape */
2463   if( !IsValid(shape) ) {
2464     THROW_SALOME_CORBA_EXCEPTION("Fuse aborted : non valid shape result", SALOME::BAD_PARAM);
2465   }
2466
2467   result = CreateObject(shape) ;
2468
2469   /* put shape and name into geom/OCAF doc */
2470   GEOMDS_Commands GC(myCurrentOCAFDoc->Main());
2471   /* add attributs 'shape' and' name_io'r in a new label */
2472   TDF_Label Lab = GC.Generated(aShape1, shape, result->Name() );
2473   TCollection_AsciiString entry;
2474   TDF_Tool::Entry(Lab, entry);
2475   result->ShapeId( entry.ToCString() ) ;
2476
2477   /* Create a new label */
2478   TDF_Label NewLab = Lab.NewChild();
2479   TCollection_ExtendedString Value("Arguments");
2480   TDataStd_Name::Set(NewLab,Value);
2481
2482   TDF_Label NewLab1 = NewLab.NewChild();
2483   TDF_Label RefLab;
2484   TDF_Tool::Label(myCurrentOCAFDoc->GetData(), shape1->ShapeId(), RefLab);
2485   TDF_Reference::Set(NewLab1, RefLab);
2486
2487   TDF_Label NewLab2 = NewLab.NewChild();
2488   TDF_Tool::Label(myCurrentOCAFDoc->GetData(), shape2->ShapeId(), RefLab);
2489   TDF_Reference::Set(NewLab2, RefLab);
2490   return result ;
2491 }
2492
2493
2494 //================================================================================
2495 // function : MakeAxisStruct()
2496 // purpose  : Create a structure GEOM::AxisStruct (see IDL file)
2497 //================================================================================
2498 GEOM::AxisStruct GEOM_Gen_i::MakeAxisStruct(CORBA::Double x,
2499                                       CORBA::Double y,
2500                                       CORBA::Double z,
2501                                       CORBA::Double vx,
2502                                       CORBA::Double vy,
2503                                       CORBA::Double vz) 
2504 {
2505   int a = 1; int b = 0; int c; c=a/b;
2506   GEOM::AxisStruct A ;
2507   A.x  = x ;   A.y  = y ;   A.z  = z ;
2508   A.vx = vx ;  A.vy = vy ;  A.vz = vz ;
2509   return A ;
2510 }
2511
2512
2513 //================================================================================
2514 // function : MakePointStruct()
2515 // purpose  : Create a structure GEOM::PointStruct (see IDL file)
2516 //================================================================================
2517 GEOM::PointStruct GEOM_Gen_i::MakePointStruct(CORBA::Double x,
2518                                         CORBA::Double y,
2519                                         CORBA::Double z)
2520 {
2521   beginService( "GEOM_Gen_i::MakePointStruct" );
2522   GEOM::PointStruct p ;
2523   p.x = x ;   p.y = y ;   p.z = z ;
2524   endService( "GEOM_Gen_i::MakePointStruct" );
2525   return p ;
2526 }
2527
2528 //================================================================================
2529 // function : MakeDirection()
2530 // purpose  : Create a structure GEOM::DirStruct (see IDL file)
2531 //================================================================================
2532 GEOM::DirStruct GEOM_Gen_i::MakeDirection(const GEOM::PointStruct& p)
2533
2534   GEOM::DirStruct d ;
2535     d.PS.x = p.x ;  d.PS.y = p.y ;  d.PS.z = p.z ;
2536     return d ;
2537   }
2538
2539 //=================================================================================
2540 // function : MakeBox()
2541 // purpose  : Create a box topology.
2542 //=================================================================================
2543 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeBox(CORBA::Double x1,
2544                                          CORBA::Double y1,
2545                                          CORBA::Double z1,
2546                                          CORBA::Double x2,
2547                                          CORBA::Double y2,
2548                                          CORBA::Double z2) 
2549      throw (SALOME::SALOME_Exception)
2550 {
2551   Unexpect aCatch(SALOME_SalomeException);
2552   gp_Pnt P1(x1,y1,z1);
2553   gp_Pnt P2(x2,y2,z2);
2554   GEOM::GEOM_Shape_var result ;
2555   TopoDS_Shape tds ;
2556   try {
2557     tds = BRepPrimAPI_MakeBox(P1,P2).Shape();
2558   }
2559   catch(Standard_Failure) {
2560     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeBox", SALOME::BAD_PARAM);
2561   }
2562
2563   if (tds.IsNull()) {
2564     THROW_SALOME_CORBA_EXCEPTION("Make Box aborted : null shape", SALOME::BAD_PARAM);
2565   } 
2566
2567   result = CreateObject(tds);
2568   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
2569   result->ShapeId(entry) ;
2570   return result;  
2571 }
2572
2573
2574 //================================================================================
2575 // function : MakeCylinder
2576 // purpose  : Create a cylinder topology
2577 //================================================================================
2578 GEOM::GEOM_Shape_ptr  GEOM_Gen_i::MakeCylinder(const GEOM::PointStruct& pstruct,
2579                                                const GEOM::DirStruct& dstruct,
2580                                                CORBA::Double radius,
2581                                                CORBA::Double height) 
2582   throw (SALOME::SALOME_Exception)
2583 {
2584   Unexpect aCatch(SALOME_SalomeException);
2585   GEOM::GEOM_Shape_var result;
2586   TopoDS_Shape tds ;
2587   gp_Pnt p(pstruct.x, pstruct.y, pstruct.z) ;
2588   gp_Dir d(dstruct.PS.x, dstruct.PS.y, dstruct.PS.z) ;
2589   gp_Ax2 axis(p, d) ;
2590
2591   try {
2592     tds = BRepPrimAPI_MakeCylinder(axis, radius, height).Shape();
2593   }
2594   catch(Standard_Failure) {
2595     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeCylinder", SALOME::BAD_PARAM);
2596   }
2597   
2598   if (tds.IsNull()) {
2599     THROW_SALOME_CORBA_EXCEPTION("Make Cylinder aborted", SALOME::BAD_PARAM);
2600   } 
2601   result = CreateObject(tds);
2602   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
2603   result->ShapeId(entry);
2604   return result ;  
2605 }
2606
2607 //================================================================================
2608 // function : MakeSphere()
2609 // purpose  : Make a sphere topology
2610 //================================================================================
2611 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeSphere(CORBA::Double x1,
2612                                       CORBA::Double y1,
2613                                       CORBA::Double z1,
2614                                       CORBA::Double radius) 
2615   throw (SALOME::SALOME_Exception)
2616 {
2617   Unexpect aCatch(SALOME_SalomeException);
2618   GEOM::GEOM_Shape_var result ;
2619   TopoDS_Shape tds ;
2620   try {
2621     tds = BRepPrimAPI_MakeSphere(gp_Pnt(x1,y1,z1), radius).Shape();
2622   }
2623   catch(Standard_Failure) {
2624     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeSphere", SALOME::BAD_PARAM);
2625   }
2626   
2627   if (tds.IsNull()) {
2628     THROW_SALOME_CORBA_EXCEPTION("Make Sphere aborted", SALOME::BAD_PARAM);
2629   } 
2630   result = CreateObject(tds) ;  
2631   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
2632   result->ShapeId(entry);
2633   return result;  
2634 }
2635
2636 //================================================================================
2637 // function : MakeTorus()
2638 // purpose  : Create a torus topology
2639 //================================================================================
2640 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeTorus( const GEOM::PointStruct& pstruct,
2641                                       const GEOM::DirStruct& dstruct,
2642                                       CORBA::Double major_radius,
2643                                       CORBA::Double minor_radius )
2644   throw (SALOME::SALOME_Exception)
2645 {
2646   Unexpect aCatch(SALOME_SalomeException);
2647   GEOM::GEOM_Shape_var result;
2648   TopoDS_Shape tds ;
2649   gp_Pnt p(pstruct.x, pstruct.y, pstruct.z) ;
2650   gp_Dir d(dstruct.PS.x, dstruct.PS.y, dstruct.PS.z) ;
2651   gp_Ax2 axis(p, d) ;
2652
2653   try {
2654   tds = BRepPrimAPI_MakeTorus(axis, major_radius, minor_radius).Shape();
2655   }
2656   catch(Standard_Failure) {
2657     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeTorus", SALOME::BAD_PARAM);
2658   }
2659
2660   if (tds.IsNull()) {
2661     THROW_SALOME_CORBA_EXCEPTION("Make torus aborted", SALOME::BAD_PARAM);
2662   }
2663   result = CreateObject(tds);
2664   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
2665   result->ShapeId(entry);
2666   return result ;
2667 }
2668
2669
2670 //================================================================================
2671 // function : MakeCone()
2672 // purpose  : Create a cone topology
2673 //================================================================================
2674 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeCone(const GEOM::PointStruct& pstruct,
2675                                     const GEOM::DirStruct& dstruct,
2676                                     CORBA::Double radius1,
2677                                     CORBA::Double radius2,
2678                                     CORBA::Double height)
2679   throw (SALOME::SALOME_Exception)
2680 {
2681   Unexpect aCatch(SALOME_SalomeException);
2682   GEOM::GEOM_Shape_var result;
2683   TopoDS_Shape tds ;
2684   gp_Pnt p(pstruct.x, pstruct.y, pstruct.z) ;
2685   gp_Dir d(dstruct.PS.x, dstruct.PS.y, dstruct.PS.z) ;
2686   gp_Ax2 axis(p, d) ;
2687   
2688   try {
2689     /* Cone doesn't work if same radius */
2690     if( fabs(radius1-radius2) <= Precision::Confusion() ) {
2691       tds = BRepPrimAPI_MakeCylinder(axis, (radius1+radius2)/2.0, height).Shape();
2692     }
2693     else {
2694       tds = BRepPrimAPI_MakeCone(axis, radius1, radius2, height).Shape();
2695     }
2696   }
2697   catch(Standard_Failure) {
2698     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeCone", SALOME::BAD_PARAM);
2699   }
2700
2701   if (tds.IsNull()) {
2702     THROW_SALOME_CORBA_EXCEPTION("Make Cone aborted", SALOME::BAD_PARAM);
2703   }
2704   result = CreateObject(tds);
2705   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
2706   result->ShapeId(entry);
2707   return result ;
2708 }
2709
2710
2711
2712 //==================================================================================
2713 // function : ImportIGES()
2714 // purpose  : Import shape from an IGES (IGS) file
2715 //          : LPN modified 7 mai 2002
2716 //==================================================================================
2717 GEOM::GEOM_Shape_ptr GEOM_Gen_i::ImportIGES(const char* filename)
2718   throw (SALOME::SALOME_Exception)
2719 {
2720   Unexpect aCatch(SALOME_SalomeException);
2721   GEOM::GEOM_Shape_var result ;
2722   //VRV: OCC 4.0 migration
2723   IGESControl_Reader aReader;  
2724   //VRV: OCC 4.0 migration
2725   try {
2726     IFSelect_ReturnStatus stat = aReader.ReadFile((char*)filename);
2727     if ( stat != IFSelect_RetDone ) {
2728       THROW_SALOME_CORBA_EXCEPTION("Error in reading import file", SALOME::BAD_PARAM);    }
2729     
2730     MESSAGE("ImportIGES : all Geometry Transfer" << endl ) ;
2731     //OCC 5.1.2 porting
2732 //     aReader.Clear();
2733 //     aReader.TransferRoots(false);
2734     aReader.ClearShapes();
2735     aReader.TransferRoots();
2736
2737     MESSAGE("ImportIGES : count of shapes produced = " << aReader.NbShapes() << endl );    
2738     TopoDS_Shape shape = aReader.OneShape();
2739
2740     if ( !shape.IsNull() ) {      
2741       /* Final CORBA object creation */
2742       result = CreateObject(shape) ;
2743       const char *entry = InsertInLabel( shape, result->Name(), myCurrentOCAFDoc ) ;
2744       result->ShapeId(entry);
2745       return result ;
2746     }
2747   }
2748   catch(Standard_Failure) {
2749     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ImportIGES()", SALOME::BAD_PARAM);
2750   } 
2751   
2752   THROW_SALOME_CORBA_EXCEPTION("Import IGES aborted : internal error", SALOME::BAD_PARAM);
2753 }
2754
2755
2756
2757 //==================================================================================
2758 // function : ImportSTEP()
2759 // purpose  : Import shape from an STEP (stp) file
2760 //          : 'result' is a compound of shapes if file contains more entities.
2761 //==================================================================================
2762 GEOM::GEOM_Shape_ptr GEOM_Gen_i::ImportSTEP(const char* filename)
2763   throw (SALOME::SALOME_Exception)
2764 {
2765   Unexpect aCatch(SALOME_SalomeException);
2766   GEOM::GEOM_Shape_var result ;
2767   //VRV: OCC 4.0 migration
2768   STEPControl_Reader aReader;
2769   //VRV: OCC 4.0 migration
2770
2771   TopoDS_Compound compound;
2772   BRep_Builder B;
2773   B.MakeCompound( compound );
2774   
2775   try {
2776     IFSelect_ReturnStatus status = aReader.ReadFile((char*)filename);
2777     
2778     if (status == IFSelect_RetDone) {
2779       Standard_Boolean failsonly = Standard_False ;
2780       aReader.PrintCheckLoad (failsonly, IFSelect_ItemsByEntity);
2781       /* Root transfers */
2782       Standard_Integer nbr = aReader.NbRootsForTransfer();
2783       aReader.PrintCheckTransfer (failsonly, IFSelect_ItemsByEntity);
2784       
2785       for ( Standard_Integer n=1; n <= nbr; n++) {
2786         
2787         Standard_Boolean ok = aReader.TransferRoot(n);
2788         /* Collecting resulting entities */
2789         Standard_Integer nbs = aReader.NbShapes();
2790         if (nbs == 0)
2791           THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ImportStep", SALOME::BAD_PARAM) ;      
2792         
2793         for ( Standard_Integer i=1; i<=nbs; i++ ) {       
2794           TopoDS_Shape aShape = aReader.Shape(i);
2795           if ( aShape.IsNull() )
2796             THROW_SALOME_CORBA_EXCEPTION("Null shape in GEOM_Gen_i::ImportStep", SALOME::BAD_PARAM) ;   
2797           
2798           /* For a single entity */
2799           if(nbr == 1 && nbs == 1) {      
2800             result = CreateObject(aShape) ;
2801             const char *entry = InsertInLabel(aShape, result->Name(), myCurrentOCAFDoc) ;
2802             result->ShapeId(entry);
2803             return result ;
2804           }
2805           else {
2806             B.Add( compound, aShape ) ;
2807           }
2808         }
2809       }
2810
2811      TopoDS_Shape tds = compound ; 
2812      result = CreateObject(tds) ;
2813      if( CORBA::is_nil(result) )
2814        THROW_SALOME_CORBA_EXCEPTION("Translation aborted : null result", SALOME::BAD_PARAM);
2815      const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
2816      result->ShapeId(entry);
2817      return result ;
2818     }
2819     
2820   }
2821   catch(Standard_Failure) {
2822     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ImportStep", SALOME::BAD_PARAM);
2823   }  
2824   return result ;
2825 }
2826
2827
2828 //==================================================================================
2829 // function : Partition()
2830 // purpose  :
2831 //==================================================================================
2832
2833 GEOM::GEOM_Shape_ptr
2834   GEOM_Gen_i::Partition(const GEOM::GEOM_Gen::ListOfIOR& ListShapes, 
2835                         const GEOM::GEOM_Gen::ListOfIOR& ListTools,
2836                         const GEOM::GEOM_Gen::ListOfIOR& ListKeepInside,
2837                         const GEOM::GEOM_Gen::ListOfIOR& ListRemoveInside,
2838                         const CORBA::Short               Limit)
2839 throw (SALOME::SALOME_Exception)
2840 {
2841   Unexpect aCatch(SALOME_SalomeException);
2842   GEOM::GEOM_Shape_var aResult;  
2843   TopoDS_Shape tds ;
2844   //MESSAGE ("In Partition");
2845   try {
2846
2847     unsigned int ind, nbshapes = 0;
2848     nbshapes += ListShapes.length() + ListTools.length();
2849     nbshapes += ListKeepInside.length() + ListRemoveInside.length();
2850     
2851     Partition_Spliter PS;
2852     TopTools_MapOfShape ShapesMap(nbshapes), ToolsMap(nbshapes);
2853     
2854     // add object shapes that are in ListShapes;
2855     for ( ind = 0; ind < ListShapes.length(); ind++) {
2856       
2857       GEOM::GEOM_Shape_var aShape = GetIORFromString( ListShapes[ind] );
2858       TopoDS_Shape Shape = GetTopoShape(aShape);
2859       if(Shape.IsNull() ) {
2860         //MESSAGE ( "In Partition a shape is null" );
2861         THROW_SALOME_CORBA_EXCEPTION("In Partition a shape is null", SALOME::BAD_PARAM);
2862       }
2863       if ( ShapesMap.Add( Shape ))
2864         PS.AddShape(Shape);
2865     }
2866     
2867     // add tool shapes that are in ListTools and not in ListShapes;
2868     for (ind = 0; ind < ListTools.length(); ind++) {
2869       
2870       GEOM::GEOM_Shape_var aShape = GetIORFromString( ListTools[ind] );
2871       TopoDS_Shape Shape = GetTopoShape(aShape);
2872       if(Shape.IsNull() ) {
2873         //MESSAGE ( "In Partition a tool shape is null" );
2874         THROW_SALOME_CORBA_EXCEPTION("In Partition a shape is null", SALOME::BAD_PARAM);
2875       }
2876       if ( !ShapesMap.Contains( Shape ) && ToolsMap.Add( Shape ))
2877         PS.AddTool(Shape);
2878     }
2879     
2880     // add shapes that are in ListKeepInside, as object shapes;
2881     for (ind = 0; ind < ListKeepInside.length(); ind++) {
2882       
2883       GEOM::GEOM_Shape_var aShape = GetIORFromString( ListKeepInside[ind] );
2884       TopoDS_Shape Shape = GetTopoShape(aShape);
2885       if(Shape.IsNull() ) {
2886         //MESSAGE ( "In Partition a Keep Inside shape is null" );
2887         THROW_SALOME_CORBA_EXCEPTION("In Partition a shape is null", SALOME::BAD_PARAM);
2888       }
2889       if (!ToolsMap.Contains( Shape ) &&
2890           ShapesMap.Add( Shape ))
2891         PS.AddShape(Shape);
2892     }
2893     
2894     // add shapes that are in ListRemoveInside, as object shapes;
2895     for (ind = 0; ind < ListRemoveInside.length(); ind++) {
2896       
2897       GEOM::GEOM_Shape_var aShape = GetIORFromString( ListRemoveInside[ind] );
2898       TopoDS_Shape Shape = GetTopoShape(aShape);
2899       if(Shape.IsNull() ) {
2900         //MESSAGE ( "In Partition a Remove Inside shape is null" );
2901         THROW_SALOME_CORBA_EXCEPTION("In Partition a shape is null", SALOME::BAD_PARAM);
2902       }
2903       if (!ToolsMap.Contains( Shape ) &&
2904           ShapesMap.Add( Shape ) )
2905         PS.AddShape(Shape);
2906     }
2907     
2908     PS.Compute ((TopAbs_ShapeEnum) Limit);
2909
2910     // suppress result outside of shapes in KInsideMap
2911     for (ind = 0; ind < ListKeepInside.length(); ind++) {
2912       GEOM::GEOM_Shape_var aShape = GetIORFromString( ListKeepInside[ind] );
2913       TopoDS_Shape Shape = GetTopoShape(aShape);
2914       PS.KeepShapesInside( Shape );
2915     }
2916     
2917     // suppress result inside of shapes in RInsideMap
2918     for (ind = 0; ind < ListRemoveInside.length(); ind++) {
2919       
2920       GEOM::GEOM_Shape_var aShape = GetIORFromString( ListRemoveInside[ind] );
2921       TopoDS_Shape Shape = GetTopoShape(aShape);
2922       PS.RemoveShapesInside( Shape );
2923     }
2924     
2925     tds = PS.Shape();
2926     
2927     if( !IsValid(tds) ) {
2928       //MESSAGE ( "In Partition: non valid shape result" );
2929       THROW_SALOME_CORBA_EXCEPTION("Partition aborted : non valid shape result", SALOME::BAD_PARAM);
2930     }
2931   }
2932   catch (Standard_Failure) {
2933     //MESSAGE ( "In Partition: Exception catched in GEOM_Gen_i::Partition()" );
2934     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::Partition", SALOME::BAD_PARAM);
2935   }
2936   
2937   aResult = CreateObject(tds) ;
2938
2939   /* add attributs S and mystr in a new label */
2940   GEOMDS_Commands GC(myCurrentOCAFDoc->Main());
2941   TDF_Label Lab = GC.AddShape(tds, aResult->Name() );
2942   TCollection_AsciiString entry;
2943   TDF_Tool::Entry(Lab,entry);
2944   aResult->ShapeId( entry.ToCString() ) ;
2945   
2946   // add arguments
2947   
2948   /* Create a new label */
2949   TDF_Label NewLab = Lab.NewChild();
2950   TCollection_ExtendedString Value("Arguments");
2951   TDataStd_Name::Set(NewLab,Value);
2952
2953   // object shapes
2954   for (unsigned int ind = 0; ind < ListShapes.length(); ind++) {
2955     TDF_Label NewLab1 = NewLab.NewChild();
2956     
2957     GEOM::GEOM_Shape_var aShape = GetIORFromString( ListShapes[ind] );
2958     Standard_CString anEntry = aShape->ShapeId();
2959     TDF_Label RefLab;
2960     TDF_Tool::Label(myCurrentOCAFDoc->GetData(), anEntry, RefLab);
2961     TDF_Reference::Set(NewLab1,RefLab);
2962   }
2963   // tool shapes
2964   for (unsigned int ind = 0; ind < ListTools.length(); ind++) {
2965     TDF_Label NewLab1 = NewLab.NewChild();
2966     
2967     GEOM::GEOM_Shape_var aShape = GetIORFromString( ListTools[ind] );
2968     Standard_CString anEntry = aShape->ShapeId();
2969     TDF_Label RefLab;
2970     TDF_Tool::Label(myCurrentOCAFDoc->GetData(), anEntry, RefLab);
2971     TDF_Reference::Set(NewLab1,RefLab);
2972   }
2973   // limit shapes 1
2974   for (unsigned int ind = 0; ind < ListKeepInside.length(); ind++) {
2975     TDF_Label NewLab1 = NewLab.NewChild();
2976     
2977     GEOM::GEOM_Shape_var aShape = GetIORFromString( ListKeepInside[ind] );
2978     Standard_CString anEntry = aShape->ShapeId();
2979     TDF_Label RefLab;
2980     TDF_Tool::Label(myCurrentOCAFDoc->GetData(), anEntry, RefLab);
2981     TDF_Reference::Set(NewLab1,RefLab);
2982   }
2983   // limit shapes 2
2984   for (unsigned int ind = 0; ind < ListRemoveInside.length(); ind++) {
2985     TDF_Label NewLab1 = NewLab.NewChild();
2986     
2987     GEOM::GEOM_Shape_var aShape = GetIORFromString( ListRemoveInside[ind] );
2988     Standard_CString anEntry = aShape->ShapeId();
2989     TDF_Label RefLab;
2990     TDF_Tool::Label(myCurrentOCAFDoc->GetData(), anEntry, RefLab);
2991     TDF_Reference::Set(NewLab1,RefLab);
2992   }
2993   
2994   return aResult;    
2995 }
2996
2997
2998
2999 //==================================================================================
3000 // function : MakeFilling()
3001 // purpose  : Create a surface from section curves filling
3002 //==================================================================================
3003 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeFilling(GEOM::GEOM_Shape_ptr myShape,
3004                                        CORBA::Short mindeg,
3005                                        CORBA::Short maxdeg,
3006                                        CORBA::Double tol3d,
3007                                        CORBA::Double tol2d,
3008                                        CORBA::Short nbiter)
3009   throw (SALOME::SALOME_Exception)
3010 {
3011   Unexpect aCatch(SALOME_SalomeException);
3012   GEOM::GEOM_Shape_var result ;
3013   TopoDS_Face tds ;
3014   TopoDS_Shape aShape = GetTopoShape(myShape) ;
3015   if( aShape.IsNull() || aShape.ShapeType() != TopAbs_COMPOUND ) {
3016     THROW_SALOME_CORBA_EXCEPTION("MakeFilling aborted : null shape or not a compound", SALOME::BAD_PARAM);
3017   } 
3018
3019   try {
3020     /* we verify the contents of the shape */
3021     TopExp_Explorer Ex ;
3022     TopoDS_Shape Scurrent ;     
3023     Standard_Real First, Last ;
3024     Handle(Geom_Curve) C ;
3025     GeomFill_SectionGenerator Section ;
3026     
3027     Standard_Integer i = 0 ;
3028     for(Ex.Init(aShape, TopAbs_EDGE); Ex.More(); Ex.Next()) {
3029       Scurrent = Ex.Current() ;
3030       if( Scurrent.IsNull() || Scurrent.ShapeType() != TopAbs_EDGE)  {
3031         THROW_SALOME_CORBA_EXCEPTION("Initial shape doesn't contain only edges !", SALOME::BAD_PARAM);
3032       }
3033       C = BRep_Tool::Curve(TopoDS::Edge(Scurrent), First, Last);
3034       C = new Geom_TrimmedCurve(C, First, Last);
3035       Section.AddCurve(C) ;
3036       i++ ;
3037     }
3038     
3039     /* a 'tolerance' is used to compare 2 knots : see GeomFill_Generator.cdl */
3040     /* We set 'tolerance' = tol3d                                            */
3041     // Section.Perform( tol3d ) ; NRI */
3042     Section.Perform( Precision::Confusion() ) ;
3043     Handle(GeomFill_Line) Line = new GeomFill_Line(i) ;
3044     
3045     GeomFill_AppSurf App(mindeg, maxdeg, tol3d, tol2d, nbiter) ; /* user parameters */
3046     App.Perform(Line, Section) ;
3047     
3048     if (!App.IsDone()) {
3049       THROW_SALOME_CORBA_EXCEPTION("Filling aborted : non valid shape result", SALOME::BAD_PARAM);
3050     }
3051     Standard_Integer UDegree, VDegree, NbUPoles, NbVPoles, NbUKnots, NbVKnots;
3052     App.SurfShape(UDegree, VDegree, NbUPoles, NbVPoles, NbUKnots, NbVKnots);    
3053     Handle(Geom_BSplineSurface) GBS = new Geom_BSplineSurface(App.SurfPoles(),
3054                                                               App.SurfWeights(),
3055                                                               App.SurfUKnots(),
3056                                                               App.SurfVKnots(),
3057                                                               App.SurfUMults(),
3058                                                               App.SurfVMults(),
3059                                                               App.UDegree(),
3060                                                               App.VDegree());
3061     
3062     if( GBS.IsNull() )  {
3063       THROW_SALOME_CORBA_EXCEPTION("Make Filling aborted", SALOME::BAD_PARAM);
3064     }
3065     tds  = BRepBuilderAPI_MakeFace(GBS) ;    
3066   }
3067   catch(Standard_Failure) {
3068     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeFilling", SALOME::BAD_PARAM);
3069   } 
3070   
3071   /* We test the validity of resulting shape */
3072   if( !IsValid(tds) ) {
3073     THROW_SALOME_CORBA_EXCEPTION("Filling aborted : non valid shape result", SALOME::BAD_PARAM);
3074   } 
3075   else {
3076     result = CreateObject(tds) ;
3077     InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
3078   }
3079  
3080   return result ;
3081 }
3082
3083
3084 //=================================================================================
3085 // function : MakeGlueFaces()
3086 // purpose  :
3087 //=================================================================================
3088
3089 TopoDS_Face GEOM_Gen_i::FindSameFace(const TopoDS_Shape& aShape, 
3090                                      const TopoDS_Face& F,
3091                                      double tol3d)
3092 {
3093   TopoDS_Face aFace;
3094   bool isSame = false;
3095   for (TopExp_Explorer exf(aShape,TopAbs_FACE); exf.More(); exf.Next())
3096     {
3097       //MESSAGE("--- test a face");
3098       int nbFound = 0;
3099       aFace = TopoDS::Face(exf.Current());
3100       TopTools_ListOfShape liste1;
3101       TopTools_ListOfShape liste2;
3102       for (TopExp_Explorer exp(aFace,TopAbs_VERTEX); exp.More(); exp.Next())
3103         {
3104           const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
3105           liste1.Append(V);
3106         }
3107       for (TopExp_Explorer exp(F,TopAbs_VERTEX); exp.More(); exp.Next())
3108         {
3109           const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
3110           liste2.Append(V);
3111         }
3112       isSame = false;
3113       if (liste1.Extent() == liste2.Extent())
3114         {
3115           TopTools_ListIteratorOfListOfShape it1(liste1);
3116           isSame = true;
3117           for (; it1.More(); it1.Next())
3118             {
3119               bool foundSamePoint = false;
3120               gp_Pnt P1 = BRep_Tool::Pnt(TopoDS::Vertex(it1.Value()));
3121               TopTools_ListIteratorOfListOfShape it2(liste2);
3122               for (it2; it2.More(); it2.Next())
3123                 {
3124                   gp_Pnt P2 = BRep_Tool::Pnt(TopoDS::Vertex(it2.Value()));
3125                   double d = P1.Distance(P2);
3126                   if (d < tol3d)
3127                     {
3128                       nbFound++;
3129                       //MESSAGE("    found Same Point : "<<nbFound<<" - "<<P1.X()<<" "<<P1.Y()<<" "<<P1.Z());
3130                       foundSamePoint = true;
3131                       break;
3132                     }
3133                 }
3134               isSame = isSame && foundSamePoint;
3135               if (! isSame) break; // a vertex does not correspond : not same face
3136             }
3137         }
3138       if (isSame)
3139         {
3140           //MESSAGE("    --- Found Same Face");
3141           break; // a face corresponding to F is found
3142         }
3143     }
3144   if (! isSame) aFace.Nullify(); // return null face
3145   return aFace;
3146 }
3147
3148 TopoDS_Edge GEOM_Gen_i::FindSameEdge(const TopoDS_Face& nf, 
3149                                      TopoDS_Edge& Eold,
3150                                      double tol3d)
3151 {
3152   TopoDS_Face newFace = TopoDS::Face(nf.Oriented(TopAbs_REVERSED));
3153   TopoDS_Vertex VFirst, VLast;
3154   TopExp::Vertices(Eold, VFirst, VLast);
3155   gp_Pnt Pf = BRep_Tool::Pnt(VFirst);
3156   gp_Pnt Pl = BRep_Tool::Pnt(VLast);
3157   TopoDS_Edge Enew;
3158   for (TopExp_Explorer ee(newFace,TopAbs_EDGE); ee.More(); ee.Next())
3159     {
3160       const TopoDS_Edge& E = TopoDS::Edge(ee.Current());
3161       TopoDS_Vertex VFn, VLn;
3162       TopExp::Vertices(E, VFn, VLn);
3163       gp_Pnt Pfn = BRep_Tool::Pnt(VFn);
3164       gp_Pnt Pln = BRep_Tool::Pnt(VLn);
3165       double dff = Pf.Distance(Pfn);
3166       double dfl = Pf.Distance(Pln);
3167       double dlf = Pl.Distance(Pfn);
3168       double dll = Pl.Distance(Pln);
3169       if ((dff < tol3d) && (dll <tol3d))
3170         {
3171           //MESSAGE("--- edge forward " <<Pf.X()<<" "<<Pf.Y()<<" "<<Pf.Z()<<" "<<Pl.X()<<" "<<Pl.Y()<<" "<<Pl.Z());
3172           Enew = TopoDS::Edge(E.Oriented(TopAbs_FORWARD));
3173           Eold = TopoDS::Edge(Eold.Oriented(TopAbs_FORWARD));
3174           break;
3175         } 
3176       if ((dfl < tol3d) && (dlf <tol3d))
3177         {
3178           //MESSAGE("--- edge reversed " <<Pf.X()<<" "<<Pf.Y()<<" "<<Pf.Z()<<" "<<Pl.X()<<" "<<Pl.Y()<<" "<<Pl.Z());
3179           Enew = TopoDS::Edge(E.Oriented(TopAbs_REVERSED));
3180           Eold = TopoDS::Edge(Eold.Oriented(TopAbs_FORWARD));
3181           break;
3182         } 
3183     }
3184   return Enew;
3185 }
3186
3187 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeGlueFaces(GEOM::GEOM_Shape_ptr myShape,
3188                                                double tol3d)
3189   throw (SALOME::SALOME_Exception)
3190 {
3191
3192   // prendre un premier shell dans la liste des shells
3193   // initialiser un compshell avec ce shell
3194   // tant qu'il reste des shells dans la liste
3195   //   chercher un shell qui a des faces en  commun avec le compshell
3196   //   creer un BRepTools_Quilt
3197   //   recenser les faces communes issues du compshell, les ajouter au quilt 
3198   //   recenser les faces restantes du shell a inclure, les ajouter au quilt
3199   //   recenser les edges en double, a remplacer
3200   //   pour chaque paire d'edge
3201   //     tester l'orientation relative des aretes
3202   //     bind dans le quilt de Eold.Forward et Enew.Forward (ou reverse)
3203   //   recuperer le nouveau shell
3204   // l'incorporer dans le compshell
3205   // appliquer BRepTools_SameParameter au compshell
3206   // (rendre parametres 2D des edges identiques aux parametres 3D)
3207
3208   Unexpect aCatch(SALOME_SalomeException);
3209   GEOM::GEOM_Shape_var result ;
3210   TopoDS_Shape tds ;
3211   TopoDS_Shape aShape = GetTopoShape(myShape) ;
3212   TopoDS_Compound C;
3213   BRep_Builder bu;
3214   bu.MakeCompound(C); // empty compound;
3215   TopTools_ListOfShape shellList;
3216   for (TopExp_Explorer exp(aShape,TopAbs_SHELL); exp.More(); exp.Next())
3217     {
3218       const TopoDS_Shell& S = TopoDS::Shell(exp.Current());
3219       shellList.Append(S);
3220     }
3221   TopTools_ListIteratorOfListOfShape its(shellList);
3222   if ( ! its.More())
3223     {
3224       THROW_SALOME_CORBA_EXCEPTION("glue aborted : no shell in shape", SALOME::BAD_PARAM);
3225     }
3226   TopoDS_Shell S = TopoDS::Shell(its.Value());
3227   bu.Add(C, S); // add first shell to compound
3228   shellList.Remove(its);
3229   its.Initialize(shellList);
3230   bool shellAdded = true;
3231   while ((shellList.Extent() > 0) && shellAdded)
3232     {
3233       //MESSAGE("more shells : "<< shellList.Extent());
3234       shellAdded = false;
3235       its.Initialize(shellList);
3236       for(; its.More(); its.Next())
3237         {
3238           //MESSAGE("one more shell to try");
3239           TopTools_ListOfShape newFaces; // common faces from new compound
3240           TopTools_ListOfShape oldFaces; // common faces from shell to add
3241           TopTools_ListOfShape addFaces; // not common faces from shell to add
3242           TopTools_ListOfShape newEdges; // common edges from new compound
3243           TopTools_ListOfShape oldEdges; // common edges from face to add
3244           TopoDS_Compound CFN;
3245           TopoDS_Compound CFO;
3246           bu.MakeCompound(CFN);       // empty compound for new faces
3247           bu.MakeCompound(CFO);       // empty compound for old faces
3248           S = TopoDS::Shell(its.Value());
3249           for (TopExp_Explorer exp(S,TopAbs_FACE); exp.More(); exp.Next())
3250             {
3251               //MESSAGE("--- try to find corresponding face in new compound");
3252               TopoDS_Face F = TopoDS::Face(exp.Current());
3253               TopoDS_Face newFace = FindSameFace(C,F,tol3d);
3254               if (! newFace.IsNull())
3255                 {
3256                   //MESSAGE("--- face found");
3257                   newFaces.Append(newFace); 
3258                   bu.Add(CFN, newFace); // common faces from new compound
3259                   oldFaces.Append(F);
3260                   for (TopExp_Explorer ee(F,TopAbs_EDGE);ee.More();ee.Next())
3261                     {
3262                       //MESSAGE("--- find edge pair");
3263                       TopoDS_Edge Eold = TopoDS::Edge(ee.Current());
3264                       const TopoDS_Edge& Enew = FindSameEdge(newFace, Eold, tol3d);
3265                       oldEdges.Append(Eold);
3266                       newEdges.Append(Enew);
3267                     }
3268                 }
3269               else
3270                 {
3271                   //MESSAGE("---");
3272                   addFaces.Append(F);
3273                   bu.Add(CFO, F); // not common faces from shell to add
3274                 }
3275             }
3276           if ( !newFaces.IsEmpty())
3277             {
3278               //MESSAGE("--- some faces found ---");
3279               shellAdded = true;
3280               BRepTools_Quilt glue;
3281               glue.Add(CFN);
3282               TopTools_ListIteratorOfListOfShape ito(oldEdges);
3283               TopTools_ListIteratorOfListOfShape itn(newEdges);
3284               for (; ito.More(); ito.Next())
3285                 {                 
3286                   //MESSAGE("--- bind");
3287                   glue.Bind(TopoDS::Edge(ito.Value()), TopoDS::Edge(itn.Value()));
3288                   itn.Next();
3289                 }
3290               glue.Add(CFO);
3291               TopoDS_Compound newc = TopoDS::Compound(glue.Shells());
3292               for (TopExp_Explorer exs(newc,TopAbs_SHELL); exs.More(); exs.Next())
3293                 {
3294                   TopoDS_Shell NS = TopoDS::Shell(exs.Current());
3295                   bu.Add(C, NS);
3296                 }
3297               shellList.Remove(its);
3298               //MESSAGE("--- remove shell from list");
3299               break;
3300             }
3301         }
3302     }
3303   //MESSAGE("---" << shellList.Extent() << " " << shellAdded);
3304
3305   TopExp_Explorer  exp(C,TopAbs_SHELL);
3306   Standard_Integer ish=0;
3307   TopoDS_Compound  Res;
3308   TopoDS_Solid     Sol;
3309   BRep_Builder     B;
3310   B.MakeCompound(Res);
3311   TopoDS_Shape theShape;
3312
3313   for (; exp.More(); exp.Next())
3314     {
3315       TopoDS_Shape Sh = exp.Current();
3316       B.MakeSolid(Sol);
3317       B.Add(Sol,Sh);
3318       BRepClass3d_SolidClassifier SC(Sol);
3319       SC.PerformInfinitePoint(1.E-6); // cf. BRepFill_Confusion() - BRepFill_Evolved.cxx
3320       if (SC.State() == TopAbs_IN)
3321         {
3322           B.MakeSolid(Sol);
3323           B.Add(Sol,Sh.Reversed());
3324         }
3325       B.Add(Res,Sol);
3326       ish++;
3327     }
3328   if (ish == 1) { theShape = Sol;}
3329   else          { theShape = Res;}
3330
3331   BRepLib::SameParameter(theShape, 1.E-5, Standard_True);
3332   tds = theShape;
3333   result = CreateObject(tds);    
3334   InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
3335   //MESSAGE("---");
3336   return result;
3337 }
3338
3339 //=================================================================================
3340 // function : MakeSewing()
3341 // purpose  :
3342 //=================================================================================
3343 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeSewing( const GEOM::GEOM_Gen::ListOfIOR& ListShapes,
3344                                        CORBA::Double precision )
3345   throw (SALOME::SALOME_Exception)
3346 {
3347   Unexpect aCatch(SALOME_SalomeException);
3348   GEOM::GEOM_Shape_var result ;
3349   TopoDS_Shape tds ;
3350   BRepOffsetAPI_Sewing aMethod ;
3351
3352   try {
3353     /* default OCC is 1.0e-06 */
3354     aMethod.Init(precision, Standard_False);  
3355     for ( unsigned int i = 0; i < ListShapes.length(); i++) {
3356       GEOM::GEOM_Shape_var aShape = GetIORFromString( ListShapes[i] ); 
3357       TopoDS_Shape Shape = GetTopoShape(aShape) ;
3358       if( Shape.IsNull() ) {
3359         THROW_SALOME_CORBA_EXCEPTION("MakeSewing aborted : null shape during operation", SALOME::BAD_PARAM);
3360       } 
3361       aMethod.Add(Shape) ;  
3362     }  
3363     
3364     aMethod.Perform() ;
3365     tds = aMethod.SewedShape() ;
3366     if( !IsValid(tds) ) {
3367       THROW_SALOME_CORBA_EXCEPTION("Make Sewing aborted : non valid shape", SALOME::BAD_PARAM);
3368     }
3369     if( tds.IsNull() ) {
3370       THROW_SALOME_CORBA_EXCEPTION("Make Sewing aborted : null shape", SALOME::BAD_PARAM);
3371     }
3372   }
3373   catch (Standard_Failure) {
3374     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeSewing", SALOME::BAD_PARAM);
3375   }
3376   
3377   result = CreateObject(tds);
3378   InsertInLabelMoreArguments(tds, result, ListShapes, myCurrentOCAFDoc) ;
3379   return result;
3380 }
3381
3382 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeSewingShape( GEOM::GEOM_Shape_ptr aShape,
3383                                             CORBA::Double precision )
3384   throw (SALOME::SALOME_Exception)
3385 {
3386   Unexpect aCatch(SALOME_SalomeException);
3387   GEOM::GEOM_Shape_var result ;
3388   TopoDS_Shape tds, S ;
3389   BRepOffsetAPI_Sewing aMethod ;
3390
3391   try {
3392     S = GetTopoShape(aShape) ;
3393     if(S.IsNull() ) {
3394       THROW_SALOME_CORBA_EXCEPTION("In Sewing a Shape is null", SALOME::BAD_PARAM);
3395     }
3396
3397     /* default OCC is 1.0e-06 */
3398     aMethod.Init(precision, Standard_False);  
3399     for ( TopExp_Explorer exp( S, TopAbs_FACE); exp.More(); exp.Next() ) {
3400       const TopoDS_Face& F = TopoDS::Face(exp.Current());
3401       aMethod.Add(F) ;  
3402     }  
3403     
3404     aMethod.Perform() ;
3405     tds = aMethod.SewedShape() ;
3406     if( !IsValid(tds) ) {
3407       THROW_SALOME_CORBA_EXCEPTION("Make Sewing aborted : non valid shape", SALOME::BAD_PARAM);
3408     }
3409   }
3410   catch (Standard_Failure) {
3411     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeSewing", SALOME::BAD_PARAM);
3412   }
3413   
3414   result = CreateObject(tds);
3415   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3416   result->ShapeId(entry) ;
3417   return result;
3418 }
3419
3420 //==================================================================================
3421 // function : OrientationChange()
3422 // purpose  : Change the orientation of a new shape
3423 //          : TopAbs_FORWARD < -- > TopAbs_REVERSED
3424 //
3425 //          : WARNING : for the moment we make a new shape !
3426 //==================================================================================
3427 GEOM::GEOM_Shape_ptr GEOM_Gen_i::OrientationChange(GEOM::GEOM_Shape_ptr aShape)
3428   throw (SALOME::SALOME_Exception)
3429 {
3430   Unexpect aCatch(SALOME_SalomeException);
3431   GEOM::GEOM_Shape_var result ;  
3432   BRep_Builder aBuilder;  
3433
3434   TopoDS_Shape shape = GetTopoShape(aShape) ;
3435   if( shape.IsNull() ) {
3436     THROW_SALOME_CORBA_EXCEPTION("Shape is null", SALOME::BAD_PARAM);
3437   }
3438
3439   BRepBuilderAPI_Copy Copy(shape);
3440   if( Copy.IsDone() ) {
3441     TopoDS_Shape tds = Copy.Shape();
3442     if( tds.IsNull() ) {
3443       THROW_SALOME_CORBA_EXCEPTION("Orientation aborted : null shape", SALOME::BAD_PARAM);
3444     } 
3445   
3446     if( tds.Orientation() == TopAbs_FORWARD)
3447       tds.Orientation(TopAbs_REVERSED) ;
3448     else
3449       tds.Orientation(TopAbs_FORWARD) ;
3450     
3451     result = CreateObject(tds); 
3452     InsertInLabelOneArgument(shape, aShape, tds, result, myCurrentOCAFDoc) ;
3453   }
3454   return result ;
3455 }
3456
3457
3458 //==================================================================================
3459 // function : GetReferencedObjects()
3460 // purpose  :
3461 //==================================================================================
3462 GEOM::GEOM_Gen::ListOfIOR* GEOM_Gen_i::GetReferencedObjects(GEOM::GEOM_Shape_ptr shape)
3463 {
3464   GEOM::GEOM_Gen::ListOfIOR_var aList = new GEOM::GEOM_Gen::ListOfIOR;
3465   aList->length(0);
3466
3467   if (shape->_is_nil()) return aList._retn();
3468
3469   Standard_CString entry = shape->ShapeId();
3470   TDF_Label Lab;
3471   TDF_Tool::Label(myCurrentOCAFDoc->GetData(), entry, Lab);
3472
3473   Handle(TDataStd_Name) Att;
3474   Lab.FindAttribute(TDataStd_Name::GetID(),Att);
3475
3476   TDF_ChildIterator ChildIterator(Lab);
3477   if (ChildIterator.More()) {
3478     TDF_Label L = ChildIterator.Value();
3479     Handle(TDataStd_Name) Att;
3480     L.FindAttribute(TDataStd_Name::GetID(),Att);
3481     if (Att->Get().IsEqual(TCollection_ExtendedString("Arguments")) ) {
3482
3483       TDF_ChildIterator ChildIterator1(L);
3484       unsigned int i = 0;
3485
3486       while (ChildIterator1.More()) {
3487         TDF_Label L = ChildIterator1.Value();
3488
3489         Handle(TDF_Reference) Ref;
3490         if (L.FindAttribute(TDF_Reference::GetID(),Ref)) {
3491           i++;
3492         }
3493         ChildIterator1.Next();
3494       }
3495       aList->length(i);
3496       i = 0;
3497       TDF_ChildIterator ChildIterator2(L);
3498       while (ChildIterator2.More()) {    
3499         TDF_Label L = ChildIterator2.Value();
3500         Handle(TDF_Reference) Ref;
3501         if (L.FindAttribute(TDF_Reference::GetID(),Ref)) {
3502           TDF_Label L = Ref->Get();
3503           
3504           Handle(TDataStd_Name) Att;
3505           L.FindAttribute(TDataStd_Name::GetID(),Att);
3506           TCollection_AsciiString nameIOR (Att->Get()) ;
3507           aList[i] = strdup( nameIOR.ToCString() );
3508           i++;
3509         }
3510    
3511         ChildIterator2.Next();
3512       }
3513     }
3514   }
3515   return aList._retn();
3516 }
3517
3518 //==================================================================================
3519 // function : GetObjects()
3520 // purpose  :
3521 //==================================================================================
3522 GEOM::GEOM_Gen::ListOfIOR* GEOM_Gen_i::GetObjects(GEOM::GEOM_Shape_ptr shape)
3523 {
3524   GEOM::GEOM_Gen::ListOfIOR_var aList = new GEOM::GEOM_Gen::ListOfIOR;
3525   aList->length(0);
3526   
3527   Standard_CString entry = shape->ShapeId();
3528   TDF_Label Lab;
3529   TDF_Tool::Label(myCurrentOCAFDoc->GetData(), entry, Lab);
3530   
3531   Handle(TDataStd_Name) Att;
3532   Lab.FindAttribute(TDataStd_Name::GetID(),Att);
3533
3534   TDF_ChildIterator ChildIterator(Lab);
3535   unsigned int i = 0;
3536   while (ChildIterator.More()) {
3537     TDF_Label L = ChildIterator.Value();
3538     Handle(TDataStd_Name) Att;
3539     L.FindAttribute(TDataStd_Name::GetID(),Att);
3540
3541     if (!Att->Get().IsEqual(TCollection_ExtendedString("Arguments")) ) {
3542       i++;
3543     }
3544     ChildIterator.Next();
3545   }
3546
3547   aList->length(i);
3548   i = 0;
3549   TDF_ChildIterator ChildIterator1(Lab);
3550   while (ChildIterator1.More()) {
3551     TDF_Label L = ChildIterator1.Value();
3552     Handle(TDataStd_Name) Att;
3553     L.FindAttribute(TDataStd_Name::GetID(),Att);
3554
3555     if (!Att->Get().IsEqual(TCollection_ExtendedString("Arguments")) ) {
3556       TCollection_AsciiString nameIOR (Att->Get());
3557       aList[i] = strdup( nameIOR.ToCString() );
3558       i++;
3559     }
3560     ChildIterator1.Next();
3561   }
3562   return aList._retn();
3563 }
3564
3565
3566 //==================================================================================
3567 // function : Import
3568 // purpose  : Import shape from a BREP file
3569 //==================================================================================
3570 GEOM::GEOM_Shape_ptr GEOM_Gen_i::ImportBREP(const char* filename)
3571   throw (SALOME::SALOME_Exception)
3572 {
3573   Unexpect aCatch(SALOME_SalomeException);
3574   TopoDS_Shape tds ;
3575   GEOM::GEOM_Shape_var result ;
3576   
3577   try {
3578     BRep_Builder aBuilder;  
3579     BRepTools::Read(tds, strdup(filename), aBuilder) ;    
3580     if (tds.IsNull()) {
3581       THROW_SALOME_CORBA_EXCEPTION("Import BRep aborted", SALOME::BAD_PARAM);
3582     } 
3583   }
3584   catch(Standard_Failure) {
3585     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ImportBREP", SALOME::BAD_PARAM);
3586   }
3587
3588   result = CreateObject(tds) ;
3589   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3590   result->ShapeId(entry);
3591   return result; 
3592 }
3593
3594
3595 //================================================================================
3596 // function : MakePlane()
3597 // purpose  : Make a plane topology (non infinite)
3598 //================================================================================
3599 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakePlane(const GEOM::PointStruct& pstruct,
3600                                      const GEOM::DirStruct& dstruct,
3601                                      CORBA::Double trimsize) 
3602   throw (SALOME::SALOME_Exception)
3603 {
3604   Unexpect aCatch(SALOME_SalomeException);
3605   GEOM::GEOM_Shape_var result ;
3606   TopoDS_Shape tds ;
3607
3608   try {
3609     gp_Pnt aPoint(pstruct.x, pstruct.y, pstruct.z) ;
3610     gp_Dir aDirection(dstruct.PS.x, dstruct.PS.y, dstruct.PS.z) ;
3611     /*  we make a trimmed plane */
3612     gp_Pln gplane(aPoint, aDirection) ;    
3613     tds = BRepBuilderAPI_MakeFace(gplane, -trimsize, +trimsize, -trimsize, +trimsize) ;
3614   }
3615   catch(Standard_Failure) {
3616     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakePlane", SALOME::BAD_PARAM);
3617   }
3618
3619   if (tds.IsNull()) {
3620     THROW_SALOME_CORBA_EXCEPTION("Make Plane aborted : null shape", SALOME::BAD_PARAM);
3621    } 
3622   
3623   result = CreateObject(tds) ;
3624   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3625   result->ShapeId(entry);
3626   return result ;
3627 }
3628
3629 //=================================================================================
3630 // function : MakeVertex()
3631 // purpose  : Create a Vertex topology.
3632 //=================================================================================
3633 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeVertex(CORBA::Double x,
3634                                       CORBA::Double y,
3635                                       CORBA::Double z) 
3636   throw (SALOME::SALOME_Exception)
3637 {
3638   Unexpect aCatch(SALOME_SalomeException);
3639   GEOM::GEOM_Shape_var result ; 
3640   gp_Pnt P(x,y,z);
3641   TopoDS_Shape tds = BRepBuilderAPI_MakeVertex(P).Shape();
3642   if (tds.IsNull()) {
3643     THROW_SALOME_CORBA_EXCEPTION("Make Vertex/Point aborted", SALOME::BAD_PARAM);
3644   }
3645   tds.Infinite(true);
3646   result = CreateObject(tds) ;
3647   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3648   result->ShapeId(entry);
3649   return result ;
3650 }
3651
3652
3653 //=================================================================================
3654 // function : MakeFace()
3655 // purpose  : 
3656 //=================================================================================
3657 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeFace( GEOM::GEOM_Shape_ptr wire,
3658                                      CORBA::Boolean wantplanarface ) 
3659   throw (SALOME::SALOME_Exception) 
3660 {
3661   Unexpect aCatch(SALOME_SalomeException);
3662   GEOM::GEOM_Shape_var result ;
3663   TopoDS_Shape aShape;
3664   TopoDS_Shape tds;
3665
3666   try {
3667     aShape = GetTopoShape(wire) ;
3668     if( aShape.IsNull() || aShape.ShapeType() != TopAbs_WIRE ) {
3669       THROW_SALOME_CORBA_EXCEPTION("MakeFace aborted : null or inappropriate shape", SALOME::BAD_PARAM);
3670     }
3671     TopoDS_Wire W = TopoDS::Wire(aShape) ;
3672     tds = BRepBuilderAPI_MakeFace(W, wantplanarface).Shape() ;
3673     if( !tds.IsNull() ) {
3674       result = CreateObject(tds) ;
3675       InsertInLabelOneArgument(aShape, wire, tds, result, myCurrentOCAFDoc) ;
3676     }
3677     else {
3678       THROW_SALOME_CORBA_EXCEPTION("Null result in GEOM_Gen_i::MakeFace", SALOME::BAD_PARAM);
3679     }
3680   }
3681   catch (Standard_Failure) {
3682     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeFace", SALOME::BAD_PARAM);
3683   }  
3684   return result ;
3685 }
3686
3687
3688 //=================================================================================
3689 // function : MakeShell()
3690 // purpose  : Make a compound from a list containing one or more shapes
3691 //=================================================================================
3692 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeShell( const GEOM::GEOM_Gen::ListOfIOR& ListShapes )
3693   throw (SALOME::SALOME_Exception)
3694 {
3695   Unexpect aCatch(SALOME_SalomeException);
3696   GEOM::GEOM_Shape_var result ;
3697   BRepTools_Quilt Glue;
3698   TopoDS_Shape C;
3699
3700   for ( unsigned int i = 0; i < ListShapes.length(); i++) {
3701     GEOM::GEOM_Shape_var aShape = GetIORFromString( ListShapes[i] );    
3702     TopoDS_Shape Shape = GetTopoShape(aShape) ;
3703     if( Shape.IsNull() ) {
3704        THROW_SALOME_CORBA_EXCEPTION("Shell aborted : null shape during operation", SALOME::BAD_PARAM);
3705     }
3706     Glue.Add(Shape) ;
3707   }
3708
3709   TopExp_Explorer exp(Glue.Shells(), TopAbs_SHELL);
3710   Standard_Integer ish = 0; 
3711   for (; exp.More(); exp.Next()) {
3712     C = exp.Current(); 
3713     ish++;
3714   }
3715
3716   if (ish != 1)
3717     C = Glue.Shells();
3718   
3719   if ( C.IsNull() ) {
3720     THROW_SALOME_CORBA_EXCEPTION("Null result : Shell operation aborted", SALOME::BAD_PARAM);
3721   }
3722   else {
3723     result = CreateObject(C) ;
3724     InsertInLabelMoreArguments(C, result, ListShapes, myCurrentOCAFDoc) ;
3725   }
3726   return result;
3727 }
3728
3729
3730 //=================================================================================
3731 // function : MakeSolid()
3732 // purpose  : Make a compound from a list containing one or more shapes
3733 //=================================================================================
3734 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeSolid( const GEOM::GEOM_Gen::ListOfIOR& ListShapes )
3735   throw (SALOME::SALOME_Exception)
3736 {
3737   Unexpect aCatch(SALOME_SalomeException);
3738   GEOM::GEOM_Shape_var result ;
3739   Standard_Integer ish = 0;
3740   TopoDS_Compound  Res;
3741   TopoDS_Solid     Sol;
3742   BRep_Builder     B;
3743   TopoDS_Shape     Shape;
3744
3745   B.MakeCompound(Res);
3746
3747   for ( unsigned int i = 0; i < ListShapes.length(); i++) {
3748     GEOM::GEOM_Shape_var aShape = GetIORFromString( ListShapes[i] );    
3749     TopoDS_Shape Sh = GetTopoShape(aShape) ;
3750     if( Sh.IsNull() ) {
3751        THROW_SALOME_CORBA_EXCEPTION("Solid aborted : null shape during operation", SALOME::BAD_PARAM);
3752     }
3753     B.MakeSolid(Sol);
3754     B.Add(Sol,Sh);
3755     BRepClass3d_SolidClassifier SC(Sol);
3756     SC.PerformInfinitePoint(Precision::Confusion());
3757     if (SC.State() == TopAbs_IN) {
3758       B.MakeSolid(Sol);
3759       B.Add(Sol,Sh.Reversed());
3760     }
3761     B.Add(Res,Sol);
3762     ish++;
3763   }
3764   if (ish == 1) { Shape = Sol;}
3765   else          { Shape = Res;} 
3766   
3767   if ( Shape.IsNull() ) {
3768     THROW_SALOME_CORBA_EXCEPTION("Null result : Solid operation aborted", SALOME::BAD_PARAM);
3769   }
3770   else {
3771     result = CreateObject(Shape) ;
3772     InsertInLabelMoreArguments(Shape, result, ListShapes, myCurrentOCAFDoc) ;
3773   }
3774   return result;
3775 }
3776
3777
3778 //================================================================================
3779 // function : MakeLine
3780 // purpose  : Make a Line topology
3781 //================================================================================
3782 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeLine(const GEOM::PointStruct& pstruct,
3783                                     const GEOM::DirStruct& dstruct)
3784   throw (SALOME::SALOME_Exception)
3785 {
3786   Unexpect aCatch(SALOME_SalomeException);
3787   GEOM::GEOM_Shape_var result  ;
3788   gp_Pnt P1(pstruct.x, pstruct.y, pstruct.z);
3789   gp_Pnt P2(dstruct.PS.x, dstruct.PS.y, dstruct.PS.z) ;  
3790   TopoDS_Shape tds ;
3791   
3792   try {
3793     tds = BRepBuilderAPI_MakeEdge(P1, P2).Shape();
3794   }
3795   catch(Standard_Failure) {
3796     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeLine", SALOME::BAD_PARAM);
3797   }
3798
3799   if ( tds.IsNull() ) {
3800     THROW_SALOME_CORBA_EXCEPTION("Make Line aborted : null shape", SALOME::BAD_PARAM);
3801   }
3802   else {
3803     tds.Infinite(true);
3804     result = CreateObject(tds) ;
3805     const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3806     result->ShapeId(entry);
3807   }
3808   return result ;  
3809 }
3810
3811
3812 //================================================================================
3813 // function : MakeVector()
3814 // purpose  : Make a vector
3815 //================================================================================
3816 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeVector(const GEOM::PointStruct& pstruct1,
3817                                       const GEOM::PointStruct& pstruct2)
3818   throw (SALOME::SALOME_Exception)
3819 {
3820   Unexpect aCatch(SALOME_SalomeException);
3821   GEOM::GEOM_Shape_var result  ;
3822   TopoDS_Shape tds ;
3823   
3824   try {
3825     gp_Pnt P1(pstruct1.x, pstruct1.y, pstruct1.z);
3826     gp_Pnt P2(pstruct2.x, pstruct2.y, pstruct2.z) ;
3827     tds = BRepBuilderAPI_MakeEdge(P1, P2).Shape();
3828   }
3829   catch(Standard_Failure) {
3830     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeVector", SALOME::BAD_PARAM);
3831   }
3832
3833   if ( tds.IsNull() ) {
3834     THROW_SALOME_CORBA_EXCEPTION("Make Vector aborted : null shape", SALOME::BAD_PARAM);
3835   }
3836   else {
3837     result = CreateObject(tds) ;
3838     const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3839     result->ShapeId(entry);
3840   }
3841   return result ;  
3842 }
3843
3844
3845 //================================================================================
3846 // function : MakeCircle()
3847 // purpose  : 
3848 //================================================================================
3849 GEOM::GEOM_Shape_ptr  GEOM_Gen_i::MakeCircle(const GEOM::PointStruct& pstruct,
3850                                        const GEOM::DirStruct& dstruct,
3851                                        CORBA::Double radius)
3852   throw (SALOME::SALOME_Exception) 
3853 {
3854   Unexpect aCatch(SALOME_SalomeException);
3855   GEOM::GEOM_Shape_var result;
3856   TopoDS_Shape tds ;
3857
3858   try {
3859     gp_Pnt p(pstruct.x, pstruct.y, pstruct.z) ;
3860     gp_Dir d(dstruct.PS.x, dstruct.PS.y, dstruct.PS.z) ;
3861     gp_Ax2 axis(p, d) ;
3862     gp_Circ circ( axis, radius);    
3863     BRepBuilderAPI_MakeEdge MakeEdge( circ );
3864     tds = MakeEdge.Edge();
3865   }
3866   catch(Standard_Failure) {
3867     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeCircle", SALOME::BAD_PARAM);
3868   }
3869   if (tds.IsNull()) {
3870     THROW_SALOME_CORBA_EXCEPTION("Make Circle aborted", SALOME::BAD_PARAM);
3871   } 
3872   result = CreateObject(tds);
3873   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3874   result->ShapeId(entry);
3875   return result ;  
3876 }
3877
3878 //================================================================================
3879 // function : MakeEllipse()
3880 // purpose  : 
3881 //================================================================================
3882 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeEllipse( const GEOM::PointStruct& pstruct,
3883                                               const GEOM::DirStruct& dstruct,
3884                                               CORBA::Double radius_major,
3885                                               CORBA::Double radius_minor )
3886   throw (SALOME::SALOME_Exception) 
3887 {
3888   Unexpect aCatch(SALOME_SalomeException);
3889   GEOM::GEOM_Shape_var result;
3890   TopoDS_Shape tds ;
3891   
3892   try {
3893     gp_Pnt p(pstruct.x, pstruct.y, pstruct.z) ;
3894     gp_Dir d(dstruct.PS.x, dstruct.PS.y, dstruct.PS.z) ;
3895
3896     const gp_Ax2 axis(p, d) ;
3897     gp_Elips anEllipse( axis, radius_major, radius_minor ) ;
3898     BRepBuilderAPI_MakeEdge MakeEdge( anEllipse );
3899     tds = MakeEdge.Edge();
3900
3901   }
3902   catch(Standard_Failure) {
3903     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeEllipse", SALOME::BAD_PARAM);
3904   }
3905   if (tds.IsNull()) {
3906     THROW_SALOME_CORBA_EXCEPTION("Make Ellipse aborted", SALOME::BAD_PARAM);
3907   } 
3908   result = CreateObject(tds);
3909   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3910   result->ShapeId(entry);
3911   return result ;  
3912 }
3913
3914 //================================================================================
3915 // function : MakeArc()
3916 // purpose  : make an arc of circle from pInit to pEnd and passing on pCircle
3917 //================================================================================
3918 GEOM::GEOM_Shape_ptr  GEOM_Gen_i::MakeArc(const GEOM::PointStruct& pInit,
3919                                     const GEOM::PointStruct& pCircle,
3920                                     const GEOM::PointStruct& pEnd)
3921   throw (SALOME::SALOME_Exception) 
3922 {
3923   Unexpect aCatch(SALOME_SalomeException);
3924   GEOM::GEOM_Shape_var result;
3925   try {
3926     gp_Pnt pI(pInit.x, pInit.y, pInit.z) ;
3927     gp_Pnt pC(pCircle.x, pCircle.y, pCircle.z) ;
3928     gp_Pnt pE(pEnd.x, pEnd.y, pEnd.z) ;
3929     
3930     GC_MakeArcOfCircle arc( pI, pC, pE ) ;
3931     if( !arc.IsDone() ) {
3932       THROW_SALOME_CORBA_EXCEPTION("Arc not done", SALOME::BAD_PARAM);
3933     }
3934     BRepBuilderAPI_MakeEdge MakeEdge( arc );
3935     TopoDS_Shape tds = MakeEdge.Edge();
3936     if (tds.IsNull()) {
3937       THROW_SALOME_CORBA_EXCEPTION("Null result : arc not done", SALOME::BAD_PARAM);
3938     } 
3939     else {
3940       result = CreateObject(tds);
3941       const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
3942       result->ShapeId(entry);
3943     }
3944   }
3945   catch(Standard_Failure) {
3946     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeArc", SALOME::BAD_PARAM);
3947   }
3948   return result ;
3949 }
3950
3951
3952
3953 //=================================================================================
3954 // function : MakeTranslation()
3955 // purpose  : Translate a 3D shape
3956 //=================================================================================
3957 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeTranslation( GEOM::GEOM_Shape_ptr myShape,
3958                                             CORBA::Double x,
3959                                             CORBA::Double y,
3960                                             CORBA::Double z)
3961   throw (SALOME::SALOME_Exception)
3962 {
3963   Unexpect aCatch(SALOME_SalomeException);
3964   GEOM::GEOM_Shape_var result ;
3965   TopoDS_Shape aShape = GetTopoShape(myShape) ;
3966   if( aShape.IsNull() ) {
3967     THROW_SALOME_CORBA_EXCEPTION("Translation aborted : null shape", SALOME::BAD_PARAM);
3968   }
3969   gp_Vec theVector(x,y,z) ;
3970   gp_Trsf theTransformation ;
3971   theTransformation.SetTranslation(theVector) ;
3972   BRepBuilderAPI_Transform myBRepTransformation(aShape, theTransformation, Standard_False) ;
3973   TopoDS_Shape tds = myBRepTransformation.Shape() ;
3974
3975   result = CreateObject(tds) ;
3976   if( CORBA::is_nil(result) ) {
3977     THROW_SALOME_CORBA_EXCEPTION("Translation aborted : null result", SALOME::BAD_PARAM);
3978   }
3979   InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
3980   return result;
3981 }
3982
3983
3984 //=================================================================================
3985 // function : MakeMultiTranslation1D()
3986 // purpose  : Multi-Translate a 3D shape
3987 //=================================================================================
3988 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeMultiTranslation1D( GEOM::GEOM_Shape_ptr myShape,
3989                                                    const GEOM::DirStruct& dir,
3990                                                    CORBA::Double step,
3991                                                    CORBA::Short nbtimes )
3992   throw (SALOME::SALOME_Exception)
3993 {
3994   Unexpect aCatch(SALOME_SalomeException);
3995   GEOM::GEOM_Shape_var result ;
3996   TopoDS_Shape tds ;
3997
3998   TopoDS_Shape aShape = GetTopoShape(myShape) ;
3999   if( aShape.IsNull() )
4000     THROW_SALOME_CORBA_EXCEPTION("MakeMultiTranslation1D aborted : null shape", SALOME::BAD_PARAM);
4001   
4002   try {
4003     int i ;
4004     double DX, DY, DZ ;
4005     gp_Trsf theTransformation ;
4006     gp_Vec myVec ;
4007     gp_Vec Vec( dir.PS.x, dir.PS.y, dir.PS.z ) ;
4008     Vec.Normalize();
4009     TopoDS_Compound compound;
4010     BRep_Builder B;
4011     B.MakeCompound( compound );
4012     
4013     for ( i = 0; i < nbtimes; i++ ) {
4014       DX = i * step * Vec.X() ;
4015       DY = i * step * Vec.Y() ;
4016       DZ = i * step * Vec.Z() ;
4017       myVec.SetCoord( DX, DY, DZ ) ;
4018       theTransformation.SetTranslation(myVec) ;
4019       BRepBuilderAPI_Transform myBRepTransformation(aShape, theTransformation, Standard_False) ;
4020       B.Add( compound, myBRepTransformation.Shape() );
4021     }
4022     tds = compound ;
4023     result = CreateObject(tds) ;
4024   }
4025   catch (Standard_Failure) {
4026     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeMultiTranslation1D", SALOME::BAD_PARAM);
4027   }
4028     
4029   if( CORBA::is_nil(result) ) {
4030     THROW_SALOME_CORBA_EXCEPTION("MakeMultiTranslation1D aborted : null result", SALOME::BAD_PARAM);
4031   }
4032   InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4033   return result;
4034 }
4035
4036
4037 //=================================================================================
4038 // function : MakeMultiTranslation2D()
4039 // purpose  : Multi-Translate a 3D shape
4040 //=================================================================================
4041 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeMultiTranslation2D( GEOM::GEOM_Shape_ptr myShape,
4042                                                    const GEOM::DirStruct& dir1,
4043                                                    CORBA::Double step1,
4044                                                    CORBA::Short nbtimes1,
4045                                                    const GEOM::DirStruct& dir2,
4046                                                    CORBA::Double step2,
4047                                                    CORBA::Short nbtimes2 )
4048   throw (SALOME::SALOME_Exception)
4049 {
4050   Unexpect aCatch(SALOME_SalomeException);
4051   GEOM::GEOM_Shape_var result ;
4052   TopoDS_Shape tds ;
4053   
4054   TopoDS_Shape aShape = GetTopoShape(myShape) ;
4055   if( aShape.IsNull() ) {
4056     THROW_SALOME_CORBA_EXCEPTION("MakeMultiTranslation2D aborted : null shape", SALOME::BAD_PARAM);
4057   }
4058   
4059   try {
4060     int i, j ;
4061     double DX, DY, DZ ;
4062     gp_Trsf theTransformation ;
4063     gp_Vec myVec ;
4064     gp_Vec Vec1( dir1.PS.x, dir1.PS.y, dir1.PS.z ) ;
4065     Vec1.Normalize();
4066     gp_Vec Vec2( dir2.PS.x, dir2.PS.y, dir2.PS.z ) ;
4067     Vec2.Normalize();
4068     TopoDS_Compound compound;
4069     BRep_Builder B;
4070     B.MakeCompound( compound );
4071     
4072     for ( i = 0; i < nbtimes1; i++ ) {
4073       for ( j = 0; j < nbtimes2; j++ ) {
4074         DX = i * step1 * Vec1.X() + j * step2 * Vec2.X() ;
4075         DY = i * step1 * Vec1.Y() + j * step2 * Vec2.Y() ;
4076         DZ = i * step1 * Vec1.Z() + j * step2 * Vec2.Z() ;
4077         myVec.SetCoord( DX, DY, DZ ) ;
4078         theTransformation.SetTranslation(myVec) ;
4079         BRepBuilderAPI_Transform myBRepTransformation(aShape, theTransformation, Standard_False) ;
4080         B.Add( compound, myBRepTransformation.Shape() );
4081       }
4082     }
4083     tds = compound ;
4084     result = CreateObject(tds) ;
4085   }
4086   catch(Standard_Failure) {
4087     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeMultiTranslation2D", SALOME::BAD_PARAM);
4088   }
4089    
4090   if( CORBA::is_nil(result) ) {
4091     THROW_SALOME_CORBA_EXCEPTION("MakeMultiTranslation2D aborted : null result", SALOME::BAD_PARAM);
4092   }
4093   InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4094   return result;
4095 }
4096
4097
4098 //=================================================================================
4099 // function : MakeMultiRotation1D()
4100 // purpose  : Multi-Rotate a 3D shape
4101 //=================================================================================
4102 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeMultiRotation1D( GEOM::GEOM_Shape_ptr myShape,
4103                                                 const GEOM::DirStruct& dir,
4104                                                 const GEOM::PointStruct& loc,
4105                                                 CORBA::Short nbtimes)
4106   throw (SALOME::SALOME_Exception)
4107 {
4108   Unexpect aCatch(SALOME_SalomeException);
4109   GEOM::GEOM_Shape_var result ;
4110   TopoDS_Shape tds ;
4111   TopoDS_Shape aShape = GetTopoShape(myShape) ;
4112   if( aShape.IsNull() ) {
4113     THROW_SALOME_CORBA_EXCEPTION("MakeMultiRotation1D aborted : null shape", SALOME::BAD_PARAM);
4114   }
4115  
4116   try {
4117
4118     int i ;
4119     gp_Pnt P(loc.x, loc.y, loc.z) ;
4120     gp_Dir D(dir.PS.x, dir.PS.y, dir.PS.z) ;
4121     gp_Ax1 AX1(P, D) ;
4122     
4123     double angle = 360.0/nbtimes ;
4124     gp_Trsf theTransformation ;
4125     TopoDS_Compound compound;
4126     BRep_Builder B;
4127     B.MakeCompound( compound );
4128     
4129     for ( i = 0; i < nbtimes; i++ ) {
4130       theTransformation.SetRotation(AX1, i*angle*PI180) ;
4131       BRepBuilderAPI_Transform myBRepTransformation(aShape, theTransformation, Standard_False) ;
4132       B.Add( compound, myBRepTransformation.Shape() );
4133     }
4134     tds = compound ;
4135     result = CreateObject(tds) ;
4136   }
4137   catch(Standard_Failure) {
4138     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeMultiRotation1D", SALOME::BAD_PARAM);
4139   }
4140   
4141   if( CORBA::is_nil(result) ) {
4142     THROW_SALOME_CORBA_EXCEPTION("MakeMultiRotation1D aborted : null result", SALOME::BAD_PARAM);
4143   }
4144   InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4145   return result;
4146 }
4147
4148
4149 //=================================================================================
4150 // function : MakeMultiRotation2D()
4151 // purpose  : Multi-Rotate a 3D shape
4152 //=================================================================================
4153 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeMultiRotation2D( GEOM::GEOM_Shape_ptr myShape,
4154                                                 const GEOM::DirStruct& dir,
4155                                                 const GEOM::PointStruct& loc,
4156                                                 CORBA::Double ang,
4157                                                 CORBA::Short nbtimes1,
4158                                                 CORBA::Double step,
4159                                                 CORBA::Short nbtimes2 )
4160   throw (SALOME::SALOME_Exception)
4161 {
4162   Unexpect aCatch(SALOME_SalomeException);
4163   GEOM::GEOM_Shape_var result ;
4164   TopoDS_Shape tds ;
4165   TopoDS_Shape aShape = GetTopoShape(myShape) ;
4166   if( aShape.IsNull() ) {
4167     THROW_SALOME_CORBA_EXCEPTION("MakeMultiRotation2D aborted : null shape", SALOME::BAD_PARAM);
4168   }
4169
4170   try {
4171    
4172     int i, j ;
4173     double DX, DY, DZ ;
4174     gp_Pnt P(loc.x, loc.y, loc.z) ;
4175     gp_Dir D(dir.PS.x, dir.PS.y, dir.PS.z) ;
4176     gp_Ax1 AX1(P, D) ;
4177     gp_Trsf theTransformation1 ;
4178     gp_Trsf theTransformation2 ;
4179     gp_Pnt P1 ;
4180     GProp_GProps System ;
4181     
4182     if ( aShape.ShapeType() == TopAbs_VERTEX) {
4183       P1 = BRep_Tool::Pnt(TopoDS::Vertex( aShape ));
4184     } 
4185     else if ( aShape.ShapeType() == TopAbs_EDGE || aShape.ShapeType() == TopAbs_WIRE ) {
4186       BRepGProp::LinearProperties(aShape, System);
4187       P1 = System.CentreOfMass() ;
4188     }
4189     else if ( aShape.ShapeType() == TopAbs_FACE || aShape.ShapeType() == TopAbs_SHELL ) {
4190       BRepGProp::SurfaceProperties(aShape, System);
4191       P1 = System.CentreOfMass() ;
4192     }
4193     else {
4194       BRepGProp::VolumeProperties(aShape, System);
4195       P1 = System.CentreOfMass() ;
4196     }
4197     
4198     Handle(Geom_Line) Line = new Geom_Line(AX1);
4199     gp_Pnt P2 = GeomAPI_ProjectPointOnCurve( P1, Line ) ;
4200     
4201     if ( P1.IsEqual(P2, Precision::Confusion() ) )
4202       THROW_SALOME_CORBA_EXCEPTION("Points are confused", SALOME::BAD_PARAM);
4203     
4204     gp_Vec Vec(P1.X()-P2.X(), P1.Y()-P2.Y(), P1.Z()-P2.Z()) ;
4205     Vec.Normalize();
4206     
4207     gp_Vec myVec ;
4208     TopoDS_Compound compound;
4209     BRep_Builder B;
4210     B.MakeCompound( compound );
4211     
4212     for ( i = 0; i < nbtimes2; i++ ) {
4213       for ( j = 0; j < nbtimes1; j++ ) {
4214         DX = i * step * Vec.X() ;
4215         DY = i * step * Vec.Y() ;
4216         DZ = i * step * Vec.Z() ;
4217         myVec.SetCoord( DX, DY, DZ ) ;
4218         theTransformation1.SetTranslation(myVec) ;
4219         theTransformation2.SetRotation(AX1, j*ang*PI180) ;
4220         BRepBuilderAPI_Transform myBRepTransformation1(aShape, theTransformation1, Standard_False) ;
4221         BRepBuilderAPI_Transform myBRepTransformation2(myBRepTransformation1.Shape(), theTransformation2, Standard_False) ;
4222         B.Add( compound, myBRepTransformation2.Shape() );
4223       }
4224     }
4225     tds = compound ;
4226     result = CreateObject(tds) ;  
4227   }
4228   catch(Standard_Failure) {
4229     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeMultiRotation2D", SALOME::BAD_PARAM);
4230   }
4231   
4232   if( CORBA::is_nil(result) ) {
4233     THROW_SALOME_CORBA_EXCEPTION("MakeMultiRotation2D aborted : null result", SALOME::BAD_PARAM);
4234   }
4235   InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4236   return result;
4237 }
4238
4239
4240 //=================================================================================
4241 // function : MakeCopy()
4242 // purpose  : Copy a 3D shape
4243 //=================================================================================
4244 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeCopy( GEOM::GEOM_Shape_ptr Shape)
4245   throw (SALOME::SALOME_Exception) 
4246 {
4247   Unexpect aCatch(SALOME_SalomeException);
4248   GEOM::GEOM_Shape_var result ;
4249   TopoDS_Shape tds ;
4250   TopoDS_Shape aShape = GetTopoShape(Shape) ;
4251   if(aShape.IsNull() ) {
4252     THROW_SALOME_CORBA_EXCEPTION("Copy aborted : null shape during operation", SALOME::BAD_PARAM);
4253   }  
4254   BRepBuilderAPI_Copy Copy(aShape);
4255   if( Copy.IsDone() ) {   
4256     tds = Copy.Shape();
4257     result = CreateObject(tds);    
4258     InsertInLabelOneArgument(aShape, Shape, tds, result, myCurrentOCAFDoc) ;
4259   }
4260
4261   return result;
4262 }
4263
4264
4265 //=================================================================================
4266 // function : MakeMirrorByPlane()
4267 // purpose  : build a shape by symmetry of 'myShape' with 'shapePlane' in argument
4268 //=================================================================================
4269 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeMirrorByPlane(GEOM::GEOM_Shape_ptr myShape,
4270                                              GEOM::GEOM_Shape_ptr shapePlane) 
4271   throw (SALOME::SALOME_Exception)
4272 {
4273   Unexpect aCatch(SALOME_SalomeException);
4274   GEOM::GEOM_Shape_var result ; 
4275   TopoDS_Shape tds ;
4276   TopoDS_Shape aShape      = GetTopoShape(myShape) ;
4277   TopoDS_Shape aShapePlane = GetTopoShape(shapePlane) ;
4278   if( aShape.IsNull()  || aShapePlane.IsNull() ) {
4279     THROW_SALOME_CORBA_EXCEPTION("Mirror aborted : null shape argument", SALOME::BAD_PARAM);
4280   }  
4281   
4282   try {
4283     Handle(Geom_Surface) surf = BRep_Tool::Surface(TopoDS::Face(aShapePlane)) ; 
4284     Handle(Geom_Plane) myPlane = Handle(Geom_Plane)::DownCast(surf) ;
4285     const gp_Ax3 pos = myPlane->Position() ;
4286     const gp_Pnt loc = pos.Location() ;  /* location of the plane */
4287     const gp_Dir dir = pos.Direction() ; /* Main direction of the plane (Z axis) */  
4288     
4289     /* plane used for mirroring */
4290     gp_Ax2 pln(loc, dir) ;
4291     gp_Trsf theTransformation ;
4292     theTransformation.SetMirror(pln) ;
4293     BRepBuilderAPI_Transform myBRepTransformation(aShape, theTransformation, Standard_False) ;
4294
4295     tds = myBRepTransformation.Shape() ;
4296     if(tds.IsNull() ) {
4297       THROW_SALOME_CORBA_EXCEPTION("Mirror aborted", SALOME::BAD_PARAM);
4298     }
4299   }
4300   catch(Standard_Failure) {
4301     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeMirrorByPlane", SALOME::BAD_PARAM);    
4302   }
4303   
4304   result = CreateObject(tds) ;
4305
4306   /* Insert arguments in ocaf */
4307   GEOM::GEOM_Gen::ListOfIOR_var ListShapes = new GEOM::GEOM_Gen::ListOfIOR;
4308   ListShapes->length(2);
4309   ListShapes[0] = GetStringFromIOR(GEOM::GEOM_Shape::_duplicate(myShape)) ;
4310   ListShapes[1] = GetStringFromIOR(GEOM::GEOM_Shape::_duplicate(shapePlane)) ;
4311   InsertInLabelMoreArguments(tds, result, ListShapes, myCurrentOCAFDoc) ;
4312   return result ;
4313 }
4314
4315
4316
4317 //=================================================================================
4318 // function : MakeRotation()
4319 // purpose  : Rotation of a 3D shape around an axis
4320 //=================================================================================
4321 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeRotation( GEOM::GEOM_Shape_ptr myShape,
4322                                          const GEOM::AxisStruct& axis,
4323                                          CORBA::Double angle)
4324   throw (SALOME::SALOME_Exception)
4325 {
4326   Unexpect aCatch(SALOME_SalomeException);
4327   GEOM::GEOM_Shape_var result ;
4328   TopoDS_Shape tds ;
4329   TopoDS_Shape aShape = GetTopoShape(myShape) ;
4330   if( aShape.IsNull() ) {
4331     THROW_SALOME_CORBA_EXCEPTION("Rotation aborted : null shape during operation", SALOME::BAD_PARAM);
4332   }
4333   
4334   try {
4335     gp_Pnt P(axis.x, axis.y, axis.z) ;
4336     gp_Dir D(axis.vx, axis.vy, axis.vz) ;
4337     gp_Ax1 AX(P, D) ;
4338     
4339     gp_Trsf theTransformation ;
4340     theTransformation.SetRotation(AX, angle) ;
4341     BRepBuilderAPI_Transform myBRepTransformation(aShape, theTransformation, Standard_False) ;
4342     tds = myBRepTransformation.Shape() ;
4343   }
4344   catch(Standard_Failure) {
4345     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeRotation", SALOME::BAD_PARAM);
4346   }
4347   
4348   if ( !tds.IsNull() ) {
4349     result = CreateObject(tds) ;
4350     InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4351   }
4352   return result ;
4353 }
4354
4355
4356 //=================================================================================
4357 // function : MakeScaleTransform()
4358 // purpose  : Make a shape multipling another by a scale factor
4359 //=================================================================================
4360 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeScaleTransform(GEOM::GEOM_Shape_ptr myShape,
4361                                               const GEOM::PointStruct& theCenterOfScale,
4362                                               CORBA::Double factor)
4363   throw (SALOME::SALOME_Exception)
4364 {
4365   Unexpect aCatch(SALOME_SalomeException);
4366   GEOM::GEOM_Shape_var result ;
4367   TopoDS_Shape tds ;
4368   TopoDS_Shape aShape = GetTopoShape(myShape) ;
4369   if( aShape.IsNull() ) {
4370     THROW_SALOME_CORBA_EXCEPTION("Scale aborted : null shape during operation", SALOME::BAD_PARAM);
4371   }
4372   
4373   try {
4374     gp_Pnt Pcenter(theCenterOfScale.x, theCenterOfScale.y, theCenterOfScale.z) ;
4375     gp_Trsf theTransformation ;  
4376     theTransformation.SetScale(Pcenter, factor) ;
4377     BRepBuilderAPI_Transform myBRepTransformation(aShape, theTransformation, Standard_False) ;
4378     tds = myBRepTransformation.Shape() ;
4379   }
4380   catch(Standard_Failure) {
4381     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeScaleTransform", SALOME::BAD_PARAM);
4382   }
4383   
4384   if ( !tds.IsNull() ) {
4385     result = CreateObject(tds) ; 
4386     InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4387   }
4388   return result ;
4389 }
4390
4391
4392 //=================================================================================
4393 // function : MakeCompound()
4394 // purpose  : Make a compound from a list containing one or more shapes
4395 //=================================================================================
4396 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeCompound( const GEOM::GEOM_Gen::ListOfIOR& ListShapes )
4397   throw (SALOME::SALOME_Exception)
4398 {
4399   Unexpect aCatch(SALOME_SalomeException);
4400   GEOM::GEOM_Shape_var result ;
4401   TopoDS_Compound C;
4402   BRep_Builder aBuilder;
4403   aBuilder.MakeCompound(C) ;
4404
4405   for ( unsigned int i = 0; i < ListShapes.length(); i++) {
4406     GEOM::GEOM_Shape_var aShape = GetIORFromString( ListShapes[i] );    
4407     TopoDS_Shape Shape = GetTopoShape(aShape) ;
4408     if( Shape.IsNull() ) {
4409        THROW_SALOME_CORBA_EXCEPTION("Compound aborted : null shape during operation", SALOME::BAD_PARAM);
4410     }
4411     aBuilder.Add(C, Shape) ;
4412   }
4413   
4414   if ( C.IsNull() ) {
4415     THROW_SALOME_CORBA_EXCEPTION("Null result : Compound operation aborted", SALOME::BAD_PARAM);
4416   }
4417   else {
4418     result = CreateObject(C) ;
4419     InsertInLabelMoreArguments(C, result, ListShapes, myCurrentOCAFDoc) ;
4420   }
4421   return result;
4422 }
4423
4424
4425 //================================================================================
4426 // function : MakeEdge()
4427 // purpose  : Make a linear edge with 2 points
4428 //================================================================================
4429 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeEdge(const GEOM::PointStruct& pstruct1,
4430                                     const GEOM::PointStruct& pstruct2)
4431   throw (SALOME::SALOME_Exception)
4432 {
4433   Unexpect aCatch(SALOME_SalomeException);
4434   GEOM::GEOM_Shape_var result  ;
4435   TopoDS_Shape tds ;
4436   
4437   try {
4438     gp_Pnt P1(pstruct1.x, pstruct1.y, pstruct1.z);
4439     gp_Pnt P2(pstruct2.x, pstruct2.y, pstruct2.z) ;  
4440     tds = BRepBuilderAPI_MakeEdge(P1, P2).Shape();
4441     if ( tds.IsNull() )
4442       THROW_SALOME_CORBA_EXCEPTION("MakeEdge aborted : null result", SALOME::BAD_PARAM);
4443   }
4444   catch (Standard_Failure) {
4445     THROW_SALOME_CORBA_EXCEPTION("Exception catched in MakeEdge", SALOME::BAD_PARAM);
4446   }
4447   
4448   result = CreateObject(tds) ;
4449   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
4450   result->ShapeId(entry);
4451   return result ;  
4452 }
4453
4454
4455
4456 //=================================================================================
4457 // function : MakeWire()
4458 // purpose  : Make a wire from a list containing one or more edges or wires that can
4459 // be connected
4460 //=================================================================================
4461 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeWire( const GEOM::GEOM_Gen::ListOfIOR& ListShapes )
4462   throw (SALOME::SALOME_Exception)
4463 {
4464   Unexpect aCatch(SALOME_SalomeException);
4465   GEOM::GEOM_Shape_var result ;
4466   BRepBuilderAPI_MakeWire MW ;
4467   TopoDS_Shape tds, Shape ; 
4468   
4469   try {
4470     for ( unsigned int i = 0; i < ListShapes.length(); i++) {
4471       GEOM::GEOM_Shape_var aShape = GetIORFromString( ListShapes[i] );    
4472       Shape = GetTopoShape(aShape) ;
4473       if( Shape.IsNull() ) {
4474         THROW_SALOME_CORBA_EXCEPTION("MakeWire aborted : null shape during operation", SALOME::BAD_PARAM);
4475       }
4476       if( Shape.ShapeType() == TopAbs_EDGE )
4477         MW.Add( TopoDS::Edge(Shape) ) ;
4478       if (Shape.ShapeType() == TopAbs_WIRE ) 
4479         MW.Add( TopoDS::Wire(Shape) ) ;
4480     }    
4481     tds = MW  ;
4482
4483   }
4484   catch(Standard_Failure) {
4485     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeWire", SALOME::BAD_PARAM);
4486   }
4487   
4488   if( tds.IsNull() ) {
4489     THROW_SALOME_CORBA_EXCEPTION("Make Wire operation aborted : null result", SALOME::BAD_PARAM);
4490   }
4491   else {
4492     result = CreateObject(tds) ;
4493     InsertInLabelMoreArguments(tds, result, ListShapes, myCurrentOCAFDoc) ;   
4494   }
4495   return result;
4496 }
4497
4498
4499 //=================================================================================
4500 // function : MakeRevolution()
4501 // purpose  : 
4502 //=================================================================================
4503 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeRevolution(GEOM::GEOM_Shape_ptr myShape,
4504                                           const GEOM::AxisStruct& axis,
4505                                           double angle)
4506   throw (SALOME::SALOME_Exception)
4507
4508   Unexpect aCatch(SALOME_SalomeException);
4509   GEOM::GEOM_Shape_var result ;
4510   TopoDS_Shape tds ;
4511   TopoDS_Shape aShape = GetTopoShape(myShape) ;
4512   if( aShape.IsNull() ) {
4513     THROW_SALOME_CORBA_EXCEPTION("Revolution aborted : null shape", SALOME::BAD_PARAM);
4514   }
4515   try {
4516     gp_Pnt P(axis.x, axis.y, axis.z) ;
4517     gp_Dir D(axis.vx, axis.vy, axis.vz);
4518     gp_Ax1 AX(P,D);
4519     tds = BRepPrimAPI_MakeRevol(aShape, AX, angle);
4520   }
4521   catch(Standard_Failure) {
4522     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeRevolution", SALOME::BAD_PARAM);
4523   }
4524   
4525   if( tds.IsNull() ) {
4526     THROW_SALOME_CORBA_EXCEPTION("Revolution aborted", SALOME::BAD_PARAM);
4527   }
4528   result = CreateObject(tds) ;
4529   InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4530   return result ;     
4531 }
4532
4533
4534 //=================================================================================
4535 // function : MakePipe()
4536 // purpose  : Create a shape by sweeping a baseShape along a pathShape
4537 //=================================================================================
4538 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakePipe( GEOM::GEOM_Shape_ptr pathShape,
4539                                      GEOM::GEOM_Shape_ptr baseShape )
4540   throw (SALOME::SALOME_Exception)
4541 {
4542   Unexpect aCatch(SALOME_SalomeException);
4543   GEOM::GEOM_Shape_var result ;
4544   TopoDS_Shape tds ;
4545   TopoDS_Wire aWire ;
4546   TopoDS_Shape pathTds = GetTopoShape(pathShape) ;
4547   TopoDS_Shape baseTds = GetTopoShape(baseShape) ;
4548
4549   if( baseTds.IsNull() || pathTds.IsNull() ) {
4550     THROW_SALOME_CORBA_EXCEPTION("MakePipe aborted : null shape argument", SALOME::BAD_PARAM);
4551   }
4552
4553   if( pathTds.ShapeType() == TopAbs_WIRE ) {
4554     aWire = TopoDS::Wire(pathTds) ;
4555   }
4556   else {
4557     if ( pathTds.ShapeType() == TopAbs_EDGE ) {
4558       TopoDS_Edge aEdge = TopoDS::Edge(pathTds) ;
4559       aWire = BRepBuilderAPI_MakeWire(aEdge);
4560     }
4561     else {
4562       THROW_SALOME_CORBA_EXCEPTION("MakePipe aborted : bad shape type", SALOME::BAD_PARAM);
4563     }
4564   }
4565
4566   try {
4567     tds = BRepOffsetAPI_MakePipe(aWire, baseTds) ;
4568   }
4569   catch(Standard_Failure) {
4570     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakePipe", SALOME::BAD_PARAM);
4571   }
4572   
4573   if (  !IsValid(tds) ) {
4574     THROW_SALOME_CORBA_EXCEPTION("MakePipe aborted : non valid shape result", SALOME::BAD_PARAM);
4575   }
4576   else {
4577     result = CreateObject(tds) ;
4578
4579     /* Insert arguments in ocaf */
4580     GEOM::GEOM_Gen::ListOfIOR_var ListShapes = new GEOM::GEOM_Gen::ListOfIOR;
4581     ListShapes->length(2);
4582     ListShapes[0] = GetStringFromIOR(GEOM::GEOM_Shape::_duplicate(pathShape)) ;
4583     ListShapes[1] = GetStringFromIOR(GEOM::GEOM_Shape::_duplicate(baseShape)) ;    
4584     InsertInLabelMoreArguments(tds, result, ListShapes, myCurrentOCAFDoc) ;
4585   }
4586   return result ;
4587 }
4588
4589
4590 //=================================================================================
4591 // function : MakePrism()
4592 // purpose  : uses myShape as base and the vector P1 to P2
4593 //=================================================================================
4594 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakePrism( GEOM::GEOM_Shape_ptr myShape,
4595                                            const GEOM::PointStruct& P1,
4596                                            const GEOM::PointStruct& P2 )
4597   throw (SALOME::SALOME_Exception)
4598 {               
4599   Unexpect aCatch(SALOME_SalomeException);
4600   GEOM::GEOM_Shape_var result ;
4601   TopoDS_Shape tds ;
4602   TopoDS_Shape aShape = GetTopoShape(myShape) ;
4603   if( aShape.IsNull() ) {
4604     THROW_SALOME_CORBA_EXCEPTION("Prism aborted : null shape operation", SALOME::BAD_PARAM);
4605   }
4606   
4607   try {
4608     gp_Vec Vector (P2.x - P1.x, P2.y - P1.y, P2.z - P1.z) ;
4609     tds = BRepPrimAPI_MakePrism(aShape, Vector, Standard_False).Shape() ;
4610   }
4611   catch(Standard_Failure) {
4612     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakePipe", SALOME::BAD_PARAM);
4613   }
4614   
4615   if ( tds.IsNull() ) {
4616     THROW_SALOME_CORBA_EXCEPTION("Prism aborted", SALOME::BAD_PARAM);
4617   }
4618   else {
4619     result = CreateObject(tds) ;     
4620     InsertInLabelOneArgument(aShape, myShape, tds, result, myCurrentOCAFDoc) ;
4621   }
4622   return result ;
4623 }
4624
4625
4626 //=================================================================================
4627 // function : MakeCDG()
4628 // purpose  : Create a CDG topology.
4629 //=================================================================================
4630 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeCDG(GEOM::GEOM_Shape_ptr aShape) 
4631   throw (SALOME::SALOME_Exception)
4632 {
4633   Unexpect aCatch(SALOME_SalomeException);
4634   GEOM::GEOM_Shape_var result ;
4635   TopoDS_Shape tds ;
4636   TopoDS_Shape shape = GetTopoShape(aShape) ;
4637   GProp_GProps System;
4638   gp_Pnt myCenterMass ;
4639
4640   if( shape.IsNull() ) {
4641     THROW_SALOME_CORBA_EXCEPTION("MakeCDG aborted : null shape argument", SALOME::BAD_PARAM);
4642   }
4643   
4644   try {
4645     if ( shape.ShapeType() == TopAbs_VERTEX) {
4646       myCenterMass = BRep_Tool::Pnt(TopoDS::Vertex( shape ));
4647     } 
4648     else if ( shape.ShapeType() == TopAbs_EDGE || shape.ShapeType() == TopAbs_WIRE ) {
4649       BRepGProp::LinearProperties(shape, System);
4650       myCenterMass = System.CentreOfMass() ;
4651     }
4652     else if ( shape.ShapeType() == TopAbs_FACE || shape.ShapeType() == TopAbs_SHELL ) {
4653       BRepGProp::SurfaceProperties(shape, System);
4654       myCenterMass = System.CentreOfMass() ;
4655     }
4656     else {
4657       BRepGProp::VolumeProperties(shape, System);
4658       myCenterMass = System.CentreOfMass() ;
4659     }
4660
4661     tds = BRepBuilderAPI_MakeVertex(myCenterMass).Shape() ;
4662   }
4663   catch(Standard_Failure) {
4664     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeCDG", SALOME::BAD_PARAM);
4665   }
4666   
4667   if ( tds.IsNull() ) {
4668     THROW_SALOME_CORBA_EXCEPTION("Make CDG aborted : null shape result", SALOME::BAD_PARAM);
4669   }
4670   else {
4671     result = CreateObject(tds) ;     
4672     InsertInLabelOneArgument(shape, aShape, tds, result, myCurrentOCAFDoc) ;
4673   }
4674   return result ; 
4675 }
4676
4677
4678 //=================================================================================
4679 // function : Archimede()
4680 // purpose  :
4681 //=================================================================================
4682 GEOM::GEOM_Shape_ptr GEOM_Gen_i::Archimede(GEOM::GEOM_Shape_ptr aShape,
4683                                      CORBA::Double aWeight,
4684                                      CORBA::Double aWaterDensity,
4685                                      CORBA::Double aMeshingDeflection)
4686   throw (SALOME::SALOME_Exception)
4687 {
4688   Unexpect aCatch(SALOME_SalomeException);
4689   GEOM::GEOM_Shape_var result;
4690
4691   double cste = -1;
4692   if (aWaterDensity != 0.)
4693     cste = aWeight/aWaterDensity;
4694   else
4695     THROW_SALOME_CORBA_EXCEPTION("Water density is null", SALOME::BAD_PARAM);
4696
4697   TopoDS_Shape shape = GetTopoShape(aShape) ;
4698   if( shape.IsNull() ) {
4699     THROW_SALOME_CORBA_EXCEPTION("Shape is null", SALOME::BAD_PARAM);
4700   }
4701
4702   gp_Dir direct(0.0,0.0,1.0);
4703   gp_Pnt PosPlan(0.0,0.0,0.0);
4704   Geom_Plane PP (PosPlan,direct);
4705   Handle(Geom_Geometry) G = PP.Copy();
4706   Handle(Geom_Plane) P = Handle(Geom_Plane)::DownCast(G);
4707
4708   gp_Dir Zdirection(0.0,0.0,1.0);
4709   VolumeSection VOL( shape, aMeshingDeflection);
4710   VOL.SetPlane(P);
4711   Handle (Geom_RectangularTrimmedSurface) SurfaceTrimmee;
4712   
4713   if(Zdirection.IsEqual(direct,Precision::Angular()) == Standard_False) { 
4714     VOL.MakeRotation(direct);
4715   }
4716   
4717   VOL.CenterOfGravity();
4718   SurfaceTrimmee = VOL.TrimSurf();
4719   Standard_Real Cote = VOL.Archimede( cste, aMeshingDeflection );
4720   
4721   if ( Cote == -1 ) {
4722     double Zmin,Zmax;
4723     VOL.getZ(Zmin,Zmax);
4724     double volume = VOL.CalculateVolume( Zmax ) * aWaterDensity;
4725
4726     char msg[100]="";  
4727     sprintf(msg, "shape sinks to the bottom : Weigth max = %.1f", volume);
4728
4729     THROW_SALOME_CORBA_EXCEPTION(msg, SALOME::BAD_PARAM);
4730   }
4731   
4732   SurfaceTrimmee=VOL.AjustePlan(SurfaceTrimmee,Cote,PosPlan);
4733   if(Zdirection.IsEqual(direct,Precision::Angular()) == Standard_False) { 
4734     SurfaceTrimmee=VOL.InvMakeRotation(direct,SurfaceTrimmee);
4735   }
4736   
4737   Standard_Real u1,u2,v1,v2;
4738   SurfaceTrimmee->Bounds(u1,u2,v1,v2);
4739   TopoDS_Face tirant = BRepBuilderAPI_MakeFace(SurfaceTrimmee, u1, u2, v1, v2);
4740   
4741   if (tirant.IsNull()) {
4742     THROW_SALOME_CORBA_EXCEPTION("Result is null", SALOME::BAD_PARAM);
4743   }
4744
4745   result = CreateObject(tirant);
4746   InsertInLabelOneArgument(shape, aShape, tirant, result, myCurrentOCAFDoc) ;
4747
4748   return result;  
4749 }
4750
4751
4752 //================================================================================
4753 // function : MakeFillet()
4754 // purpose  : Create a cylinder topology
4755 //================================================================================
4756 GEOM::GEOM_Shape_ptr  GEOM_Gen_i::MakeFillet( GEOM::GEOM_Shape_ptr shape,
4757                                               CORBA::Double radius,
4758                                               CORBA::Short ShapeType,
4759                                               const GEOM::GEOM_Shape::ListOfSubShapeID& ListOfID ) 
4760   throw (SALOME::SALOME_Exception)
4761 {
4762   Unexpect aCatch(SALOME_SalomeException);
4763   GEOM::GEOM_Shape_var result;
4764   TopoDS_Shape tds ;
4765
4766   const TopoDS_Shape aShape = GetTopoShape(shape) ;
4767   if( aShape.IsNull() ) {
4768     THROW_SALOME_CORBA_EXCEPTION("Shape is null", SALOME::BAD_PARAM);
4769   }
4770
4771   BRepFilletAPI_MakeFillet fill(aShape);
4772
4773   try {
4774     /* case all */
4775     if(ListOfID.length() == 0) {
4776       TopExp_Explorer Exp ( aShape, TopAbs_EDGE );
4777       for (Exp; Exp.More(); Exp.Next()) {
4778         TopoDS_Edge E =TopoDS::Edge(Exp.Current());
4779         fill.Add(E);
4780       }
4781       for (int i = 1;i<=fill.NbContours();i++) {
4782         fill.SetRadius(radius,i,i);
4783       }
4784       tds = fill.Shape();
4785       
4786     } else {
4787
4788       /* case selection */               
4789       for ( unsigned int ind = 0; ind < ListOfID.length(); ind++ ) {
4790         TopoDS_Shape ss ;
4791         if( GetShapeFromIndex( aShape, (TopAbs_ShapeEnum)ShapeType, ListOfID[ind], ss ) ) {
4792           TopoDS_Edge E = TopoDS::Edge(ss) ;
4793           fill.Add( E );
4794         }
4795       }
4796       for (int i = 1;i<=fill.NbContours();i++) {
4797         fill.SetRadius(radius,i,i);
4798       }
4799       tds = fill.Shape();
4800     }
4801   }
4802   catch(Standard_Failure) {
4803     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeFillet", SALOME::BAD_PARAM);
4804   }
4805   
4806   if (tds.IsNull()) {
4807     THROW_SALOME_CORBA_EXCEPTION("Make Fillet aborted", SALOME::BAD_PARAM);
4808   } 
4809   result = CreateObject(tds);
4810   InsertInLabelOneArgument(aShape, shape, tds, result, myCurrentOCAFDoc) ;
4811
4812   return result ;  
4813 }
4814
4815
4816 //================================================================================
4817 // function : MakeChamfer
4818 // purpose  : Create a Chamfer topology
4819 //================================================================================
4820 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakeChamfer( GEOM::GEOM_Shape_ptr shape,
4821                                               CORBA::Double d1,
4822                                               CORBA::Double d2,
4823                                               CORBA::Short ShapeType,
4824                                               const GEOM::GEOM_Shape::ListOfSubShapeID& ListOfID ) 
4825   throw (SALOME::SALOME_Exception)
4826 {
4827   Unexpect aCatch(SALOME_SalomeException);
4828   GEOM::GEOM_Shape_var result;
4829   TopoDS_Shape tds ;
4830
4831   const TopoDS_Shape aShape = GetTopoShape(shape) ;
4832   if( aShape.IsNull() ) {
4833     THROW_SALOME_CORBA_EXCEPTION("Shape is null", SALOME::BAD_PARAM);
4834   }
4835   
4836   BRepFilletAPI_MakeChamfer MC(aShape);
4837
4838   try {
4839     /* case all */
4840     TopTools_IndexedDataMapOfShapeListOfShape M;
4841     TopExp::MapShapesAndAncestors(aShape,TopAbs_EDGE,TopAbs_FACE,M);
4842     if(ListOfID.length() == 0) {
4843       for (int i = 1;i<=M.Extent();i++) {
4844         TopoDS_Edge E = TopoDS::Edge(M.FindKey(i));
4845         TopoDS_Face F = TopoDS::Face(M.FindFromIndex(i).First());
4846         if (!BRepTools::IsReallyClosed(E, F) && !BRep_Tool::Degenerated(E))
4847           MC.Add(d1,d2,E,F);
4848       }
4849       tds = MC.Shape();
4850
4851     } else {
4852
4853       /* case selection */  
4854       for ( unsigned int ind = 0; ind < ListOfID.length(); ind++ ) {
4855         TopoDS_Shape ss ;
4856         if( GetShapeFromIndex( aShape, (TopAbs_ShapeEnum)ShapeType, ListOfID[ind], ss ) ) {
4857           TopoDS_Edge E = TopoDS::Edge( ss ) ;
4858           TopoDS_Face F = TopoDS::Face(M.FindFromKey(E).First());
4859           if (!BRepTools::IsReallyClosed(E, F) && !BRep_Tool::Degenerated(E))
4860             MC.Add(d1,d2,E,F);
4861         }
4862       }
4863       tds = MC.Shape();
4864     }
4865   }
4866   catch(Standard_Failure) {
4867     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeChamfer", SALOME::BAD_PARAM);
4868   }
4869   
4870   if (tds.IsNull()) {
4871     THROW_SALOME_CORBA_EXCEPTION("Make Chamfer aborted", SALOME::BAD_PARAM);
4872   } 
4873   result = CreateObject(tds);
4874   InsertInLabelOneArgument(aShape, shape, tds, result, myCurrentOCAFDoc) ;
4875
4876   return result ;
4877 }
4878
4879 //=================================================================================
4880 // function : CheckShape()
4881 // purpose  :
4882 //=================================================================================
4883 CORBA::Boolean GEOM_Gen_i::CheckShape(GEOM::GEOM_Shape_ptr shape) 
4884   throw (SALOME::SALOME_Exception)
4885 {
4886   Unexpect aCatch(SALOME_SalomeException);
4887   TopoDS_Shape S = GetTopoShape(shape) ;
4888   if( S.IsNull() ) {
4889     THROW_SALOME_CORBA_EXCEPTION("Shape is null", SALOME::BAD_PARAM);
4890   }
4891
4892   BRepCheck_Analyzer ana(S,false);
4893   if (ana.IsValid()) 
4894     return 1;
4895
4896   return 0;
4897 }
4898
4899 //=================================================================================
4900 // function : MakePlacedBox()
4901 // purpose  :
4902 //=================================================================================
4903 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakePlacedBox(CORBA::Double x1,  CORBA::Double y1,  CORBA::Double z1,
4904                                          CORBA::Double delta1, CORBA::Double delta2, CORBA::Double delta3)
4905   throw (SALOME::SALOME_Exception)
4906 {
4907   Unexpect aCatch(SALOME_SalomeException);
4908   GEOM::GEOM_Shape_var result ;
4909   TopoDS_Shape tds ;
4910
4911   CORBA::Double x2, y2, z2 ;
4912
4913   try {
4914     x2 = x1 + delta1 ;
4915     y2 = y1 + delta2 ;
4916     z2 = z1 + delta3 ;
4917     
4918     gp_Pnt P1(x1,y1,z1);
4919     gp_Pnt P2(x2,y2,z2);
4920     
4921     tds = BRepPrimAPI_MakeBox(P1,P2).Shape();
4922   }
4923   catch(Standard_Failure) {
4924     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakeBox", SALOME::BAD_PARAM);
4925   }
4926   
4927   if (tds.IsNull()) {
4928     THROW_SALOME_CORBA_EXCEPTION("Make Box aborted : null shape", SALOME::BAD_PARAM);
4929   } 
4930   
4931   result = CreateObject(tds);
4932   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
4933   result->ShapeId(entry) ;
4934
4935   return result;  
4936 }
4937
4938 //=================================================================================
4939 // function : MakePanel()
4940 // purpose  :
4941 //=================================================================================
4942 GEOM::GEOM_Shape_ptr GEOM_Gen_i::MakePanel(GEOM::GEOM_Shape_ptr shape,
4943                                      CORBA::Short directiontype,
4944                                      CORBA::Double delta)
4945   throw (SALOME::SALOME_Exception)
4946 {
4947   Unexpect aCatch(SALOME_SalomeException);
4948   GEOM::GEOM_Shape_var result ;
4949   TopoDS_Shape tds ;
4950   TopoDS_Shape aShape = GetTopoShape(shape) ;
4951   Bnd_Box B ;
4952   Standard_Real axmin,aymin,azmin,axmax,aymax,azmax ;
4953   GEOM::PointStruct pstruct1, pstruct2, pstruct3, pstruct4 ;
4954
4955   if(aShape.IsNull() ) {
4956     THROW_SALOME_CORBA_EXCEPTION("MakePanel aborted : null shape during operation", SALOME::BAD_PARAM);
4957   }  
4958
4959   try {
4960     BRepBndLib::Add(aShape,B);
4961     B.Enlarge(10.);
4962     B.Get(axmin,aymin,azmin,axmax,aymax,azmax);
4963     
4964     switch (directiontype)
4965       {
4966       case 1 :   /* X */
4967         pstruct1 = MakePointStruct( delta, aymin, azmin ) ;
4968         pstruct2 = MakePointStruct( delta, aymin, azmax ) ;
4969         pstruct3 = MakePointStruct( delta, aymax, azmax ) ;
4970         pstruct4 = MakePointStruct( delta, aymax, azmin ) ;
4971         break ;
4972       case 2 :   /* Y */
4973         pstruct1 = MakePointStruct( axmin, delta, azmin ) ;
4974         pstruct2 = MakePointStruct( axmin, delta, azmax ) ;
4975         pstruct3 = MakePointStruct( axmax, delta, azmax ) ;
4976         pstruct4 = MakePointStruct( axmax, delta, azmin ) ;
4977         break ;
4978       case 3 :   /* Z */
4979         pstruct1 = MakePointStruct( axmin, aymin, delta ) ;
4980         pstruct2 = MakePointStruct( axmin, aymax, delta ) ;
4981         pstruct3 = MakePointStruct( axmax, aymax, delta ) ;
4982         pstruct4 = MakePointStruct( axmax, aymin, delta ) ;
4983         break ;
4984       default :
4985         return result ;
4986       }
4987     
4988     GEOM::GEOM_Shape_ptr Edge1 = MakeEdge(pstruct1, pstruct2);
4989     GEOM::GEOM_Shape_ptr Edge2 = MakeEdge(pstruct2, pstruct3);
4990     GEOM::GEOM_Shape_ptr Edge3 = MakeEdge(pstruct3, pstruct4);
4991     GEOM::GEOM_Shape_ptr Edge4 = MakeEdge(pstruct4, pstruct1);
4992     
4993     GEOM::GEOM_Gen::ListOfIOR_var aList = new GEOM::GEOM_Gen::ListOfIOR;
4994     aList->length(4);
4995     aList[0]=strdup(Edge1->Name());
4996     aList[1]=strdup(Edge2->Name());
4997     aList[2]=strdup(Edge3->Name());
4998     aList[3]=strdup(Edge4->Name());
4999     
5000     GEOM::GEOM_Shape_ptr aWire = MakeWire( aList );
5001     GEOM::GEOM_Shape_ptr aFace = MakeFace( aWire, true ) ;
5002     tds = GetTopoShape(aFace);
5003     
5004   }
5005   catch(Standard_Failure) {
5006     THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::MakePanel", SALOME::BAD_PARAM);
5007   }
5008   
5009   if (tds.IsNull()) {
5010     THROW_SALOME_CORBA_EXCEPTION("Make PanelsPartition aborted : null shape", SALOME::BAD_PARAM);
5011   } 
5012   
5013   result = CreateObject(tds); 
5014   const char *entry = InsertInLabel(tds, result->Name(), myCurrentOCAFDoc) ;
5015   result->ShapeId(entry) ;
5016   
5017   return result;
5018 }
5019
5020
5021 void GEOM_Gen_i::ExportIGES(const char* filename,GEOM::GEOM_Shape_ptr theShape) 
5022   throw (SALOME::SALOME_Exception)
5023 {
5024   Unexpect aCatch(SALOME_SalomeException);
5025   if (theShape->_is_nil()) 
5026     {
5027       THROW_SALOME_CORBA_EXCEPTION("Export IGES aborted", SALOME::BAD_PARAM);
5028     } 
5029   TopoDS_Shape tds = GetTopoShape(theShape);
5030   if (tds.IsNull()) 
5031     {
5032       THROW_SALOME_CORBA_EXCEPTION("Export IGES aborted", SALOME::BAD_PARAM);
5033     } 
5034   try 
5035     {
5036       //VRV: OCC 4.0 migration
5037       IGESControl_Controller::Init();
5038       IGESControl_Writer ICW (Interface_Static::CVal("XSTEP.iges.unit"),
5039                                    Interface_Static::IVal("XSTEP.iges.writebrep.mode"));
5040       //VRV: OCC 4.0 migration
5041         
5042       ICW.AddShape (tds);
5043       ICW.ComputeModel();
5044       char * aname = strdup(filename);
5045       Standard_Boolean result = ICW.Write( aname );
5046       free(aname);
5047     }
5048   catch(Standard_Failure) 
5049     {
5050       THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ExportIGES", SALOME::BAD_PARAM);
5051     }
5052 }
5053
5054 void GEOM_Gen_i::ExportBREP(const char* filename,GEOM::GEOM_Shape_ptr theShape)
5055   throw (SALOME::SALOME_Exception)
5056 {
5057   Unexpect aCatch(SALOME_SalomeException);
5058   if (theShape->_is_nil()) 
5059     {
5060       THROW_SALOME_CORBA_EXCEPTION("Export BRep aborted", SALOME::BAD_PARAM);
5061     } 
5062   TopoDS_Shape tds = GetTopoShape(theShape);
5063   if (tds.IsNull()) 
5064     {
5065       THROW_SALOME_CORBA_EXCEPTION("Export BRep aborted", SALOME::BAD_PARAM);
5066     } 
5067   try 
5068     {
5069       char * aname = strdup(filename);
5070       Standard_Boolean result = BRepTools::Write(tds,aname);
5071       free(aname);
5072     }
5073   catch(Standard_Failure) 
5074     {
5075       THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ExportBREP", SALOME::BAD_PARAM);
5076     }
5077 }
5078
5079 void GEOM_Gen_i::ExportSTEP(const char* filename,GEOM::GEOM_Shape_ptr theShape) 
5080   throw (SALOME::SALOME_Exception)
5081 {
5082   Unexpect aCatch(SALOME_SalomeException);
5083   if (theShape->_is_nil()) 
5084     {
5085       THROW_SALOME_CORBA_EXCEPTION("Export STEP aborted", SALOME::BAD_PARAM);
5086     } 
5087   TopoDS_Shape tds = GetTopoShape(theShape);
5088   if (tds.IsNull()) 
5089     {
5090       THROW_SALOME_CORBA_EXCEPTION("Export STEP aborted", SALOME::BAD_PARAM);
5091     } 
5092   try 
5093     {
5094       IFSelect_ReturnStatus status ;
5095       //VRV: OCC 4.0 migration
5096       STEPControl_Writer aWriter;
5097       status = aWriter.Transfer( tds, STEPControl_ManifoldSolidBrep ) ;
5098       //VRV: OCC 4.0 migration
5099       if ( status == IFSelect_RetDone ) 
5100         {
5101           char * aname = strdup(filename);
5102           status = aWriter.Write( aname ) ;
5103           free(aname);
5104         }
5105     }
5106   catch(Standard_Failure) 
5107     {
5108       THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ExportBREP", SALOME::BAD_PARAM);
5109     }
5110 }
5111
5112
5113 //=====================================================================================
5114 // EXPORTED METHODS
5115 //=====================================================================================
5116 extern "C"
5117 {
5118   PortableServer::ObjectId * GEOMEngine_factory(CORBA::ORB_ptr orb,
5119                                                 PortableServer::POA_ptr poa, 
5120                                                 PortableServer::ObjectId * contId,
5121                                                 const char *instanceName, 
5122                                                 const char * interfaceName)
5123   {
5124    GEOM_Gen_i * myGEOM_Gen_i = new GEOM_Gen_i(orb, poa, contId, instanceName, interfaceName);
5125    myGEOM_Gen_i->register_name("/myGEOM_Gen"); // NRI : 11/07/2002 : Add for Supervision example 
5126    return myGEOM_Gen_i->getId() ;
5127   }
5128 }
5129