]> SALOME platform Git repositories - modules/geom.git/blob - src/STEPImport/STEPImport.cxx
Salome HOME
9b5f1e9966faf2f22a21c312d1a6489de27f751e
[modules/geom.git] / src / STEPImport / STEPImport.cxx
1 // Copyright (C) 2007-2012  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 #include <Basics_OCCTVersion.hxx>
30
31 #include <TDF_ChildIDIterator.hxx>
32 #include <TDF_Label.hxx>
33 #include <TDataStd_Name.hxx>
34 #include <TNaming_Builder.hxx>
35 #include <TNaming_NamedShape.hxx>
36
37 #include <IFSelect_ReturnStatus.hxx>
38 #include <Interface_InterfaceModel.hxx>
39 #include <Interface_Static.hxx>
40 #include <STEPControl_Reader.hxx>
41 #include <StepBasic_Product.hxx>
42 #include <StepBasic_ProductDefinition.hxx>
43 #include <StepBasic_ProductDefinitionFormation.hxx>
44 #include <StepGeom_GeometricRepresentationItem.hxx>
45 #include <StepShape_TopologicalRepresentationItem.hxx>
46 #include <TransferBRep.hxx>
47 #include <Transfer_Binder.hxx>
48 #include <Transfer_TransientProcess.hxx>
49 #include <XSControl_TransferReader.hxx>
50 #include <XSControl_WorkSession.hxx>
51
52 #include <BRep_Builder.hxx>
53
54 #include <TopExp.hxx>
55 #include <TopExp_Explorer.hxx>
56 #include <TopTools_IndexedMapOfShape.hxx>
57 #include <TopoDS_Compound.hxx>
58 #include <TopoDS_Iterator.hxx>
59 #include <TopoDS_Shape.hxx>
60
61 #include <TCollection_AsciiString.hxx>
62 #include <TColStd_SequenceOfAsciiString.hxx>
63
64 #include <Standard_Failure.hxx>
65 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
66
67 #ifdef WNT
68  #if defined STEPIMPORT_EXPORTS || defined STEPImport_EXPORTS
69   #if defined WIN32
70    #define STEPIMPORT_EXPORT __declspec( dllexport )
71   #else
72    #define STEPIMPORT_EXPORT
73   #endif
74  #else
75   #if defined WIN32
76    #define STEPIMPORT_EXPORT __declspec( dllimport )
77   #else
78    #define STEPIMPORT_EXPORT
79   #endif
80  #endif
81 #else
82  #define STEPIMPORT_EXPORT
83 #endif
84
85 //=============================================================================
86 /*!
87  *  Import()
88  */
89 //=============================================================================
90
91 extern "C"
92 {
93   STEPIMPORT_EXPORT
94   Handle(TCollection_HAsciiString) GetValue (const TCollection_AsciiString& theFileName,
95                                              const TCollection_AsciiString& theParameterName,
96                                              TCollection_AsciiString&       theError)
97   {
98     Handle(TCollection_HAsciiString) aValue;
99
100     if (theParameterName != "LEN_UNITS") {
101       theError = theParameterName + " parameter reading is not supported by STEP plugin";
102       return aValue;
103     }
104
105     // Set "C" numeric locale to save numbers correctly
106     Kernel_Utils::Localizer loc;
107
108     STEPControl_Reader aReader;
109
110     Interface_Static::SetCVal("xstep.cascade.unit","M");
111     Interface_Static::SetIVal("read.step.ideas", 1);
112     Interface_Static::SetIVal("read.step.nonmanifold", 1);
113
114     try {
115 #if OCC_VERSION_LARGE > 0x06010000
116       OCC_CATCH_SIGNALS;
117 #endif
118       IFSelect_ReturnStatus status = aReader.ReadFile(theFileName.ToCString());
119       if (status == IFSelect_RetDone) {
120         TColStd_SequenceOfAsciiString anUnitLengthNames;
121         TColStd_SequenceOfAsciiString anUnitAngleNames;
122         TColStd_SequenceOfAsciiString anUnitSolidAngleNames;
123         aReader.FileUnits(anUnitLengthNames, anUnitAngleNames, anUnitSolidAngleNames);
124         if (anUnitLengthNames.Length() > 0) {
125           TCollection_AsciiString aLenUnits = anUnitLengthNames.First();
126           if (aLenUnits == "millimetre")
127             aValue = new TCollection_HAsciiString ("MM");
128           else if (aLenUnits == "centimetre")
129             aValue = new TCollection_HAsciiString ("CM");
130           else if (aLenUnits == "metre")
131             aValue = new TCollection_HAsciiString ("M");
132           else if (aLenUnits == "INCH")
133             aValue = new TCollection_HAsciiString ("INCH");
134           // TODO
135           //else if (aLenUnits == "")
136           //  aValue = new TCollection_HAsciiString ("");
137
138           // tmp begin
139           //std::cout << "$$$ --- " << anUnitLengthNames.First();
140           //for (int ii = 2; ii <= anUnitLengthNames.Length(); ii++)
141           //  std::cout << ", " << anUnitLengthNames.Value(ii);
142           //std::cout << std::endl;
143           // tmp end
144         }
145       }
146       else {
147         theError = theFileName + " reading failed";
148       }
149     }
150     catch (Standard_Failure) {
151       Handle(Standard_Failure) aFail = Standard_Failure::Caught();
152       theError = aFail->GetMessageString();
153     }
154
155     return aValue;
156   }
157
158   STEPIMPORT_EXPORT
159   TopoDS_Shape Import (const TCollection_AsciiString& theFileName,
160                        const TCollection_AsciiString& theFormatName,
161                        TCollection_AsciiString&       theError,
162                        const TDF_Label&               theShapeLabel)
163   {
164     TopoDS_Shape aResShape;
165
166     // Set "C" numeric locale to save numbers correctly
167     Kernel_Utils::Localizer loc;
168
169     STEPControl_Reader aReader;
170
171     //VSR: 16/09/09: Convert to METERS
172     Interface_Static::SetCVal("xstep.cascade.unit","M");
173     Interface_Static::SetIVal("read.step.ideas", 1);
174     Interface_Static::SetIVal("read.step.nonmanifold", 1);
175
176     BRep_Builder B;
177     TopoDS_Compound compound;
178     B.MakeCompound(compound);
179
180     try {
181       OCC_CATCH_SIGNALS;
182
183       IFSelect_ReturnStatus status = aReader.ReadFile(theFileName.ToCString());
184
185       if (status == IFSelect_RetDone) {
186
187         // Regard or not the model units
188         if (theFormatName == "STEP_SCALE") {
189           // set UnitFlag to units from file
190           TColStd_SequenceOfAsciiString anUnitLengthNames;
191           TColStd_SequenceOfAsciiString anUnitAngleNames;
192           TColStd_SequenceOfAsciiString anUnitSolidAngleNames;
193           aReader.FileUnits(anUnitLengthNames, anUnitAngleNames, anUnitSolidAngleNames);
194           if (anUnitLengthNames.Length() > 0) {
195             TCollection_AsciiString aLenUnits = anUnitLengthNames.First();
196             if (aLenUnits == "millimetre")
197               Interface_Static::SetCVal("xstep.cascade.unit", "MM");
198             else if (aLenUnits == "centimetre")
199               Interface_Static::SetCVal("xstep.cascade.unit", "CM");
200             else if (aLenUnits == "metre")
201               Interface_Static::SetCVal("xstep.cascade.unit", "M");
202             else if (aLenUnits == "INCH")
203               Interface_Static::SetCVal("xstep.cascade.unit", "INCH");
204             else {
205               theError = "The file contains not supported units.";
206               return aResShape;
207             }
208             // TODO
209             //else if (aLenUnits == "")
210             //  Interface_Static::SetCVal("xstep.cascade.unit", "");
211           }
212         }
213         else {
214           //cout<<"need re-scale a model"<<endl;
215           // set UnitFlag to 'meter'
216           Interface_Static::SetCVal("xstep.cascade.unit","M");
217         }
218
219         Standard_Boolean failsonly = Standard_False;
220         aReader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity);
221
222         /* Root transfers */
223         Standard_Integer nbr = aReader.NbRootsForTransfer();
224         aReader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity);
225
226         for (Standard_Integer n = 1; n <= nbr; n++) {
227           Standard_Boolean ok = aReader.TransferRoot(n);
228           /* Collecting resulting entities */
229           Standard_Integer nbs = aReader.NbShapes();
230           if (!ok || nbs == 0)
231           {
232             // THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ImportStep", SALOME::BAD_PARAM);
233             continue; // skip empty root
234           }
235           /* For a single entity */
236           else if (nbr == 1 && nbs == 1) {
237             aResShape = aReader.Shape(1);
238             // ATTENTION: this is a workaround for mantis issue 0020442 remark 0010776
239             // It should be removed after patching OCCT for bug OCC22436
240             // (fix for OCCT is expected in service pack next to OCCT6.3sp12)
241             if (aResShape.ShapeType() == TopAbs_COMPOUND) {
242               int nbSub1 = 0;
243               TopoDS_Shape currShape;
244               TopoDS_Iterator It (aResShape, Standard_True, Standard_True);
245               for (; It.More(); It.Next()) {
246                 nbSub1++;
247                 currShape = It.Value();
248               }
249               if (nbSub1 == 1)
250                 aResShape = currShape;
251             }
252             // END workaround
253             break;
254           }
255
256           for (Standard_Integer i = 1; i <= nbs; i++) {
257             TopoDS_Shape aShape = aReader.Shape(i);
258             if (aShape.IsNull()) {
259               // THROW_SALOME_CORBA_EXCEPTION("Null shape in GEOM_Gen_i::ImportStep", SALOME::BAD_PARAM) ;
260               //return aResShape;
261               continue;
262             }
263             else {
264               B.Add(compound, aShape);
265             }
266           }
267         }
268         if (aResShape.IsNull())
269           aResShape = compound;
270
271         // Check if any BRep entity has been read, there must be at least a vertex
272         if ( !TopExp_Explorer( aResShape, TopAbs_VERTEX ).More() )
273         {
274           theError = "No geometrical data in the imported file.";
275           return TopoDS_Shape();
276         }
277
278         // BEGIN: Store names of sub-shapes from file
279         TopTools_IndexedMapOfShape anIndices;
280         TopExp::MapShapes(aResShape, anIndices);
281
282         Handle(Interface_InterfaceModel) Model = aReader.WS()->Model();
283         Handle(XSControl_TransferReader) TR = aReader.WS()->TransferReader();
284         if (!TR.IsNull()) {
285           Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
286           Handle(Standard_Type) tPD  = STANDARD_TYPE(StepBasic_ProductDefinition);
287           Handle(Standard_Type) tShape  = STANDARD_TYPE(StepShape_TopologicalRepresentationItem);
288           Handle(Standard_Type) tGeom  = STANDARD_TYPE(StepGeom_GeometricRepresentationItem);
289
290           Standard_Integer nb = Model->NbEntities();
291           for (Standard_Integer ie = 1; ie <= nb; ie++) {
292             Handle(Standard_Transient) enti = Model->Value(ie);
293             Handle(TCollection_HAsciiString) aName;
294             if ( enti->IsKind( tShape ) || enti->IsKind(tGeom))
295             {
296               aName = Handle(StepRepr_RepresentationItem)::DownCast(enti)->Name();
297             }
298             else if (enti->DynamicType() == tPD)
299             {
300               Handle(StepBasic_ProductDefinition) PD =
301                 Handle(StepBasic_ProductDefinition)::DownCast(enti);
302               if (PD.IsNull()) continue;
303
304               Handle(StepBasic_Product) Prod = PD->Formation()->OfProduct();
305               aName = Prod->Name();
306             }
307             else
308             {
309               continue;
310             }
311             if ( aName->UsefullLength() < 1 )
312               continue;
313             // skip 'N0NE' name
314             if ( aName->UsefullLength() == 4 &&
315                  toupper (aName->Value(1)) == 'N' &&
316                  toupper (aName->Value(2)) == 'O' &&
317                  toupper (aName->Value(3)) == 'N' &&
318                  toupper (aName->Value(4)) == 'E')
319               continue;
320
321             // special check to pass names like "Open CASCADE STEP translator 6.3 1"
322             TCollection_AsciiString aSkipName ("Open CASCADE STEP translator");
323             if (aName->Length() >= aSkipName.Length()) {
324               if (aName->String().SubString(1, aSkipName.Length()).IsEqual(aSkipName))
325                 continue;
326             }
327             TCollection_ExtendedString aNameExt (aName->ToCString());
328
329             // find target shape
330             Handle(Transfer_Binder) binder = TP->Find(enti);
331             if (binder.IsNull()) continue;
332             TopoDS_Shape S = TransferBRep::ShapeResult(binder);
333             if (S.IsNull()) continue;
334
335             // as PRODUCT can be included in the main shape
336             // several times, we look here for all iclusions.
337             Standard_Integer isub, nbSubs = anIndices.Extent();
338             for (isub = 1; isub <= nbSubs; isub++)
339             {
340               TopoDS_Shape aSub = anIndices.FindKey(isub);
341               if (aSub.IsPartner(S)) {
342                 TDF_Label L;
343                 if (enti->IsKind(tGeom)) {
344                   // check all named shapes using iterator
345                   TDF_ChildIDIterator anIt (theShapeLabel, TDataStd_Name::GetID(), Standard_True);
346                   for (; anIt.More(); anIt.Next()) {
347                     Handle(TDataStd_Name) nameAttr =
348                       Handle(TDataStd_Name)::DownCast(anIt.Value());
349                     if (nameAttr.IsNull()) continue;
350                     TDF_Label Lab = nameAttr->Label();
351                     Handle(TNaming_NamedShape) shAttr; 
352                     if (Lab.FindAttribute(TNaming_NamedShape::GetID(), shAttr) && shAttr->Get().IsEqual(aSub))
353                       L = Lab;
354                   }
355                 }
356                 // create label and set shape
357                 if (L.IsNull())
358                 {
359                   TDF_TagSource aTag;
360                   L = aTag.NewChild(theShapeLabel);
361                   TNaming_Builder tnBuild (L);
362                   //tnBuild.Generated(S);
363                   tnBuild.Generated(aSub);
364                 }
365                 // set a name
366                 TDataStd_Name::Set(L, aNameExt);
367               }
368             }
369           }
370         }
371         // END: Store names
372       }
373       else {
374 //        switch (status) {
375 //        case IFSelect_RetVoid:
376 //          theError = "Nothing created or No data to process";
377 //          break;
378 //        case IFSelect_RetError:
379 //          theError = "Error in command or input data";
380 //          break;
381 //        case IFSelect_RetFail:
382 //          theError = "Execution was run, but has failed";
383 //          break;
384 //        case IFSelect_RetStop:
385 //          theError = "Execution has been stopped. Quite possible, an exception was raised";
386 //          break;
387 //        default:
388 //          break;
389 //        }
390         theError = "Wrong format of the imported file. Can't import file.";
391         aResShape.Nullify();
392       }
393     }
394     catch (Standard_Failure) {
395       Handle(Standard_Failure) aFail = Standard_Failure::Caught();
396       theError = aFail->GetMessageString();
397       aResShape.Nullify();
398     }
399     // Return previous locale
400     return aResShape;
401   }
402 }