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