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