Import: add new implementation of STEP importer/exporter

For better supporting Link and groups. The original implementation can
still be used by uncheck the STEP import setting 'Use Link Group'.
This commit is contained in:
Zheng, Lei
2019-07-12 12:14:00 +08:00
committed by wmayer
parent d26f772035
commit 32ad54c9ef
9 changed files with 2428 additions and 533 deletions

View File

@@ -56,8 +56,7 @@
#include <CXX/Extensions.hxx>
#include <CXX/Objects.hxx>
#include "ImportOCAF.h"
#include "ExportOCAF.h"
#include "ImportOCAF2.h"
//#include "ImportOCAFAssembly.h"
#include <Base/PyObjectBase.h>
#include <Base/Console.h>
@@ -76,22 +75,38 @@
#include "ImpExpDxf.h"
class ImportOCAFExt : public Import::ImportOCAF2
{
public:
ImportOCAFExt(Handle(TDocStd_Document) h, App::Document* d, const std::string& name)
: ImportOCAF2(h, d, name)
{
}
std::map<Part::Feature*, std::vector<App::Color> > partColors;
private:
virtual void applyFaceColors(Part::Feature* part, const std::vector<App::Color>& colors) override {
partColors[part] = colors;
}
};
namespace Import {
class Module : public Py::ExtensionModule<Module>
{
public:
Module() : Py::ExtensionModule<Module>("Import")
{
add_varargs_method("open",&Module::importer,
add_keyword_method("open",&Module::importer,
"open(string) -- Open the file and create a new document."
);
add_varargs_method("insert",&Module::importer,
add_keyword_method("insert",&Module::importer,
"insert(string,string) -- Insert the file into the given document."
);
// add_varargs_method("openAssembly",&Module::importAssembly,
// "openAssembly(string) -- Open the assembly file and create a new document."
// );
add_varargs_method("export",&Module::exporter,
add_keyword_method("export",&Module::exporter,
"export(list,string) -- Export a list of objects into a single file."
);
add_varargs_method("readDXF",&Module::readDXF,
@@ -109,11 +124,17 @@ public:
virtual ~Module() {}
private:
Py::Object importer(const Py::Tuple& args)
Py::Object importer(const Py::Tuple& args, const Py::Dict &kwds)
{
char* Name;
char* DocName=0;
if (!PyArg_ParseTuple(args.ptr(), "et|s","utf-8",&Name,&DocName))
PyObject *importHidden = Py_None;
PyObject *merge = Py_None;
PyObject *useLinkGroup = Py_None;
int mode = -1;
static char* kwd_list[] = {"name", "docName","importHidden","merge","useLinkGroup","mode",0};
if(!PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "et|sOOOi",
kwd_list,"utf-8",&Name,&DocName,&importHidden,&merge,&useLinkGroup,&mode))
throw Py::Exception();
std::string Utf8Name = std::string(Name);
@@ -135,6 +156,7 @@ private:
Handle(XCAFApp_Application) hApp = XCAFApp_Application::GetApplication();
Handle(TDocStd_Document) hDoc;
hApp->NewDocument(TCollection_ExtendedString("MDTV-CAF"), hDoc);
ImportOCAFExt ocaf(hDoc, pcDoc, file.fileNamePure());
if (file.hasExtension("stp") || file.hasExtension("step")) {
try {
@@ -201,19 +223,25 @@ private:
}
#if 1
Import::ImportOCAFCmd ocaf(hDoc, pcDoc, file.fileNamePure());
if(merge!=Py_None)
ocaf.setMerge(PyObject_IsTrue(merge));
if(importHidden!=Py_None)
ocaf.setImportHiddenObject(PyObject_IsTrue(importHidden));
if(useLinkGroup!=Py_None)
ocaf.setUseLinkGroup(PyObject_IsTrue(useLinkGroup));
if(mode>=0)
ocaf.setMode(mode);
ocaf.loadShapes();
#else
Import::ImportXCAF xcaf(hDoc, pcDoc, file.fileNamePure());
xcaf.loadShapes();
#endif
pcDoc->recompute();
#endif
hApp->Close(hDoc);
std::map<Part::Feature*, std::vector<App::Color> > colorMap = ocaf.getPartColorsMap();
if (!colorMap.empty()) {
if (!ocaf.partColors.size()) {
Py::List list;
for (auto it : colorMap) {
for (auto &it : ocaf.partColors) {
Py::Tuple tuple(2);
tuple.setItem(0, Py::asObject(it.first->getPyObject()));
@@ -236,11 +264,16 @@ private:
return Py::None();
}
Py::Object exporter(const Py::Tuple& args)
Py::Object exporter(const Py::Tuple& args, const Py::Dict &kwds)
{
PyObject* object;
char* Name;
if (!PyArg_ParseTuple(args.ptr(), "Oet",&object,"utf-8",&Name))
PyObject *exportHidden = Py_None;
PyObject *legacy = Py_None;
PyObject *keepPlacement = Py_None;
static char* kwd_list[] = {"obj", "name", "exportHidden", "legacy", "keepPlacement",0};
if(!PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "Oet|OOO",
kwd_list,&object,"utf-8",&Name,&exportHidden,&legacy,&keepPlacement))
throw Py::Exception();
std::string Utf8Name = std::string(Name);
@@ -253,71 +286,46 @@ private:
Handle(TDocStd_Document) hDoc;
hApp->NewDocument(TCollection_ExtendedString("MDTV-CAF"), hDoc);
//bool keepExplicitPlacement = list.size() > 1;
bool keepExplicitPlacement = Standard_True;
Import::ExportOCAFCmd ocaf(hDoc, keepExplicitPlacement);
std::map<Part::Feature*, std::vector<App::Color> > partColors;
std::vector<Part::Feature*> partObjects;
std::vector<App::DocumentObject*> objs;
for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) {
PyObject* item = (*it).ptr();
if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) {
App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(item)->getDocumentObjectPtr();
if (obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
Part::Feature* part = static_cast<Part::Feature*>(obj);
partObjects.push_back(part);
}
else {
Base::Console().Message("'%s' is not a shape, export will be ignored.\n", obj->Label.getValue());
}
}
else if (PyTuple_Check(item) && PyTuple_Size(item) == 2) {
Py::Tuple tuple(*it);
Py::Object item0 = tuple.getItem(0);
Py::Object item1 = tuple.getItem(1);
if (PyObject_TypeCheck(item0.ptr(), &(App::DocumentObjectPy::Type))) {
App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(item0.ptr())->getDocumentObjectPtr();
if (obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
Part::Feature* part = static_cast<Part::Feature*>(obj);
App::PropertyColorList colors;
colors.setPyObject(item1.ptr());
partObjects.push_back(part);
partColors[part] = colors.getValues();
}
else {
Base::Console().Message("'%s' is not a shape, export will be ignored.\n", obj->Label.getValue());
}
}
}
if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type)))
objs.push_back(static_cast<App::DocumentObjectPy*>(item)->getDocumentObjectPtr());
}
ocaf.setPartColorsMap(partColors);
// That stuff is exporting a list of selected objects into FreeCAD Tree
std::vector <TDF_Label> hierarchical_label;
std::vector <TopLoc_Location> hierarchical_loc;
std::vector <App::DocumentObject*> hierarchical_part;
for (auto it : partObjects) {
ocaf.exportObject(it, hierarchical_label, hierarchical_loc, hierarchical_part);
if(legacy == Py_None) {
auto hGrp = App::GetApplication().GetParameterGroupByPath(
"User parameter:BaseApp/Preferences/Mod/Import");
legacy = hGrp->GetBool("ExportLegacy",false)?Py_True:Py_False;
}
// Free Shapes must have absolute placement and not explicit
std::vector <TDF_Label> FreeLabels;
std::vector <int> part_id;
ocaf.getFreeLabels(hierarchical_label, FreeLabels, part_id);
// Got issue with the colors as they are coming from the View Provider they can't be determined into
// the App Code.
std::vector< std::vector<App::Color> > Colors;
ocaf.getPartColors(hierarchical_part, FreeLabels, part_id, Colors);
ocaf.reallocateFreeShape(hierarchical_part, FreeLabels, part_id, Colors);
Import::ExportOCAF2 ocaf(hDoc);
if(!PyObject_IsTrue(legacy) || !ocaf.canFallback(objs)) {
if(exportHidden!=Py_None)
ocaf.setExportHiddenObject(PyObject_IsTrue(exportHidden));
if(keepPlacement!=Py_None)
ocaf.setKeepPlacement(PyObject_IsTrue(keepPlacement));
ocaf.exportObjects(objs);
}else{
bool keepExplicitPlacement = objs.size() > 1;
keepExplicitPlacement = Standard_True;
ExportOCAF ocaf(hDoc, keepExplicitPlacement);
// That stuff is exporting a list of selected objects into FreeCAD Tree
std::vector <TDF_Label> hierarchical_label;
std::vector <TopLoc_Location> hierarchical_loc;
std::vector <App::DocumentObject*> hierarchical_part;
for(auto obj : objs)
ocaf.exportObject(obj,hierarchical_label, hierarchical_loc,hierarchical_part);
// Free Shapes must have absolute placement and not explicit
std::vector <TDF_Label> FreeLabels;
std::vector <int> part_id;
ocaf.getFreeLabels(hierarchical_label,FreeLabels, part_id);
#if OCC_VERSION_HEX >= 0x070200
// Update is not performed automatically anymore: https://tracker.dev.opencascade.org/view.php?id=28055
XCAFDoc_DocumentTool::ShapeTool(hDoc->Main())->UpdateAssemblies();
// Update is not performed automatically anymore: https://tracker.dev.opencascade.org/view.php?id=28055
XCAFDoc_DocumentTool::ShapeTool(hDoc->Main())->UpdateAssemblies();
#endif
}
Base::FileInfo file(Utf8Name.c_str());
if (file.hasExtension("stp") || file.hasExtension("step")) {

View File

@@ -31,6 +31,8 @@ SET(Import_SRCS
ExportOCAF.h
ImportOCAF.cpp
ImportOCAF.h
ImportOCAF2.cpp
ImportOCAF2.h
#ImportOCAFAssembly.cpp
#ImportOCAFAssembly.h
StepShapePy.xml

View File

@@ -54,7 +54,9 @@
# include <XCAFDoc_ShapeTool.hxx>
# include <XCAFDoc_ColorTool.hxx>
# include <XCAFDoc_Location.hxx>
# include <XCAFDoc_GraphNode.hxx>
# include <TDF_Label.hxx>
# include <TDF_Tool.hxx>
# include <TDF_LabelSequence.hxx>
# include <TDF_ChildIterator.hxx>
# include <TDataStd_Name.hxx>
@@ -81,11 +83,14 @@
# endif
#endif
#include <boost/algorithm/string.hpp>
#include <Base/Parameter.h>
#include <Base/Console.h>
#include <App/Application.h>
#include <App/Document.h>
#include <App/DocumentObjectPy.h>
#include <App/Part.h>
#include <App/Link.h>
#include <Mod/Part/App/PartFeature.h>
#include <Mod/Part/App/FeatureCompound.h>
#include "ImportOCAF.h"
@@ -102,11 +107,8 @@
#include <tbb/task_group.h>
#endif
using namespace Import;
#define OCAF_KEEP_PLACEMENT
ImportOCAF::ImportOCAF(Handle(TDocStd_Document) h, App::Document* d, const std::string& name)

View File

@@ -29,10 +29,12 @@
#include <XCAFDoc_ShapeTool.hxx>
#include <Quantity_Color.hxx>
#include <TopoDS_Shape.hxx>
#include <TDF_LabelMapHasher.hxx>
#include <climits>
#include <string>
#include <set>
#include <map>
#include <unordered_map>
#include <vector>
#include <App/Material.h>
#include <App/Part.h>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,212 @@
/****************************************************************************
* Copyright (c) 2018 Zheng, Lei (realthunder) <realthunder.dev@gmail.com>*
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
****************************************************************************/
#ifndef IMPORT_IMPORTOCAF2_H
#define IMPORT_IMPORTOCAF2_H
#include <TDocStd_Document.hxx>
#include <XCAFDoc_ColorTool.hxx>
#include <XCAFDoc_ShapeTool.hxx>
#include <TopoDS_Shape.hxx>
#include <TDF_LabelMapHasher.hxx>
#include <climits>
#include <string>
#include <set>
#include <map>
#include <unordered_map>
#include <vector>
#include <App/Material.h>
#include <App/Part.h>
#include <Mod/Part/App/FeatureCompound.h>
#include <Base/Sequencer.h>
#include "ImportOCAF.h"
#include "ExportOCAF.h"
class TDF_Label;
class TopLoc_Location;
namespace App {
class Document;
class DocumentObject;
}
namespace Part {
class Feature;
}
namespace Import {
struct ShapeHasher {
std::size_t operator()(const TopoDS_Shape &s) const {
return s.HashCode(INT_MAX);
}
};
struct LabelHasher {
std::size_t operator()(const TDF_Label &l) const {
return TDF_LabelMapHasher::HashCode(l,INT_MAX);
}
};
class ImportExport ImportOCAF2
{
public:
ImportOCAF2(Handle(TDocStd_Document) h, App::Document* d, const std::string& name);
virtual ~ImportOCAF2();
App::DocumentObject* loadShapes();
void setMerge(bool enable) { merge=enable;};
void setUseLinkGroup(bool enable) { useLinkGroup=enable; }
void setBaseName(bool enable) { useBaseName=enable; }
void setImportHiddenObject(bool enable) {importHidden=enable;}
void setReduceObjects(bool enable) {reduceObjects=enable;}
void setShowProgress(bool enable) {showProgress=enable;}
void setExpandCompound(bool enable) {expandCompound=enable;}
enum ImportMode {
SingleDoc = 0,
GroupPerDoc = 1,
GroupPerDir = 2,
ObjectPerDoc = 3,
ObjectPerDir = 4,
ModeMax,
};
void setMode(int m);
int getMode() const {return mode;}
private:
struct Info {
std::string baseName;
App::DocumentObject *obj = 0;
App::PropertyPlacement *propPlacement = 0;
App::Color faceColor;
App::Color edgeColor;
bool hasFaceColor = false;
bool hasEdgeColor = false;
int free = true;
};
App::DocumentObject *loadShape(App::Document *doc, TDF_Label label,
const TopoDS_Shape &shape, bool baseOnly=false, bool newDoc=true);
App::Document *getDocument(App::Document *doc, TDF_Label label);
bool createAssembly(App::Document *doc, TDF_Label label,
const TopoDS_Shape &shape, Info &info, bool newDoc);
bool createObject(App::Document *doc, TDF_Label label,
const TopoDS_Shape &shape, Info &info, bool newDoc);
bool createGroup(App::Document *doc, Info &info,
const TopoDS_Shape &shape, std::vector<App::DocumentObject*> &children,
const boost::dynamic_bitset<> &visibilities, bool canReduce=false);
bool getColor(const TopoDS_Shape &shape, Info &info, bool check=false, bool noDefault=false);
void getSHUOColors(TDF_Label label, std::map<std::string,App::Color> &colors, bool appendFirst);
void setObjectName(Info &info, TDF_Label label);
std::string getLabelName(TDF_Label label);
App::DocumentObject *expandShape(App::Document *doc, TDF_Label label, const TopoDS_Shape &shape);
virtual void applyEdgeColors(Part::Feature*, const std::vector<App::Color>&) {}
virtual void applyFaceColors(Part::Feature*, const std::vector<App::Color>&) {}
virtual void applyElementColors(App::DocumentObject*, const std::map<std::string,App::Color>&) {}
virtual void applyLinkColor(App::DocumentObject *, int /*index*/, App::Color){}
private:
class ImportLegacy : public ImportOCAF {
public:
ImportLegacy(ImportOCAF2 &parent)
:ImportOCAF(parent.pDoc, parent.pDocument, parent.default_name),myParent(parent)
{}
private:
void applyColors(Part::Feature* part, const std::vector<App::Color>& colors) {
myParent.applyFaceColors(part, colors);
}
ImportOCAF2 &myParent;
};
friend class ImportLegacy;
Handle(TDocStd_Document) pDoc;
App::Document* pDocument;
Handle(XCAFDoc_ShapeTool) aShapeTool;
Handle(XCAFDoc_ColorTool) aColorTool;
bool merge;
std::string default_name;
bool useLinkGroup;
bool useBaseName;
bool importHidden;
bool reduceObjects;
bool showProgress;
bool expandCompound;
int mode;
std::string filePath;
std::unordered_map<TopoDS_Shape, Info, ShapeHasher> myShapes;
std::unordered_map<TDF_Label, std::string, LabelHasher> myNames;
std::unordered_map<App::DocumentObject*, App::PropertyPlacement*> myCollapsedObjects;
App::Color defaultFaceColor;
App::Color defaultEdgeColor;
Base::SequencerLauncher *sequencer;
};
class ImportExport ExportOCAF2
{
public:
typedef std::function<std::map<std::string,App::Color>(
App::DocumentObject*, const char*)> GetShapeColorsFunc;
ExportOCAF2(Handle(TDocStd_Document) h, GetShapeColorsFunc func=GetShapeColorsFunc());
void setExportHiddenObject(bool enable) {exportHidden=enable;}
void setKeepPlacement(bool enable) {keepPlacement=enable;}
void exportObjects(std::vector<App::DocumentObject*> &objs, const char *name=0);
bool canFallback(std::vector<App::DocumentObject*> objs);
private:
TDF_Label exportObject(App::DocumentObject *obj, const char *sub, TDF_Label parent, const char *name=0);
void setupObject(TDF_Label label, App::DocumentObject *obj,
const Part::TopoShape &shape, const std::string &prefix,
const char *name=0, bool force=false);
void setName(TDF_Label label, App::DocumentObject *obj, const char *name=0);
TDF_Label findComponent(const char *subname, TDF_Label label, TDF_LabelSequence &labels);
private:
Handle(TDocStd_Document) pDoc;
Handle(XCAFDoc_ShapeTool) aShapeTool;
Handle(XCAFDoc_ColorTool) aColorTool;
std::unordered_map<App::DocumentObject *, TDF_Label> myObjects;
std::unordered_map<TDF_Label, std::vector<std::string>, LabelHasher> myNames;
std::set<std::pair<App::DocumentObject*,std::string> > mySetups;
std::vector<App::DocumentObject*> groupLinks;
GetShapeColorsFunc getShapeColors;
App::Color defaultColor;
bool exportHidden;
bool keepPlacement;
};
}
#endif //IMPORT_IMPORTOCAF2_H

View File

@@ -82,14 +82,14 @@
#include <App/DocumentObjectPy.h>
#include <Gui/Application.h>
#include <Gui/MainWindow.h>
#include <Gui/Command.h>
#include <Mod/Part/Gui/ViewProvider.h>
#include <Mod/Part/App/PartFeature.h>
#include <Mod/Part/App/ProgressIndicator.h>
#include <Mod/Part/App/ImportIges.h>
#include <Mod/Part/App/ImportStep.h>
#include <Mod/Part/App/encodeFilename.h>
#include <Mod/Import/App/ImportOCAF.h>
#include <Mod/Import/App/ExportOCAF.h>
#include <Mod/Import/App/ImportOCAF2.h>
#include <TDataStd.hxx>
#include <TDataStd_Integer.hxx>
@@ -121,7 +121,11 @@
#include <Gui/Application.h>
#include <Gui/Document.h>
#include <Gui/ViewProvider.h>
#include <Gui/ViewProviderLink.h>
FC_LOG_LEVEL_INIT("Import", true, true)
class OCAFBrowser
{
public:
@@ -286,23 +290,66 @@ void OCAFBrowser::load(const TDF_Label& label, QTreeWidgetItem* item, const QStr
}
}
class ImportOCAFGui : public Import::ImportOCAF
class ImportOCAFExt : public Import::ImportOCAF2
{
public:
ImportOCAFGui(Handle(TDocStd_Document) h, App::Document* d, const std::string& name)
: ImportOCAF(h, d, name)
ImportOCAFExt(Handle(TDocStd_Document) h, App::Document* d, const std::string& name)
: ImportOCAF2(h, d, name)
{
}
private:
void applyColors(Part::Feature* part, const std::vector<App::Color>& colors)
{
Gui::ViewProvider* vp = Gui::Application::Instance->getViewProvider(part);
if (vp && vp->isDerivedFrom(PartGui::ViewProviderPartExt::getClassTypeId())) {
static_cast<PartGui::ViewProviderPartExt*>(vp)->ShapeColor.setValue(colors.front());
static_cast<PartGui::ViewProviderPartExt*>(vp)->DiffuseColor.setValues(colors);
}
}
virtual void applyFaceColors(Part::Feature* part, const std::vector<App::Color>& colors) override {
auto vp = dynamic_cast<PartGui::ViewProviderPartExt*>(Gui::Application::Instance->getViewProvider(part));
if (!vp) return;
if(colors.empty()) {
// vp->MapFaceColor.setValue(true);
// vp->MapLineColor.setValue(true);
// vp->updateColors(0,true);
return;
}
// vp->MapFaceColor.setValue(false);
if(colors.size() == 1)
vp->ShapeColor.setValue(colors.front());
else
vp->DiffuseColor.setValues(colors);
}
virtual void applyEdgeColors(Part::Feature* part, const std::vector<App::Color>& colors) override {
auto vp = dynamic_cast<PartGui::ViewProviderPartExt*>(Gui::Application::Instance->getViewProvider(part));
if (!vp) return;
// vp->MapLineColor.setValue(false);
if(colors.size() == 1)
vp->LineColor.setValue(colors.front());
else
vp->LineColorArray.setValues(colors);
}
virtual void applyLinkColor(App::DocumentObject *obj, int index, App::Color color) override {
auto vp = dynamic_cast<Gui::ViewProviderLink*>(Gui::Application::Instance->getViewProvider(obj));
if(!vp)
return;
if(index<0) {
vp->OverrideMaterial.setValue(true);
vp->ShapeMaterial.setDiffuseColor(color);
return;
}
if(vp->OverrideMaterialList.getSize()<=index)
vp->OverrideMaterialList.setSize(index+1);
vp->OverrideMaterialList.set1Value(index,true);
App::Material mat(App::Material::DEFAULT);
if(vp->MaterialList.getSize()<=index)
vp->MaterialList.setSize(index+1,mat);
mat.diffuseColor = color;
vp->MaterialList.set1Value(index,mat);
}
virtual void applyElementColors(App::DocumentObject *obj,
const std::map<std::string,App::Color> &colors) override
{
auto vp = Gui::Application::Instance->getViewProvider(obj);
if(!vp)
return;
(void)colors;
// vp->setElementColors(colors);
}
};
class ExportOCAFGui : public Import::ExportOCAF
@@ -329,13 +376,13 @@ class Module : public Py::ExtensionModule<Module>
public:
Module() : Py::ExtensionModule<Module>("ImportGui")
{
add_varargs_method("open",&Module::open,
add_keyword_method("open",&Module::insert,
"open(string) -- Open the file and create a new document."
);
add_varargs_method("insert",&Module::insert,
add_keyword_method("insert",&Module::insert,
"insert(string,string) -- Insert the file into the given document."
);
add_varargs_method("export",&Module::exporter,
add_keyword_method("export",&Module::exporter,
"export(list,string) -- Export a list of objects into a single file."
);
add_varargs_method("ocaf",&Module::ocaf,
@@ -347,21 +394,23 @@ public:
virtual ~Module() {}
private:
Py::Object open(const Py::Tuple& args)
{
return insert(args);
}
Py::Object insert(const Py::Tuple& args)
Py::Object insert(const Py::Tuple& args, const Py::Dict &kwds)
{
char* Name;
char* DocName=0;
if (!PyArg_ParseTuple(args.ptr(), "et|s","utf-8",&Name,&DocName))
PyObject *importHidden = Py_None;
PyObject *merge = Py_None;
PyObject *useLinkGroup = Py_None;
int mode = -1;
static char* kwd_list[] = {"name","docName","importHidden","merge","useLinkGroup","mode",0};
if(!PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "et|sOOOi",
kwd_list,"utf-8",&Name,&DocName,&importHidden,&merge,&useLinkGroup,&mode))
throw Py::Exception();
std::string Utf8Name = std::string(Name);
PyMem_Free(Name);
std::string name8bit = Part::encodeFilename(Utf8Name);
try {
//Base::Console().Log("Insert in Part with %s",Name);
Base::FileInfo file(Utf8Name.c_str());
@@ -380,17 +429,29 @@ private:
hApp->NewDocument(TCollection_ExtendedString("MDTV-CAF"), hDoc);
ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Import/hSTEP");
optionReadShapeCompoundMode = hGrp->GetBool("ReadShapeCompoundMode", optionReadShapeCompoundMode);
ImportOCAFExt ocaf(hDoc, pcDoc, file.fileNamePure());
FC_TIME_INIT(t);
FC_DURATION_DECL_INIT2(d1,d2);
if (file.hasExtension("stp") || file.hasExtension("step")) {
if(mode<0)
mode = ocaf.getMode();
if(mode && !pcDoc->isSaved()) {
auto gdoc = Gui::Application::Instance->getDocument(pcDoc);
if(!gdoc->save())
return Py::Object();
}
try {
STEPCAFControl_Reader aReader;
aReader.SetColorMode(true);
aReader.SetNameMode(true);
aReader.SetLayerMode(true);
aReader.SetSHUOMode(true);
if (aReader.ReadFile((const char*)name8bit.c_str()) != IFSelect_RetDone) {
throw Py::Exception(PyExc_IOError, "cannot read STEP file");
}
Handle(Message_ProgressIndicator) pi = new Part::ProgressIndicator(100);
aReader.Reader().WS()->MapReader()->SetProgress(pi);
pi->NewScope(100, "Reading STEP file...");
@@ -445,18 +506,30 @@ private:
throw Py::Exception(Base::BaseExceptionFreeCADError, "no supported file format");
}
ImportOCAFGui ocaf(hDoc, pcDoc, file.fileNamePure());
// We must recompute the doc before loading shapes as they are going to be
// inserted into the document and computed at the same time so we are going to
// purge the document before recomputing it to clear it and settle it in the proper
// way. This is drastically improving STEP rendering time on complex STEP files.
pcDoc->recompute();
if (file.hasExtension("stp") || file.hasExtension("step"))
ocaf.setMerge(optionReadShapeCompoundMode);
ocaf.loadShapes();
pcDoc->purgeTouched();
pcDoc->recompute();
FC_DURATION_PLUS(d1,t);
if(merge!=Py_None)
ocaf.setMerge(PyObject_IsTrue(merge));
if(importHidden!=Py_None)
ocaf.setImportHiddenObject(PyObject_IsTrue(importHidden));
if(useLinkGroup!=Py_None)
ocaf.setUseLinkGroup(PyObject_IsTrue(useLinkGroup));
ocaf.setMode(mode);
auto ret = ocaf.loadShapes();
hApp->Close(hDoc);
FC_DURATION_PLUS(d2,t);
FC_DURATION_MSG(d1,"file read");
FC_DURATION_MSG(d2,"import");
FC_DURATION_MSG((d1+d2),"total");
if(ret) {
App::GetApplication().setActiveDocument(pcDoc);
auto gdoc = Gui::Application::Instance->getDocument(pcDoc);
if(gdoc) {
gdoc->setActiveView();
Gui::Application::Instance->commandManager().runCommandByName("Std_ViewFitAll");
}
return Py::asObject(ret->getPyObject());
}
}
catch (Standard_Failure& e) {
throw Py::Exception(Base::BaseExceptionFreeCADError, e.GetMessageString());
@@ -468,11 +541,23 @@ private:
return Py::None();
}
Py::Object exporter(const Py::Tuple& args)
static std::map<std::string, App::Color> getShapeColors(App::DocumentObject *obj, const char *subname) {
auto vp = Gui::Application::Instance->getViewProvider(obj);
if(vp)
return vp->getElementColors(subname);
return std::map<std::string,App::Color>();
}
Py::Object exporter(const Py::Tuple& args, const Py::Dict &kwds)
{
PyObject* object;
char* Name;
if (!PyArg_ParseTuple(args.ptr(), "Oet",&object,"utf-8",&Name))
PyObject *exportHidden = Py_None;
PyObject *legacy = Py_None;
PyObject *keepPlacement = Py_None;
static char* kwd_list[] = {"obj", "name", "exportHidden", "legacy", "keepPlacement",0};
if(!PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "Oet|OOO",
kwd_list,&object,"utf-8",&Name,&exportHidden,&legacy,&keepPlacement))
throw Py::Exception();
std::string Utf8Name = std::string(Name);
@@ -485,37 +570,52 @@ private:
Handle(TDocStd_Document) hDoc;
hApp->NewDocument(TCollection_ExtendedString("MDTV-CAF"), hDoc);
//bool keepExplicitPlacement = list.size() > 1;
bool keepExplicitPlacement = Standard_True;
ExportOCAFGui ocaf(hDoc, keepExplicitPlacement);
// That stuff is exporting a list of selected objects into FreeCAD Tree
std::vector <TDF_Label> hierarchical_label;
std::vector <TopLoc_Location> hierarchical_loc;
std::vector <App::DocumentObject*> hierarchical_part;
std::vector<App::DocumentObject *> objs;
for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) {
PyObject* item = (*it).ptr();
if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) {
App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(item)->getDocumentObjectPtr();
ocaf.exportObject(obj, hierarchical_label, hierarchical_loc, hierarchical_part);
}
}
if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type)))
objs.push_back(static_cast<App::DocumentObjectPy*>(item)->getDocumentObjectPtr());
}
if(legacy == Py_None) {
auto hGrp = App::GetApplication().GetParameterGroupByPath(
"User parameter:BaseApp/Preferences/Mod/Import");
legacy = hGrp->GetBool("ExportLegacy",false)?Py_True:Py_False;
}
Import::ExportOCAF2 ocaf(hDoc, &getShapeColors);
if(!PyObject_IsTrue(legacy) || !ocaf.canFallback(objs)) {
if(exportHidden!=Py_None)
ocaf.setExportHiddenObject(PyObject_IsTrue(exportHidden));
if(keepPlacement!=Py_None)
ocaf.setKeepPlacement(PyObject_IsTrue(keepPlacement));
ocaf.exportObjects(objs);
} else {
bool keepExplicitPlacement = objs.size() > 1;
keepExplicitPlacement = Standard_True;
ExportOCAFGui ocaf(hDoc, keepExplicitPlacement);
// That stuff is exporting a list of selected objects into FreeCAD Tree
std::vector <TDF_Label> hierarchical_label;
std::vector <TopLoc_Location> hierarchical_loc;
std::vector <App::DocumentObject*> hierarchical_part;
for(auto obj : objs)
ocaf.exportObject(obj,hierarchical_label, hierarchical_loc,hierarchical_part);
// Free Shapes must have absolute placement and not explicit
std::vector <TDF_Label> FreeLabels;
std::vector <int> part_id;
ocaf.getFreeLabels(hierarchical_label, FreeLabels, part_id);
// Got issue with the colors as they are coming from the View Provider they can't be determined into
// the App Code.
std::vector< std::vector<App::Color> > Colors;
ocaf.getPartColors(hierarchical_part, FreeLabels, part_id, Colors);
ocaf.reallocateFreeShape(hierarchical_part, FreeLabels, part_id, Colors);
// Free Shapes must have absolute placement and not explicit
std::vector <TDF_Label> FreeLabels;
std::vector <int> part_id;
ocaf.getFreeLabels(hierarchical_label,FreeLabels, part_id);
// Got issue with the colors as they are coming from the View Provider they can't be determined into
// the App Code.
std::vector< std::vector<App::Color> > Colors;
ocaf.getPartColors(hierarchical_part,FreeLabels,part_id,Colors);
ocaf.reallocateFreeShape(hierarchical_part,FreeLabels,part_id,Colors);
#if OCC_VERSION_HEX >= 0x070200
// Update is not performed automatically anymore: https://tracker.dev.opencascade.org/view.php?id=28055
XCAFDoc_DocumentTool::ShapeTool(hDoc->Main())->UpdateAssemblies();
XCAFDoc_DocumentTool::ShapeTool(hDoc->Main())->UpdateAssemblies();
#endif
}
Base::FileInfo file(Utf8Name.c_str());
if (file.hasExtension("stp") || file.hasExtension("step")) {
@@ -597,6 +697,7 @@ private:
aReader.SetColorMode(true);
aReader.SetNameMode(true);
aReader.SetLayerMode(true);
aReader.SetSHUOMode(true);
if (aReader.ReadFile((Standard_CString)Name) != IFSelect_RetDone) {
throw Py::Exception(PyExc_IOError, "cannot read STEP file");
}