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