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