FreeCAD

Форк
0
/
ImportStep.cpp 
229 строк · 9.2 Кб
1
/***************************************************************************
2
 *   Copyright (c) 2008 Jürgen Riegel <juergen.riegel@web.de>              *
3
 *                                                                         *
4
 *   This file is part of the FreeCAD CAx development system.              *
5
 *                                                                         *
6
 *   This library is free software; you can redistribute it and/or         *
7
 *   modify it under the terms of the GNU Library General Public           *
8
 *   License as published by the Free Software Foundation; either          *
9
 *   version 2 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         *
14
 *   GNU Library General Public License for more details.                  *
15
 *                                                                         *
16
 *   You should have received a copy of the GNU Library General Public     *
17
 *   License along with this library; see the file COPYING.LIB. If not,    *
18
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
19
 *   Suite 330, Boston, MA  02111-1307, USA                                *
20
 *                                                                         *
21
 ***************************************************************************/
22

23
#include "PreCompiled.h"
24
#ifndef _PreComp_
25
# include <fcntl.h>
26
# include <sstream>
27
# include <Quantity_Color.hxx>
28
# include <BRep_Builder.hxx>
29
# include <STEPControl_Reader.hxx>
30
# include <StepData_StepModel.hxx>
31
# include <TopoDS.hxx>
32
# include <TopoDS_Shape.hxx>
33
# include <TopoDS_Shell.hxx>
34
# include <TopoDS_Solid.hxx>
35
# include <TopoDS_Compound.hxx>
36
# include <TopExp_Explorer.hxx>
37
# include <Standard_Version.hxx>
38
# include <Transfer_TransientProcess.hxx>
39
# include <XSControl_TransferReader.hxx>
40
# include <XSControl_WorkSession.hxx>
41
#endif
42

43
#include <StepElement_AnalysisItemWithinRepresentation.hxx>
44
#include <StepVisual_AnnotationCurveOccurrence.hxx>
45

46
#include <App/Document.h>
47
#include <Base/Console.h>
48

49
#include "ImportStep.h"
50
#include "encodeFilename.h"
51
#include "ShapeMapHasher.h"
52
#include "PartFeature.h"
53
#include "ProgressIndicator.h"
54

55

56
namespace Part {
57
bool ReadColors (const Handle(XSControl_WorkSession) &WS, std::map<int, Quantity_Color>& hash_col);
58
bool ReadNames (const Handle(XSControl_WorkSession) &WS);
59
}
60

61
int Part::ImportStepParts(App::Document *pcDoc, const char* Name)
62
{
63
    // Use this to force to link against TKSTEPBase, TKSTEPAttr and TKStep209
64
    // in order to make RUNPATH working on Linux
65
    StepElement_AnalysisItemWithinRepresentation stepElement;
66
    StepVisual_AnnotationCurveOccurrence stepVis;
67

68
    STEPControl_Reader aReader;
69
    TopoDS_Shape aShape;
70
    Base::FileInfo fi(Name);
71

72
    if (!fi.exists()) {
73
        std::stringstream str;
74
        str << "File '" << Name << "' does not exist!";
75
        throw Base::FileException(str.str().c_str());
76
    }
77
    std::string encodednamestr = encodeFilename(std::string(Name));
78
    const char * encodedname = encodednamestr.c_str();
79

80
    if (aReader.ReadFile((Standard_CString)encodedname) !=
81
            IFSelect_RetDone) {
82
        throw Base::FileException("Cannot open STEP file");
83
    }
84

85
#if OCC_VERSION_HEX < 0x070500
86
    Handle(Message_ProgressIndicator) pi = new ProgressIndicator(100);
87
    aReader.WS()->MapReader()->SetProgress(pi);
88
    pi->NewScope(100, "Reading STEP file...");
89
    pi->Show();
90
#endif
91

92
    // Root transfers
93
    Standard_Integer nbr = aReader.NbRootsForTransfer();
94
    //aReader.PrintCheckTransfer (failsonly, IFSelect_ItemsByEntity);
95
    for (Standard_Integer n = 1; n<= nbr; n++) {
96
        Base::Console().Log("STEP: Transferring Root %d\n",n);
97
        aReader.TransferRoot(n);
98
    }
99
#if OCC_VERSION_HEX < 0x070500
100
    pi->EndScope();
101
#endif
102

103
    // Collecting resulting entities
104
    Standard_Integer nbs = aReader.NbShapes();
105
    if (nbs == 0) {
106
        throw Base::FileException("No shapes found in file ");
107
    }
108
    else {
109
        //Handle(StepData_StepModel) Model = aReader.StepModel();
110
        //Handle(XSControl_WorkSession) ws = aReader.WS();
111
        //Handle(XSControl_TransferReader) tr = ws->TransferReader();
112

113
        std::map<int, Quantity_Color> hash_col;
114
        //ReadColors(aReader.WS(), hash_col);
115
        //ReadNames(aReader.WS());
116

117
        for (Standard_Integer i=1; i<=nbs; i++) {
118
            Base::Console().Log("STEP:   Transferring Shape %d\n",i);
119
            aShape = aReader.Shape(i);
120

121
            // load each solid as an own object
122
            TopExp_Explorer ex;
123
            for (ex.Init(aShape, TopAbs_SOLID); ex.More(); ex.Next())
124
            {
125
                // get the shape
126
                const TopoDS_Solid& aSolid = TopoDS::Solid(ex.Current());
127

128
                std::string name = fi.fileNamePure();
129
                //Handle(Standard_Transient) ent = tr->EntityFromShapeResult(aSolid, 3);
130
                //if (!ent.IsNull()) {
131
                //    name += ws->Model()->StringLabel(ent)->ToCString();
132
                //}
133

134
                Part::Feature *pcFeature;
135
                pcFeature = static_cast<Part::Feature*>(pcDoc->addObject("Part::Feature", name.c_str()));
136
                pcFeature->Shape.setValue(aSolid);
137

138
                // This is a trick to access the GUI via Python and set the color property
139
                // of the associated view provider. If no GUI is up an exception is thrown
140
                // and cleared immediately
141
                std::map<int, Quantity_Color>::iterator it = hash_col.find(ShapeMapHasher{}(aSolid));
142
                if (it != hash_col.end()) {
143
                    try {
144
                        Py::Object obj(pcFeature->getPyObject(), true);
145
                        Py::Object vp(obj.getAttr("ViewObject"));
146
                        Py::Tuple col(3);
147
                        col.setItem(0, Py::Float(it->second.Red()));
148
                        col.setItem(1, Py::Float(it->second.Green()));
149
                        col.setItem(2, Py::Float(it->second.Blue()));
150
                        vp.setAttr("ShapeAppearance", col);
151
                        //Base::Console().Message("Set color to shape\n");
152
                    }
153
                    catch (Py::Exception& e) {
154
                        e.clear();
155
                    }
156
                }
157
            }
158
            // load all non-solids now
159
            for (ex.Init(aShape, TopAbs_SHELL, TopAbs_SOLID); ex.More(); ex.Next())
160
            {
161
                // get the shape
162
                const TopoDS_Shell& aShell = TopoDS::Shell(ex.Current());
163

164
                std::string name = fi.fileNamePure();
165
                //Handle(Standard_Transient) ent = tr->EntityFromShapeResult(aShell, 3);
166
                //if (!ent.IsNull()) {
167
                //    name += ws->Model()->StringLabel(ent)->ToCString();
168
                //}
169

170
                Part::Feature *pcFeature = static_cast<Part::Feature*>(pcDoc->addObject("Part::Feature", name.c_str()));
171
                pcFeature->Shape.setValue(aShell);
172
            }
173

174
            // put all other free-flying shapes into a single compound
175
            Standard_Boolean emptyComp = Standard_True;
176
            BRep_Builder builder;
177
            TopoDS_Compound comp;
178
            builder.MakeCompound(comp);
179

180
            for (ex.Init(aShape, TopAbs_FACE, TopAbs_SHELL); ex.More(); ex.Next()) {
181
                if (!ex.Current().IsNull()) {
182
                    builder.Add(comp, ex.Current());
183
                    emptyComp = Standard_False;
184
                }
185
            }
186
            for (ex.Init(aShape, TopAbs_WIRE, TopAbs_FACE); ex.More(); ex.Next()) {
187
                if (!ex.Current().IsNull()) {
188
                    builder.Add(comp, ex.Current());
189
                    emptyComp = Standard_False;
190
                }
191
            }
192
            for (ex.Init(aShape, TopAbs_EDGE, TopAbs_WIRE); ex.More(); ex.Next()) {
193
                if (!ex.Current().IsNull()) {
194
                    builder.Add(comp, ex.Current());
195
                    emptyComp = Standard_False;
196
                }
197
            }
198
            for (ex.Init(aShape, TopAbs_VERTEX, TopAbs_EDGE); ex.More(); ex.Next()) {
199
                if (!ex.Current().IsNull()) {
200
                    builder.Add(comp, ex.Current());
201
                    emptyComp = Standard_False;
202
                }
203
            }
204

205
            if (!emptyComp) {
206
                std::string name = fi.fileNamePure();
207
                Part::Feature *pcFeature = static_cast<Part::Feature*>(pcDoc->addObject
208
                    ("Part::Feature", name.c_str()));
209
                pcFeature->Shape.setValue(comp);
210
            }
211
        }
212
    }
213

214
    return 0;
215
}
216

217

218
bool Part::ReadColors (const Handle(XSControl_WorkSession) &WS, std::map<int, Quantity_Color>& hash_col)
219
{
220
    (void)WS;
221
    (void)hash_col;
222
    return Standard_False;
223
}
224

225
bool Part::ReadNames (const Handle(XSControl_WorkSession) &WS)
226
{
227
    (void)WS;
228
    return Standard_False;
229
}
230

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.