Salome HOME
GDD: temporaly remove sphynx doc generation
[modules/geom.git] / src / STEPImport / STEPImport.cxx
1 // Copyright (C) 2007-2011  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  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.salome-platform.org/ or email : webmaster.salome@opencascade.com
21
22 //  File:        STEPImport.cxx
23 //  Created:     Wed May 19 14:41:10 2004
24 //  Author:      Pavel TELKOV
25
26 #include "utilities.h"
27
28 #include <Basics_Utils.hxx>
29
30 #include <Basics_OCCTVersion.hxx>
31
32 #include <BRep_Builder.hxx>
33
34 #include <IFSelect_ReturnStatus.hxx>
35
36 #include <STEPControl_Reader.hxx>
37 #include <StepBasic_ProductDefinition.hxx>
38 #include <StepBasic_ProductDefinitionFormation.hxx>
39 #include <StepBasic_Product.hxx>
40 #include <Interface_InterfaceModel.hxx>
41 #include <XSControl_TransferReader.hxx>
42 #include <XSControl_WorkSession.hxx>
43 #include <StepShape_TopologicalRepresentationItem.hxx>
44
45 #include <Transfer_Binder.hxx>
46 #include <TNaming_Builder.hxx>
47 #include <TDataStd_Name.hxx>
48 #include <Transfer_TransientProcess.hxx>
49 #include <TransferBRep.hxx>
50
51 #include <TCollection_AsciiString.hxx>
52 #include <TopoDS_Compound.hxx>
53 #include <TopoDS_Shape.hxx>
54 #include <TDF_Label.hxx>
55 #include <TDF_Tool.hxx>
56 #include <Interface_Static.hxx>
57
58 #include <TopTools_IndexedMapOfShape.hxx>
59 #include <TopExp.hxx>
60 #include <TopoDS_Iterator.hxx>
61 #include <BRepTools.hxx>
62
63 #include <Standard_Failure.hxx>
64 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
65
66 #ifdef WNT
67  #if defined STEPIMPORT_EXPORTS || defined STEPImport_EXPORTS
68   #if defined WIN32
69    #define STEPIMPORT_EXPORT __declspec( dllexport )
70   #else
71    #define STEPIMPORT_EXPORT
72   #endif
73  #else
74   #if defined WIN32
75    #define STEPIMPORT_EXPORT __declspec( dllimport )
76   #else
77    #define STEPIMPORT_EXPORT
78   #endif
79  #endif
80 #else
81  #define STEPIMPORT_EXPORT
82 #endif
83
84 //=============================================================================
85 /*!
86  *  Import()
87  */
88 //=============================================================================
89
90 extern "C"
91 {
92   STEPIMPORT_EXPORT
93   TopoDS_Shape Import (const TCollection_AsciiString& theFileName,
94                        const TCollection_AsciiString& /*theFormatName*/,
95                        TCollection_AsciiString&       theError,
96                        const TDF_Label&               theShapeLabel)
97   {
98     MESSAGE("Import STEP model from file " << theFileName.ToCString());
99     // Set "C" numeric locale to save numbers correctly
100     Kernel_Utils::Localizer loc;
101     TopoDS_Shape aResShape;
102     //VRV: OCC 4.0 migration
103     STEPControl_Reader aReader;
104     //VSR: 16/09/09: Convert to METERS
105     Interface_Static::SetCVal("xstep.cascade.unit","M");
106     Interface_Static::SetIVal("read.step.ideas", 1);
107     Interface_Static::SetIVal("read.step.nonmanifold", 1);
108     //VRV: OCC 4.0 migration
109     TopoDS_Compound compound;
110     BRep_Builder B;
111     B.MakeCompound(compound);
112     try {
113 #if OCC_VERSION_LARGE > 0x06010000
114       OCC_CATCH_SIGNALS;
115 #endif
116       IFSelect_ReturnStatus status = aReader.ReadFile(theFileName.ToCString());
117
118       if (status == IFSelect_RetDone) {
119         Standard_Boolean failsonly = Standard_False;
120         aReader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity);
121         /* Root transfers */
122         Standard_Integer nbr = aReader.NbRootsForTransfer();
123         aReader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity);
124
125         for (Standard_Integer n = 1; n <= nbr; n++) {
126           Standard_Boolean ok = aReader.TransferRoot(n);
127           /* Collecting resulting entities */
128           Standard_Integer nbs = aReader.NbShapes();
129           if (!ok || nbs == 0)
130           {
131             // THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ImportStep", SALOME::BAD_PARAM);
132             continue; // skip empty root
133           }
134           /* For a single entity */
135           else if (nbr == 1 && nbs == 1) {
136             aResShape = aReader.Shape(1);
137             // ATTENTION: this is a workaround for mantis issue 0020442 remark 0010776
138             // It should be removed after patching OCCT for bug OCC22436
139             // (fix for OCCT is expected in service pack next to OCCT6.3sp12)
140             if (aResShape.ShapeType() == TopAbs_COMPOUND) {
141               int nbSub1 = 0;
142               TopoDS_Shape currShape;
143               TopoDS_Iterator It (aResShape, Standard_True, Standard_True);
144               for (; It.More(); It.Next()) {
145                 nbSub1++;
146                 currShape = It.Value();
147               }
148               if (nbSub1 == 1)
149                 aResShape = currShape;
150             }
151             // END workaround
152             break;
153           }
154
155           for (Standard_Integer i = 1; i <= nbs; i++) {
156             TopoDS_Shape aShape = aReader.Shape(i);
157             if (aShape.IsNull()) {
158               // THROW_SALOME_CORBA_EXCEPTION("Null shape in GEOM_Gen_i::ImportStep", SALOME::BAD_PARAM) ;
159               //return aResShape;
160               continue;
161             }
162             else {
163               B.Add(compound, aShape);
164             }
165           }
166         }
167         if (aResShape.IsNull())
168           aResShape = compound;
169
170         // BEGIN: Store names of sub-shapes from file
171         TopTools_IndexedMapOfShape anIndices;
172         TopExp::MapShapes(aResShape, anIndices);
173
174         Handle(Interface_InterfaceModel) Model = aReader.WS()->Model();
175         Handle(XSControl_TransferReader) TR = aReader.WS()->TransferReader();
176         if (!TR.IsNull()) {
177           Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
178           Handle(Standard_Type) tPD  = STANDARD_TYPE(StepBasic_ProductDefinition);
179           Handle(Standard_Type) tShape  = STANDARD_TYPE(StepShape_TopologicalRepresentationItem);
180
181           Standard_Integer nb = Model->NbEntities();
182           for (Standard_Integer ie = 1; ie <= nb; ie++) {
183             Handle(Standard_Transient) enti = Model->Value(ie);
184             Handle(TCollection_HAsciiString) aName;
185             if ( enti->IsKind( tShape ))
186             {
187               aName = Handle(StepRepr_RepresentationItem)::DownCast(enti)->Name();
188             }
189             else if (enti->DynamicType() == tPD)
190             {
191               Handle(StepBasic_ProductDefinition) PD =
192                 Handle(StepBasic_ProductDefinition)::DownCast(enti);
193               if (PD.IsNull()) continue;
194
195               Handle(StepBasic_Product) Prod = PD->Formation()->OfProduct();
196               aName = Prod->Name();
197             }
198             else
199             {
200               continue;
201             }
202             if ( aName->UsefullLength() < 1 )
203               continue;
204             // skip 'N0NE' name
205             if ( aName->UsefullLength() == 4 &&
206                  toupper (aName->Value(1)) == 'N' &&
207                  toupper (aName->Value(2)) == 'O' &&
208                  toupper (aName->Value(3)) == 'N' &&
209                  toupper (aName->Value(4)) == 'E')
210               continue;
211
212             // special check to pass names like "Open CASCADE STEP translator 6.3 1"
213             TCollection_AsciiString aSkipName ("Open CASCADE STEP translator");
214             if (aName->Length() >= aSkipName.Length()) {
215               if (aName->String().SubString(1, aSkipName.Length()).IsEqual(aSkipName))
216                 continue;
217             }
218             TCollection_ExtendedString aNameExt (aName->ToCString());
219
220             // find target shape
221             Handle(Transfer_Binder) binder = TP->Find(enti);
222             if (binder.IsNull()) continue;
223             TopoDS_Shape S = TransferBRep::ShapeResult(binder);
224             if (S.IsNull()) continue;
225
226             // as PRODUCT can be included in the main shape
227             // several times, we look here for all iclusions.
228             Standard_Integer isub, nbSubs = anIndices.Extent();
229             for (isub = 1; isub <= nbSubs; isub++)
230             {
231               TopoDS_Shape aSub = anIndices.FindKey(isub);
232               if (aSub.IsPartner(S)) {
233                 // create label and set shape
234                 TDF_Label L;
235                 TDF_TagSource aTag;
236                 L = aTag.NewChild(theShapeLabel);
237                 TNaming_Builder tnBuild (L);
238                 //tnBuild.Generated(S);
239                 tnBuild.Generated(aSub);
240
241                 // set a name
242                 TDataStd_Name::Set(L, aNameExt);
243               }
244             }
245           }
246         }
247         // END: Store names
248       }
249       else {
250 //        switch (status) {
251 //        case IFSelect_RetVoid:
252 //          theError = "Nothing created or No data to process";
253 //          break;
254 //        case IFSelect_RetError:
255 //          theError = "Error in command or input data";
256 //          break;
257 //        case IFSelect_RetFail:
258 //          theError = "Execution was run, but has failed";
259 //          break;
260 //        case IFSelect_RetStop:
261 //          theError = "Execution has been stopped. Quite possible, an exception was raised";
262 //          break;
263 //        default:
264 //          break;
265 //        }
266         theError = "Wrong format of the imported file. Can't import file.";
267         aResShape.Nullify();
268       }
269     }
270     catch (Standard_Failure) {
271       Handle(Standard_Failure) aFail = Standard_Failure::Caught();
272       theError = aFail->GetMessageString();
273       aResShape.Nullify();
274     }
275     // Return previous locale
276     return aResShape;
277   }
278 }