[Assembly] fixing the commands and some import

This commit is contained in:
jriegel 2014-11-09 22:29:43 +01:00 committed by Stefan Tröger
parent d59904fd37
commit 5271a24476
7 changed files with 2031 additions and 496 deletions

File diff suppressed because it is too large Load Diff

View File

@ -76,34 +76,23 @@ void CmdAssemblyAddNewPart::activated(int iMsg)
}
openCommand("Insert Part");
// need the help of the Part module to set up a Part
addModule(App,"PartDesign");
addModule(Gui,"PartDesignGui");
addModule(Gui,"AssemblyGui");
std::string PartName = getUniqueObjectName("Part");
doCommand(Doc,"App.activeDocument().addObject('Assembly::ItemPart','%s')",PartName.c_str());
if(dest){
std::string fatherName = dest->getNameInDocument();
doCommand(Doc,"App.activeDocument().%s.Items = App.activeDocument().%s.Items + [App.activeDocument().%s] ",fatherName.c_str(),fatherName.c_str(),PartName.c_str());
}
Command::addModule(App,"PartDesign");
Command::addModule(Gui,"PartDesignGui");
std::string ProductName = dest->getNameInDocument();
std::string RefName = getUniqueObjectName((PartName + "-1").c_str());
std::string BodyName = getUniqueObjectName("Body");
// add the standard planes
std::string Plane1Name = BodyName + "_PlaneXY";
std::string Plane2Name = BodyName + "_PlaneYZ";
std::string Plane3Name = BodyName + "_PlaneXZ";
doCommand(Doc,"App.activeDocument().addObject('App::Plane','%s')",Plane1Name.c_str());
doCommand(Doc,"App.activeDocument().ActiveObject.Label = 'XY-Plane'");
doCommand(Doc,"App.activeDocument().addObject('App::Plane','%s')",Plane2Name.c_str());
doCommand(Doc,"App.activeDocument().ActiveObject.Placement = App.Placement(App.Vector(),App.Rotation(App.Vector(0,1,0),90))");
doCommand(Doc,"App.activeDocument().ActiveObject.Label = 'YZ-Plane'");
doCommand(Doc,"App.activeDocument().addObject('App::Plane','%s')",Plane3Name.c_str());
doCommand(Doc,"App.activeDocument().ActiveObject.Placement = App.Placement(App.Vector(),App.Rotation(App.Vector(1,0,0),90))");
doCommand(Doc,"App.activeDocument().ActiveObject.Label = 'XZ-Plane'");
// add to anotation set of the Part object
doCommand(Doc,"App.activeDocument().%s.Annotation = [App.activeDocument().%s,App.activeDocument().%s,App.activeDocument().%s] ",PartName.c_str(),Plane1Name.c_str(),Plane2Name.c_str(),Plane3Name.c_str());
// add the main body
doCommand(Doc,"App.activeDocument().addObject('PartDesign::Body','%s')",BodyName.c_str());
doCommand(Doc,"App.activeDocument().%s.Model = App.activeDocument().%s ",PartName.c_str(),BodyName.c_str());
doCommand(Doc,"App.activeDocument().addObject('App::Part','%s')",PartName.c_str());
doCommand(Doc,"App.activeDocument().addObject('Assembly::ProductRef','%s')",RefName.c_str());
doCommand(Doc,"App.activeDocument().%s.Items = App.activeDocument().%s.Items + [App.activeDocument().%s]",ProductName.c_str(),ProductName.c_str(),RefName.c_str());
doCommand(Doc,"App.activeDocument().%s.Item = App.activeDocument().%s",RefName.c_str(),PartName.c_str());
doCommand(Doc,"AssemblyGui.setActiveAssembly(App.activeDocument().%s)",ProductName.c_str());
// create a PartDesign Part for now, can be later any kind of Part or an empty one
doCommand(Gui::Command::Doc,"PartDesignGui.setUpPart(App.activeDocument().%s)",PartName.c_str());
this->updateActive();
}
@ -135,15 +124,23 @@ void CmdAssemblyAddNewComponent::activated(int iMsg)
dest = dynamic_cast<Assembly::Product*>(Sel.front());
}else if(ActiveAsmObject && ActiveAsmObject->getTypeId().isDerivedFrom(Assembly::Product::getClassTypeId())) {
dest = dynamic_cast<Assembly::Product*>(ActiveAsmObject);
}else {
QMessageBox::warning(Gui::getMainWindow(), QObject::tr("No active or selected assembly"),
QObject::tr("You need a active or selected assembly to insert a component in."));
return;
}
openCommand("Insert Component");
std::string CompName = getUniqueObjectName("Assembly");
doCommand(Doc,"App.activeDocument().addObject('Assembly::Product','%s')",CompName.c_str());
if(dest){
std::string fatherName = dest->getNameInDocument();
doCommand(Doc,"App.activeDocument().%s.Items = App.activeDocument().%s.Items + [App.activeDocument().%s] ",fatherName.c_str(),fatherName.c_str(),CompName.c_str());
}
std::string NewProdName = getUniqueObjectName("Product");
std::string ProductName = dest->getNameInDocument();
std::string RefName = getUniqueObjectName((NewProdName + "-1").c_str());
doCommand(Doc,"App.activeDocument().addObject('Assembly::Product','%s')",NewProdName.c_str());
doCommand(Doc,"App.activeDocument().addObject('Assembly::ProductRef','%s')",RefName.c_str());
doCommand(Doc,"App.activeDocument().%s.Items = App.activeDocument().%s.Items + [App.activeDocument().%s]",ProductName.c_str(),ProductName.c_str(),RefName.c_str());
doCommand(Doc,"App.activeDocument().%s.Item = App.activeDocument().%s",RefName.c_str(),NewProdName.c_str());
}
//===========================================================================

View File

@ -46,22 +46,30 @@ using namespace AssemblyGui;
void switchToDocument(const App::Document* doc)
{
if(doc->countObjects() == 0){ // -> set up a empty document
std::string PartName = doc->getUniqueObjectName("Part");
if( doc->Tip.getValue() && doc->Tip.getValue()->getTypeId() == App::Part::getClassTypeId() )
{ // in case of a Part document
std::string PartName = doc->Tip.getValue()->getNameInDocument();
std::string ProductName = doc->getUniqueObjectName("Product");
std::string RefName = doc->getUniqueObjectName((PartName + "-1").c_str());
Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().Tip = App.activeDocument().addObject('Assembly::Product','%s')",ProductName.c_str());
Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().addObject('Assembly::ProductRef','%s')",RefName.c_str());
Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().%s.Items = App.activeDocument().%s",ProductName.c_str(),RefName.c_str());
Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().addObject('App::Part','%s')",PartName.c_str());
Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().%s.Item = App.activeDocument().%s",RefName.c_str(),PartName.c_str());
Gui::Command::addModule(Gui::Command::Gui,"AssemblyGui");
Gui::Command::doCommand(Gui::Command::Doc,"AssemblyGui.setActiveAssembly(App.activeDocument().%s)",ProductName.c_str());
// create a PartDesign Part for now, can be later any kind of Part or an empty one
Gui::Command::addModule(Gui::Command::Doc,"PartDesignGui");
Gui::Command::doCommand(Gui::Command::Doc,"PartDesignGui.setUpPart(App.activeDocument().%s)",PartName.c_str());
//// create a PartDesign Part for now, can be later any kind of Part or an empty one
//Gui::Command::addModule(Gui::Command::Doc,"PartDesignGui");
//Gui::Command::doCommand(Gui::Command::Doc,"PartDesignGui.setUpPart(App.activeDocument().%s)",PartName.c_str());
} else if(doc->countObjects() == 0){ // -> set up a empty document
std::string ProductName = doc->getUniqueObjectName("Product");
Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().Tip = App.activeDocument().addObject('Assembly::Product','%s')",ProductName.c_str());
Gui::Command::addModule(Gui::Command::Gui,"AssemblyGui");
Gui::Command::doCommand(Gui::Command::Doc,"AssemblyGui.setActiveAssembly(App.activeDocument().%s)",ProductName.c_str());
}
}
@ -157,16 +165,16 @@ void Workbench::activated()
addTaskWatcher(Watcher);
Gui::Control().showTaskView();
//App::Document *doc = App::GetApplication().getActiveDocument();
App::Document *doc = App::GetApplication().getActiveDocument();
//if(!doc){
// // create a new document
// std::string uniqueName = App::GetApplication().getUniqueDocumentName("Assembly1");
// Gui::Command::doCommand(Gui::Command::Doc,"App.newDocument('%s')",uniqueName.c_str());
// doc = App::GetApplication().getActiveDocument();
// switchToDocument(doc);
//}
if(doc)
switchToDocument(doc);
// show a warning about the Alpha state of FreeCAD Assembly

View File

@ -76,10 +76,17 @@ public:
add_varargs_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,
"export(list,string) -- Export a list of objects into a single file."
);
initialize("This module is the Import module."); // register with Python
if(TargetObjectPy)
target = static_cast<App::DocumentObjectPy*>(TargetObjectPy)->getDocumentObjectPtr();
}
virtual ~Module() {}
@ -301,16 +308,25 @@ private:
"importAssembly(FileName,Target) -- Import a Assembly file and creates a Assembly structure."},
};
PyObject * importAssembly(PyObject *self, PyObject *args)
static PyObject * importAssembly(PyObject *self, PyObject *args)
{
char* Name;
PyObject* TargetObject=0;
if (!PyArg_ParseTuple(args, "s|O",&Name,&TargetObject))
PyObject* TargetObjectPy=0;
if (!PyArg_ParseTuple(args, "et|O!","utf-8",&Name,&(App::DocumentObjectPy::Type),&TargetObjectPy))
return 0;
std::string Utf8Name = std::string(Name);
PyMem_Free(Name);
std::string name8bit = Part::encodeFilename(Utf8Name);
PY_TRY {
//Base::Console().Log("Insert in Part with %s",Name);
Base::FileInfo file(Name);
Base::FileInfo file(name8bit);
App::DocumentObject* target = nullptr;
if(TargetObjectPy)
target = static_cast<App::DocumentObjectPy*>(TargetObjectPy)->getDocumentObjectPtr();
App::Document *pcDoc = 0;
@ -330,7 +346,7 @@ PyObject * importAssembly(PyObject *self, PyObject *args)
aReader.SetColorMode(true);
aReader.SetNameMode(true);
aReader.SetLayerMode(true);
if (aReader.ReadFile((Standard_CString)Name) != IFSelect_RetDone) {
if (aReader.ReadFile((Standard_CString)(name8bit.c_str())) != IFSelect_RetDone) {
PyErr_SetString(PyExc_Exception, "cannot read STEP file");
return 0;
}
@ -359,7 +375,7 @@ PyObject * importAssembly(PyObject *self, PyObject *args)
aReader.SetColorMode(true);
aReader.SetNameMode(true);
aReader.SetLayerMode(true);
if (aReader.ReadFile((Standard_CString)Name) != IFSelect_RetDone) {
if (aReader.ReadFile((Standard_CString)(name8bit.c_str())) != IFSelect_RetDone) {
PyErr_SetString(PyExc_Exception, "cannot read IGES file");
return 0;
}
@ -385,8 +401,8 @@ PyObject * importAssembly(PyObject *self, PyObject *args)
return 0;
}
Import::ImportOCAFAssembly ocaf(hDoc, pcDoc, file.fileNamePure());
ocaf.loadShapes();
Import::ImportOCAFAssembly ocaf(hDoc, pcDoc, file.fileNamePure(),target);
ocaf.loadAssembly();
pcDoc->recompute();
}
@ -400,6 +416,226 @@ PyObject * importAssembly(PyObject *self, PyObject *args)
Py_Return;
}
static PyObject * importer(PyObject *self, PyObject *args)
{
char* Name;
char* DocName=0;
if (!PyArg_ParseTuple(args, "et|s","utf-8",&Name,&DocName))
return NULL;
std::string Utf8Name = std::string(Name);
PyMem_Free(Name);
std::string name8bit = Part::encodeFilename(Utf8Name);
PY_TRY {
//Base::Console().Log("Insert in Part with %s",Name);
Base::FileInfo file(Utf8Name.c_str());
App::Document *pcDoc = 0;
if (DocName) {
pcDoc = App::GetApplication().getDocument(DocName);
}
if (!pcDoc) {
pcDoc = App::GetApplication().newDocument("Unnamed");
}
Handle(XCAFApp_Application) hApp = XCAFApp_Application::GetApplication();
Handle(TDocStd_Document) hDoc;
hApp->NewDocument(TCollection_ExtendedString("MDTV-CAF"), hDoc);
if (file.hasExtension("stp") || file.hasExtension("step")) {
try {
STEPCAFControl_Reader aReader;
aReader.SetColorMode(true);
aReader.SetNameMode(true);
aReader.SetLayerMode(true);
if (aReader.ReadFile((Standard_CString)(name8bit.c_str())) != IFSelect_RetDone) {
PyErr_SetString(Base::BaseExceptionFreeCADError, "cannot read STEP file");
return 0;
}
Handle_Message_ProgressIndicator pi = new Part::ProgressIndicator(100);
aReader.Reader().WS()->MapReader()->SetProgress(pi);
pi->NewScope(100, "Reading STEP file...");
pi->Show();
aReader.Transfer(hDoc);
pi->EndScope();
}
catch (OSD_Exception) {
Handle_Standard_Failure e = Standard_Failure::Caught();
Base::Console().Error("%s\n", e->GetMessageString());
Base::Console().Message("Try to load STEP file without colors...\n");
Part::ImportStepParts(pcDoc,Utf8Name.c_str());
pcDoc->recompute();
}
}
else if (file.hasExtension("igs") || file.hasExtension("iges")) {
Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()
.GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Part")->GetGroup("IGES");
try {
IGESControl_Controller::Init();
IGESCAFControl_Reader aReader;
// http://www.opencascade.org/org/forum/thread_20603/?forum=3
aReader.SetReadVisible(hGrp->GetBool("SkipBlankEntities", true)
? Standard_True : Standard_False);
aReader.SetColorMode(true);
aReader.SetNameMode(true);
aReader.SetLayerMode(true);
if (aReader.ReadFile((Standard_CString)(name8bit.c_str())) != IFSelect_RetDone) {
PyErr_SetString(Base::BaseExceptionFreeCADError, "cannot read IGES file");
return 0;
}
Handle_Message_ProgressIndicator pi = new Part::ProgressIndicator(100);
aReader.WS()->MapReader()->SetProgress(pi);
pi->NewScope(100, "Reading IGES file...");
pi->Show();
aReader.Transfer(hDoc);
pi->EndScope();
}
catch (OSD_Exception) {
Handle_Standard_Failure e = Standard_Failure::Caught();
Base::Console().Error("%s\n", e->GetMessageString());
Base::Console().Message("Try to load IGES file without colors...\n");
Part::ImportIgesParts(pcDoc,Utf8Name.c_str());
pcDoc->recompute();
}
}
else {
PyErr_SetString(Base::BaseExceptionFreeCADError, "no supported file format");
return 0;
}
#if 1
Import::ImportOCAF ocaf(hDoc, pcDoc, file.fileNamePure());
ocaf.loadShapes();
#else
Import::ImportXCAF xcaf(hDoc, pcDoc, file.fileNamePure());
xcaf.loadShapes();
#endif
pcDoc->recompute();
}
catch (Standard_Failure) {
Handle_Standard_Failure e = Standard_Failure::Caught();
PyErr_SetString(Base::BaseExceptionFreeCADError, e->GetMessageString());
return 0;
}
PY_CATCH
Py_Return;
}
static PyObject * open(PyObject *self, PyObject *args)
{
return importer(self, args);
}
static PyObject * exporter(PyObject *self, PyObject *args)
{
PyObject* object;
char* Name;
if (!PyArg_ParseTuple(args, "Oet",&object,"utf-8",&Name))
return NULL;
std::string Utf8Name = std::string(Name);
PyMem_Free(Name);
std::string name8bit = Part::encodeFilename(Utf8Name);
PY_TRY {
Handle(XCAFApp_Application) hApp = XCAFApp_Application::GetApplication();
Handle(TDocStd_Document) hDoc;
hApp->NewDocument(TCollection_ExtendedString("MDTV-CAF"), hDoc);
Import::ExportOCAF ocaf(hDoc);
Py::Sequence list(object);
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);
std::vector<App::Color> colors;
ocaf.saveShape(part, colors);
}
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());
ocaf.saveShape(part, colors.getValues());
}
else {
Base::Console().Message("'%s' is not a shape, export will be ignored.\n", obj->Label.getValue());
}
}
}
}
Base::FileInfo file(Utf8Name.c_str());
if (file.hasExtension("stp") || file.hasExtension("step")) {
//Interface_Static::SetCVal("write.step.schema", "AP214IS");
STEPCAFControl_Writer writer;
writer.Transfer(hDoc, STEPControl_AsIs);
// edit STEP header
#if OCC_VERSION_HEX >= 0x060500
APIHeaderSection_MakeHeader makeHeader(writer.ChangeWriter().Model());
#else
APIHeaderSection_MakeHeader makeHeader(writer.Writer().Model());
#endif
Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()
.GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Part")->GetGroup("STEP");
makeHeader.SetName(new TCollection_HAsciiString((const Standard_CString)Utf8Name.c_str()));
makeHeader.SetAuthorValue (1, new TCollection_HAsciiString(hGrp->GetASCII("Author", "Author").c_str()));
makeHeader.SetOrganizationValue (1, new TCollection_HAsciiString(hGrp->GetASCII("Company").c_str()));
makeHeader.SetOriginatingSystem(new TCollection_HAsciiString(App::GetApplication().getExecutableName()));
makeHeader.SetDescriptionValue(1, new TCollection_HAsciiString("FreeCAD Model"));
IFSelect_ReturnStatus ret = writer.Write(name8bit.c_str());
if (ret == IFSelect_RetError || ret == IFSelect_RetFail || ret == IFSelect_RetStop) {
PyErr_Format(PyExc_IOError, "Cannot open file '%s'", Utf8Name.c_str());
return 0;
}
}
else if (file.hasExtension("igs") || file.hasExtension("iges")) {
IGESControl_Controller::Init();
IGESCAFControl_Writer writer;
IGESData_GlobalSection header = writer.Model()->GlobalSection();
header.SetAuthorName(new TCollection_HAsciiString(Interface_Static::CVal("write.iges.header.author")));
header.SetCompanyName(new TCollection_HAsciiString(Interface_Static::CVal("write.iges.header.company")));
header.SetSendName(new TCollection_HAsciiString(Interface_Static::CVal("write.iges.header.product")));
writer.Model()->SetGlobalSection(header);
writer.Transfer(hDoc);
Standard_Boolean ret = writer.Write(name8bit.c_str());
if (!ret) {
PyErr_Format(PyExc_IOError, "Cannot open file '%s'", Utf8Name.c_str());
return 0;
}
}
}
catch (Standard_Failure) {
Handle_Standard_Failure e = Standard_Failure::Caught();
PyErr_SetString(Base::BaseExceptionFreeCADError, e->GetMessageString());
return 0;
}
PY_CATCH
Py_Return;
}
PyObject* initModule()
{
return (new Module)->module().ptr();

View File

@ -64,115 +64,10 @@
#include <Mod/Part/App/ImportStep.h>
#include <Mod/Part/App/encodeFilename.h>
<<<<<<< ba8252ee7a68c3a6f954372590d46fea1c4238da
namespace Import {
class Module : public Py::ExtensionModule<Module>
=======
static PyObject * importAssembly(PyObject *self, PyObject *args)
{
char* Name;
PyObject* TargetObject=0;
if (!PyArg_ParseTuple(args, "s|O",&Name,&TargetObject))
return 0;
PY_TRY {
//Base::Console().Log("Insert in Part with %s",Name);
Base::FileInfo file(Name);
App::Document *pcDoc = 0;
pcDoc = App::GetApplication().getActiveDocument();
if (!pcDoc)
pcDoc = App::GetApplication().newDocument("ImportedAssembly");
Handle(XCAFApp_Application) hApp = XCAFApp_Application::GetApplication();
Handle(TDocStd_Document) hDoc;
hApp->NewDocument(TCollection_ExtendedString("MDTV-CAF"), hDoc);
if (file.hasExtension("stp") || file.hasExtension("step")) {
try {
STEPCAFControl_Reader aReader;
aReader.SetColorMode(true);
aReader.SetNameMode(true);
aReader.SetLayerMode(true);
if (aReader.ReadFile((Standard_CString)Name) != IFSelect_RetDone) {
PyErr_SetString(PyExc_Exception, "cannot read STEP file");
return 0;
}
Handle_Message_ProgressIndicator pi = new Part::ProgressIndicator(100);
aReader.Reader().WS()->MapReader()->SetProgress(pi);
pi->NewScope(100, "Reading STEP file...");
pi->Show();
aReader.Transfer(hDoc);
pi->EndScope();
}
catch (OSD_Exception) {
Handle_Standard_Failure e = Standard_Failure::Caught();
Base::Console().Error("%s\n", e->GetMessageString());
Base::Console().Message("Try to load STEP file without colors...\n");
Part::ImportStepParts(pcDoc,Name);
pcDoc->recompute();
}
}
else if (file.hasExtension("igs") || file.hasExtension("iges")) {
try {
IGESControl_Controller::Init();
Interface_Static::SetIVal("read.surfacecurve.mode",3);
IGESCAFControl_Reader aReader;
aReader.SetColorMode(true);
aReader.SetNameMode(true);
aReader.SetLayerMode(true);
if (aReader.ReadFile((Standard_CString)Name) != IFSelect_RetDone) {
PyErr_SetString(PyExc_Exception, "cannot read IGES file");
return 0;
}
Handle_Message_ProgressIndicator pi = new Part::ProgressIndicator(100);
aReader.WS()->MapReader()->SetProgress(pi);
pi->NewScope(100, "Reading IGES file...");
pi->Show();
aReader.Transfer(hDoc);
pi->EndScope();
}
catch (OSD_Exception) {
Handle_Standard_Failure e = Standard_Failure::Caught();
Base::Console().Error("%s\n", e->GetMessageString());
Base::Console().Message("Try to load IGES file without colors...\n");
Part::ImportIgesParts(pcDoc,Name);
pcDoc->recompute();
}
}
else {
PyErr_SetString(PyExc_Exception, "no supported file format");
return 0;
}
Import::ImportOCAFAssembly ocaf(hDoc, pcDoc, file.fileNamePure());
ocaf.loadShapes();
pcDoc->recompute();
}
catch (Standard_Failure) {
Handle_Standard_Failure e = Standard_Failure::Caught();
PyErr_SetString(PyExc_Exception, e->GetMessageString());
return 0;
}
PY_CATCH
Py_Return;
}
static PyObject * importer(PyObject *self, PyObject *args)
>>>>>>> Open new track for importing Assembly structures with OCSF reader.
{
<<<<<<< 1b2c7a1da1451e3e0f5b8968455de0323c77c7f7
public:
Module() : Py::ExtensionModule<Module>("Import")
{
@ -189,18 +84,51 @@ public:
}
virtual ~Module() {}
=======
char* Name;
PyObject* TargetObjectPy=0;
if (!PyArg_ParseTuple(args, "et|O!","utf-8",&Name,&(App::DocumentObjectPy::Type),&TargetObjectPy))
return 0;
std::string Utf8Name = std::string(Name);
PyMem_Free(Name);
std::string name8bit = Part::encodeFilename(Utf8Name);
PY_TRY {
//Base::Console().Log("Insert in Part with %s",Name);
Base::FileInfo file(name8bit);
App::DocumentObject* target = nullptr;
if(TargetObjectPy)
target = static_cast<App::DocumentObjectPy*>(TargetObjectPy)->getDocumentObjectPtr();
>>>>>>> [Assembly] fixing the commands and some import
private:
Py::Object importer(const Py::Tuple& args)
{
char* Name;
char* DocName=0;
if (!PyArg_ParseTuple(args.ptr(), "et|s","utf-8",&Name,&DocName))
throw Py::Exception();
<<<<<<< 1b2c7a1da1451e3e0f5b8968455de0323c77c7f7
std::string Utf8Name = std::string(Name);
PyMem_Free(Name);
std::string name8bit = Part::encodeFilename(Utf8Name);
=======
if (file.hasExtension("stp") || file.hasExtension("step")) {
try {
STEPCAFControl_Reader aReader;
aReader.SetColorMode(true);
aReader.SetNameMode(true);
aReader.SetLayerMode(true);
if (aReader.ReadFile((Standard_CString)(name8bit.c_str())) != IFSelect_RetDone) {
PyErr_SetString(PyExc_Exception, "cannot read STEP file");
return 0;
}
>>>>>>> [Assembly] fixing the commands and some import
try {
//Base::Console().Log("Insert in Part with %s",Name);
@ -210,6 +138,7 @@ private:
if (DocName) {
pcDoc = App::GetApplication().getDocument(DocName);
}
<<<<<<< 1b2c7a1da1451e3e0f5b8968455de0323c77c7f7
if (!pcDoc) {
pcDoc = App::GetApplication().newDocument("Unnamed");
}
@ -234,6 +163,20 @@ private:
pi->Show();
aReader.Transfer(hDoc);
pi->EndScope();
=======
}
else if (file.hasExtension("igs") || file.hasExtension("iges")) {
try {
IGESControl_Controller::Init();
Interface_Static::SetIVal("read.surfacecurve.mode",3);
IGESCAFControl_Reader aReader;
aReader.SetColorMode(true);
aReader.SetNameMode(true);
aReader.SetLayerMode(true);
if (aReader.ReadFile((Standard_CString)(name8bit.c_str())) != IFSelect_RetDone) {
PyErr_SetString(PyExc_Exception, "cannot read IGES file");
return 0;
>>>>>>> [Assembly] fixing the commands and some import
}
catch (OSD_Exception) {
Handle_Standard_Failure e = Standard_Failure::Caught();
@ -298,7 +241,19 @@ private:
throw Py::RuntimeError(e.what());
}
<<<<<<< 1b2c7a1da1451e3e0f5b8968455de0323c77c7f7
return Py::None();
=======
Import::ImportOCAFAssembly ocaf(hDoc, pcDoc, file.fileNamePure(),target);
ocaf.loadAssembly();
pcDoc->recompute();
}
catch (Standard_Failure) {
Handle_Standard_Failure e = Standard_Failure::Caught();
PyErr_SetString(PyExc_Exception, e->GetMessageString());
return 0;
>>>>>>> [Assembly] fixing the commands and some import
}
Py::Object exporter(const Py::Tuple& args)
{
@ -402,26 +357,112 @@ private:
return Py::None();
}
{"importAssembly" ,importAssembly ,METH_VARARGS,
"importAssembly(FileName,Target) -- Import a Assembly file and creates a Assembly structure."},
};
PyObject * importAssembly(PyObject *self, PyObject *args)
{
char* Name;
PyObject* TargetObject=0;
if (!PyArg_ParseTuple(args, "s|O",&Name,&TargetObject))
return 0;
PY_TRY {
//Base::Console().Log("Insert in Part with %s",Name);
Base::FileInfo file(Name);
App::Document *pcDoc = 0;
pcDoc = App::GetApplication().getActiveDocument();
if (!pcDoc)
pcDoc = App::GetApplication().newDocument("ImportedAssembly");
Handle(XCAFApp_Application) hApp = XCAFApp_Application::GetApplication();
Handle(TDocStd_Document) hDoc;
hApp->NewDocument(TCollection_ExtendedString("MDTV-CAF"), hDoc);
if (file.hasExtension("stp") || file.hasExtension("step")) {
try {
STEPCAFControl_Reader aReader;
aReader.SetColorMode(true);
aReader.SetNameMode(true);
aReader.SetLayerMode(true);
if (aReader.ReadFile((Standard_CString)Name) != IFSelect_RetDone) {
PyErr_SetString(PyExc_Exception, "cannot read STEP file");
return 0;
}
Handle_Message_ProgressIndicator pi = new Part::ProgressIndicator(100);
aReader.Reader().WS()->MapReader()->SetProgress(pi);
pi->NewScope(100, "Reading STEP file...");
pi->Show();
aReader.Transfer(hDoc);
pi->EndScope();
}
catch (OSD_Exception) {
Handle_Standard_Failure e = Standard_Failure::Caught();
Base::Console().Error("%s\n", e->GetMessageString());
Base::Console().Message("Try to load STEP file without colors...\n");
Part::ImportStepParts(pcDoc,Name);
pcDoc->recompute();
}
}
else if (file.hasExtension("igs") || file.hasExtension("iges")) {
try {
IGESControl_Controller::Init();
Interface_Static::SetIVal("read.surfacecurve.mode",3);
IGESCAFControl_Reader aReader;
aReader.SetColorMode(true);
aReader.SetNameMode(true);
aReader.SetLayerMode(true);
if (aReader.ReadFile((Standard_CString)Name) != IFSelect_RetDone) {
PyErr_SetString(PyExc_Exception, "cannot read IGES file");
return 0;
}
Handle_Message_ProgressIndicator pi = new Part::ProgressIndicator(100);
aReader.WS()->MapReader()->SetProgress(pi);
pi->NewScope(100, "Reading IGES file...");
pi->Show();
aReader.Transfer(hDoc);
pi->EndScope();
}
catch (OSD_Exception) {
Handle_Standard_Failure e = Standard_Failure::Caught();
Base::Console().Error("%s\n", e->GetMessageString());
Base::Console().Message("Try to load IGES file without colors...\n");
Part::ImportIgesParts(pcDoc,Name);
pcDoc->recompute();
}
}
else {
PyErr_SetString(PyExc_Exception, "no supported file format");
return 0;
}
Import::ImportOCAFAssembly ocaf(hDoc, pcDoc, file.fileNamePure());
ocaf.loadShapes();
pcDoc->recompute();
}
catch (Standard_Failure) {
Handle_Standard_Failure e = Standard_Failure::Caught();
PyErr_SetString(PyExc_Exception, e->GetMessageString());
return 0;
}
PY_CATCH
Py_Return;
}
PyObject* initModule()
{
return (new Module)->module().ptr();
}
<<<<<<< ba8252ee7a68c3a6f954372590d46fea1c4238da
} // namespace Import
=======
/* registration table */
struct PyMethodDef Import_Import_methods[] = {
{"open" ,open ,METH_VARARGS,
"open(string) -- Open the file and create a new document."},
{"insert" ,importer ,METH_VARARGS,
"insert(string,string) -- Insert the file into the given document."},
{"export" ,exporter ,METH_VARARGS,
"export(list,string) -- Export a list of objects into a single file."},
{"importAssembly" ,importAssembly ,METH_VARARGS,
"importAssembly(FileName,Target) -- Import a Assembly file and creates a Assembly structure."},
{NULL, NULL} /* end of table marker */
};
>>>>>>> Open new track for importing Assembly structures with OCSF reader.

View File

@ -79,8 +79,11 @@
using namespace Import;
ImportOCAFAssembly::ImportOCAFAssembly(Handle_TDocStd_Document h, App::Document* d, const std::string& name)
: pDoc(h), doc(d), default_name(name)
ImportOCAFAssembly::ImportOCAFAssembly(Handle_TDocStd_Document h, App::Document* d, const std::string& name, App::DocumentObject *target)
: pDoc(h),
doc(d),
default_name(name),
targetObj(target)
{
aShapeTool = XCAFDoc_DocumentTool::ShapeTool (pDoc->Main());
aColorTool = XCAFDoc_DocumentTool::ColorTool(pDoc->Main());
@ -96,6 +99,47 @@ void ImportOCAFAssembly::loadShapes()
loadShapes(pDoc->Main(), TopLoc_Location(), default_name, "", false,0);
}
void ImportOCAFAssembly::loadAssembly()
{
myRefShapes.clear();
loadShapes(pDoc->Main(), TopLoc_Location(), default_name, "", false,0);
}
std::string ImportOCAFAssembly::getName(const TDF_Label& label)
{
Handle(TDataStd_Name) name;
std::string part_name;
if (label.FindAttribute(TDataStd_Name::GetID(),name)) {
TCollection_ExtendedString extstr = name->Get();
char* str = new char[extstr.LengthOfCString()+1];
extstr.ToUTF8CString(str);
part_name = str;
delete [] str;
return part_name;
//if (part_name.empty()) {
// return "";
//}
//else {
// bool ws=true;
// for (std::string::iterator it = part_name.begin(); it != part_name.end(); ++it) {
// if (*it != ' ') {
// ws = false;
// break;
// }
// }
// if (ws)
// part_name = defaultname;
//}
}
return "";
}
void ImportOCAFAssembly::loadShapes(const TDF_Label& label, const TopLoc_Location& loc, const std::string& defaultname, const std::string& assembly, bool isRef, int dep)
{
int hash = 0;
@ -146,7 +190,7 @@ void ImportOCAFAssembly::loadShapes(const TDF_Label& label, const TopLoc_Locatio
std::stringstream str;
Base::Console().Message("H:%-9d \tN:%-30s \tT:%d \tA:%d \tS:%d \tC:%d \tSS:%d \tF:%d \tR:%d \tC:%d \tSS:%d\tTrf:%s-- %d \n",
Base::Console().Log("H:%-9d \tN:%-30s \tTop:%d, Asm:%d, Shape:%d, Compound:%d, Simple:%d, Free:%d, Ref:%d, Component:%d, SubShape:%d\tTrf:%s-- Dep:%d \n",
hash,
part_name.c_str(),
aShapeTool->IsTopLevel(label),
@ -199,18 +243,22 @@ void ImportOCAFAssembly::loadShapes(const TDF_Label& label, const TopLoc_Locatio
void ImportOCAFAssembly::createShape(const TDF_Label& label, const TopLoc_Location& loc, const std::string& name)
{
Base::Console().Log("-create Shape\n");
const TopoDS_Shape& aShape = aShapeTool->GetShape(label);
if (!aShape.IsNull() && aShape.ShapeType() == TopAbs_COMPOUND) {
TopExp_Explorer xp;
int ctSolids = 0, ctShells = 0;
for (xp.Init(aShape, TopAbs_SOLID); xp.More(); xp.Next(), ctSolids++)
{
createShape(xp.Current(), loc, name);
}
for (xp.Init(aShape, TopAbs_SHELL, TopAbs_SOLID); xp.More(); xp.Next(), ctShells++)
{
createShape(xp.Current(), loc, name);
}
if (ctSolids > 0 || ctShells > 0)
return;
}
createShape(aShape, loc, name);
}
@ -274,285 +322,4 @@ void ImportOCAFAssembly::createShape(const TopoDS_Shape& aShape, const TopLoc_Lo
}
}
// ----------------------------------------------------------------------------
ExportOCAFAssembly::ExportOCAFAssembly(Handle_TDocStd_Document h)
: pDoc(h)
{
aShapeTool = XCAFDoc_DocumentTool::ShapeTool(pDoc->Main());
aColorTool = XCAFDoc_DocumentTool::ColorTool(pDoc->Main());
rootLabel = TDF_TagSource::NewChild(pDoc->Main());
}
void ExportOCAFAssembly::saveShape(Part::Feature* part, const std::vector<App::Color>& colors)
{
const TopoDS_Shape& shape = part->Shape.getValue();
if (shape.IsNull())
return;
// Add shape and name
//TDF_Label shapeLabel = hShapeTool->AddShape(shape, Standard_False);
TDF_Label shapeLabel= TDF_TagSource::NewChild(rootLabel);
#if OCC_VERSION_HEX >= 0x060500
TDataXtd_Shape::Set(shapeLabel, shape);
#else
TDataStd_Shape::Set(shapeLabel, shape);
#endif
TDataStd_Name::Set(shapeLabel, TCollection_ExtendedString(part->Label.getValue(), 1));
// Add color information
Quantity_Color col;
std::set<int> face_index;
TopTools_IndexedMapOfShape faces;
TopExp_Explorer xp(shape,TopAbs_FACE);
while (xp.More()) {
face_index.insert(faces.Add(xp.Current()));
xp.Next();
}
// define color per face?
if (colors.size() == face_index.size()) {
xp.Init(shape,TopAbs_FACE);
while (xp.More()) {
int index = faces.FindIndex(xp.Current());
if (face_index.find(index) != face_index.end()) {
face_index.erase(index);
TDF_Label faceLabel= TDF_TagSource::NewChild(shapeLabel);
#if OCC_VERSION_HEX >= 0x060500
TDataXtd_Shape::Set(faceLabel, xp.Current());
#else
TDataStd_Shape::Set(faceLabel, xp.Current());
#endif
const App::Color& color = colors[index-1];
Quantity_Parameter mat[3];
mat[0] = color.r;
mat[1] = color.g;
mat[2] = color.b;
col.SetValues(mat[0],mat[1],mat[2],Quantity_TOC_RGB);
aColorTool->SetColor(faceLabel, col, XCAFDoc_ColorSurf);
}
xp.Next();
}
}
else if (!colors.empty()) {
App::Color color = colors.front();
Quantity_Parameter mat[3];
mat[0] = color.r;
mat[1] = color.g;
mat[2] = color.b;
col.SetValues(mat[0],mat[1],mat[2],Quantity_TOC_RGB);
aColorTool->SetColor(shapeLabel, col, XCAFDoc_ColorGen);
}
}
// ----------------------------------------------------------------------------
ImportXCAFAssembly::ImportXCAFAssembly(Handle_TDocStd_Document h, App::Document* d, const std::string& name)
: hdoc(h), doc(d), default_name(name)
{
aShapeTool = XCAFDoc_DocumentTool::ShapeTool (hdoc->Main());
hColors = XCAFDoc_DocumentTool::ColorTool(hdoc->Main());
}
ImportXCAFAssembly::~ImportXCAFAssembly()
{
}
void ImportXCAFAssembly::loadShapes()
{
// collect sequence of labels to display
TDF_LabelSequence shapeLabels, colorLabels;
aShapeTool->GetFreeShapes (shapeLabels);
hColors->GetColors(colorLabels);
// set presentations and show
for (Standard_Integer i=1; i <= shapeLabels.Length(); i++ ) {
// get the shapes and attributes
const TDF_Label& label = shapeLabels.Value(i);
loadShapes(label);
}
std::map<Standard_Integer, TopoDS_Shape>::iterator it;
// go through solids
for (it = mySolids.begin(); it != mySolids.end(); ++it) {
createShape(it->second, true, true);
}
// go through shells
for (it = myShells.begin(); it != myShells.end(); ++it) {
createShape(it->second, true, true);
}
// go through compounds
for (it = myCompds.begin(); it != myCompds.end(); ++it) {
createShape(it->second, true, true);
}
// do the rest
if (!myShapes.empty()) {
BRep_Builder builder;
TopoDS_Compound comp;
builder.MakeCompound(comp);
for (it = myShapes.begin(); it != myShapes.end(); ++it) {
builder.Add(comp, it->second);
}
createShape(comp, true, false);
}
}
void ImportXCAFAssembly::createShape(const TopoDS_Shape& shape, bool perface, bool setname) const
{
Part::Feature* part;
part = static_cast<Part::Feature*>(doc->addObject("Part::Feature", default_name.c_str()));
part->Shape.setValue(shape);
std::map<Standard_Integer, Quantity_Color>::const_iterator jt;
jt = myColorMap.find(shape.HashCode(INT_MAX));
App::Color partColor(0.8f,0.8f,0.8f);
#if 0//TODO
Gui::ViewProvider* vp = Gui::Application::Instance->getViewProvider(part);
if (vp && vp->isDerivedFrom(PartGui::ViewProviderPart::getClassTypeId())) {
if (jt != myColorMap.end()) {
App::Color color;
color.r = jt->second.Red();
color.g = jt->second.Green();
color.b = jt->second.Blue();
static_cast<PartGui::ViewProviderPart*>(vp)->ShapeColor.setValue(color);
}
partColor = static_cast<PartGui::ViewProviderPart*>(vp)->ShapeColor.getValue();
}
#endif
// set label name if defined
if (setname && !myNameMap.empty()) {
std::map<Standard_Integer, std::string>::const_iterator jt;
jt = myNameMap.find(shape.HashCode(INT_MAX));
if (jt != myNameMap.end()) {
part->Label.setValue(jt->second);
}
}
// check for colors per face
if (perface && !myColorMap.empty()) {
TopTools_IndexedMapOfShape faces;
TopExp_Explorer xp(shape,TopAbs_FACE);
while (xp.More()) {
faces.Add(xp.Current());
xp.Next();
}
bool found_face_color = false;
std::vector<App::Color> faceColors;
faceColors.resize(faces.Extent(), partColor);
xp.Init(shape,TopAbs_FACE);
while (xp.More()) {
jt = myColorMap.find(xp.Current().HashCode(INT_MAX));
if (jt != myColorMap.end()) {
int index = faces.FindIndex(xp.Current());
App::Color color;
color.r = (float)jt->second.Red();
color.g = (float)jt->second.Green();
color.b = (float)jt->second.Blue();
faceColors[index-1] = color;
found_face_color = true;
}
xp.Next();
}
if (found_face_color) {
#if 0//TODO
Gui::ViewProvider* vp = Gui::Application::Instance->getViewProvider(part);
if (vp && vp->isDerivedFrom(PartGui::ViewProviderPartExt::getClassTypeId())) {
static_cast<PartGui::ViewProviderPartExt*>(vp)->DiffuseColor.setValues(faceColors);
}
#endif
}
}
}
void ImportXCAFAssembly::loadShapes(const TDF_Label& label)
{
TopoDS_Shape aShape;
if (aShapeTool->GetShape(label,aShape)) {
//if (aShapeTool->IsReference(label)) {
// TDF_Label reflabel;
// if (aShapeTool->GetReferredShape(label, reflabel)) {
// loadShapes(reflabel);
// }
//}
if (aShapeTool->IsTopLevel(label)) {
int ctSolids = 0, ctShells = 0, ctComps = 0;
// add the shapes
TopExp_Explorer xp;
for (xp.Init(aShape, TopAbs_SOLID); xp.More(); xp.Next(), ctSolids++)
this->mySolids[xp.Current().HashCode(INT_MAX)] = (xp.Current());
for (xp.Init(aShape, TopAbs_SHELL, TopAbs_SOLID); xp.More(); xp.Next(), ctShells++)
this->myShells[xp.Current().HashCode(INT_MAX)] = (xp.Current());
// if no solids and no shells were found then go for compounds
if (ctSolids == 0 && ctShells == 0) {
for (xp.Init(aShape, TopAbs_COMPOUND); xp.More(); xp.Next(), ctComps++)
this->myCompds[xp.Current().HashCode(INT_MAX)] = (xp.Current());
}
if (ctComps == 0) {
for (xp.Init(aShape, TopAbs_FACE, TopAbs_SHELL); xp.More(); xp.Next())
this->myShapes[xp.Current().HashCode(INT_MAX)] = (xp.Current());
for (xp.Init(aShape, TopAbs_WIRE, TopAbs_FACE); xp.More(); xp.Next())
this->myShapes[xp.Current().HashCode(INT_MAX)] = (xp.Current());
for (xp.Init(aShape, TopAbs_EDGE, TopAbs_WIRE); xp.More(); xp.Next())
this->myShapes[xp.Current().HashCode(INT_MAX)] = (xp.Current());
for (xp.Init(aShape, TopAbs_VERTEX, TopAbs_EDGE); xp.More(); xp.Next())
this->myShapes[xp.Current().HashCode(INT_MAX)] = (xp.Current());
}
}
// getting color
Quantity_Color col;
if (hColors->GetColor(label, XCAFDoc_ColorGen, col) ||
hColors->GetColor(label, XCAFDoc_ColorSurf, col) ||
hColors->GetColor(label, XCAFDoc_ColorCurv, col)) {
// add defined color
myColorMap[aShape.HashCode(INT_MAX)] = col;
}
else {
// http://www.opencascade.org/org/forum/thread_17107/
TopoDS_Iterator it;
for (it.Initialize(aShape);it.More(); it.Next()) {
if (hColors->GetColor(it.Value(), XCAFDoc_ColorGen, col) ||
hColors->GetColor(it.Value(), XCAFDoc_ColorSurf, col) ||
hColors->GetColor(it.Value(), XCAFDoc_ColorCurv, col)) {
// add defined color
myColorMap[it.Value().HashCode(INT_MAX)] = col;
}
}
}
// getting names
Handle(TDataStd_Name) name;
if (label.FindAttribute(TDataStd_Name::GetID(),name)) {
TCollection_ExtendedString extstr = name->Get();
char* str = new char[extstr.LengthOfCString()+1];
extstr.ToUTF8CString(str);
std::string label(str);
if (!label.empty())
myNameMap[aShape.HashCode(INT_MAX)] = label;
delete [] str;
}
#if 0
// http://www.opencascade.org/org/forum/thread_15174/
if (aShapeTool->IsAssembly(label)) {
TDF_LabelSequence shapeLabels;
aShapeTool->GetComponents(label, shapeLabels);
Standard_Integer nbShapes = shapeLabels.Length();
for (Standard_Integer i = 1; i <= nbShapes; i++) {
loadShapes(shapeLabels.Value(i));
}
}
#endif
if (label.HasChild()) {
TDF_ChildIterator it;
for (it.Initialize(label); it.More(); it.Next()) {
loadShapes(it.Value());
}
}
}
}

View File

@ -52,9 +52,15 @@ namespace Import {
class ImportExport ImportOCAFAssembly
{
public:
ImportOCAFAssembly(Handle_TDocStd_Document h, App::Document* d, const std::string& name);
ImportOCAFAssembly(Handle_TDocStd_Document h, App::Document* d, const std::string& name, App::DocumentObject *target);
virtual ~ImportOCAFAssembly();
void loadShapes();
void loadAssembly();
protected:
std::string getName(const TDF_Label& label);
App::DocumentObject *targetObj;
private:
void loadShapes(const TDF_Label& label, const TopLoc_Location&, const std::string& partname, const std::string& assembly, bool isRef, int dep);
@ -72,46 +78,7 @@ private:
static const int HashUpper = INT_MAX;
};
class ImportExport ExportOCAFAssembly
{
public:
ExportOCAFAssembly(Handle_TDocStd_Document h);
void saveShape(Part::Feature* part, const std::vector<App::Color>&);
private:
Handle_TDocStd_Document pDoc;
Handle_XCAFDoc_ShapeTool aShapeTool;
Handle_XCAFDoc_ColorTool aColorTool;
TDF_Label rootLabel;
};
class ImportXCAFAssembly
{
public:
ImportXCAFAssembly(Handle_TDocStd_Document h, App::Document* d, const std::string& name);
virtual ~ImportXCAFAssembly();
void loadShapes();
private:
void createShape(const TopoDS_Shape& shape, bool perface=false, bool setname=false) const;
void loadShapes(const TDF_Label& label);
virtual void applyColors(Part::Feature*, const std::vector<App::Color>&){}
private:
Handle_TDocStd_Document hdoc;
App::Document* doc;
Handle_XCAFDoc_ShapeTool aShapeTool;
Handle_XCAFDoc_ColorTool hColors;
std::string default_name;
std::map<Standard_Integer, TopoDS_Shape> mySolids;
std::map<Standard_Integer, TopoDS_Shape> myShells;
std::map<Standard_Integer, TopoDS_Shape> myCompds;
std::map<Standard_Integer, TopoDS_Shape> myShapes;
std::map<Standard_Integer, Quantity_Color> myColorMap;
std::map<Standard_Integer, std::string> myNameMap;
};
}
} // namespace Import {
#endif //IMPORT_ImportOCAFAssembly_H