Exemplo n.º 1
0
void ProfileBased::getUpToFaceFromLinkSub(TopoDS_Face& upToFace,
                                         const App::PropertyLinkSub& refFace)
{
    App::DocumentObject* ref = refFace.getValue();
    std::vector<std::string> subStrings = refFace.getSubValues();

    if (ref == NULL)
        throw Base::ValueError("SketchBased: Up to face: No face selected");

    if (ref->getTypeId().isDerivedFrom(App::Plane::getClassTypeId())) {
        upToFace = TopoDS::Face(makeShapeFromPlane(ref));
        return;
    } else if (ref->getTypeId().isDerivedFrom(PartDesign::Plane::getClassTypeId())) {
        Part::Datum* datum = static_cast<Part::Datum*>(ref);
        upToFace = TopoDS::Face(datum->getShape());
        return;
    }

    if (!ref->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))
        throw Base::TypeError("SketchBased: Up to face: Must be face of a feature");
    Part::TopoShape baseShape = static_cast<Part::Feature*>(ref)->Shape.getShape();

    if (subStrings.empty() || subStrings[0].empty())
        throw Base::ValueError("SketchBased: Up to face: No face selected");
    // TODO: Check for multiple UpToFaces?

    upToFace = TopoDS::Face(baseShape.getSubShape(subStrings[0].c_str()));
    if (upToFace.IsNull())
        throw Base::ValueError("SketchBased: Up to face: Failed to extract face");
}
Exemplo n.º 2
0
App::DocumentObjectExecReturn *DrawViewCollection::execute(void)
{
    if (ScaleType.isValue("Document")) {
        const std::vector<App::DocumentObject *> &views = Views.getValues();
        for(std::vector<App::DocumentObject *>::const_iterator it = views.begin(); it != views.end(); ++it) {
            App::DocumentObject *docObj = *it;
            if(docObj->getTypeId().isDerivedFrom(TechDraw::DrawView::getClassTypeId())) {
                TechDraw::DrawView *view = static_cast<TechDraw::DrawView *>(*it);

                // Set scale factor of each view
                view->ScaleType.setValue("Document");
                view->touch();
            }
        }
    } else if(strcmp(ScaleType.getValueAsString(), "Custom") == 0) {
        // Rebuild the views
        const std::vector<App::DocumentObject *> &views = Views.getValues();
        for(std::vector<App::DocumentObject *>::const_iterator it = views.begin(); it != views.end(); ++it) {
            App::DocumentObject *docObj = *it;
            if(docObj->getTypeId().isDerivedFrom(TechDraw::DrawView::getClassTypeId())) {
                TechDraw::DrawView *view = static_cast<TechDraw::DrawView *>(*it);

                view->ScaleType.setValue("Custom");
                // Set scale factor of each view
                view->Scale.setValue(Scale.getValue());
                view->touch();
            }
        }
    }

    return DrawView::execute();
}
Exemplo n.º 3
0
static PyObject * exporter(PyObject *self, PyObject *args)
{
    PyObject* object;
    char* Name;
    if (!PyArg_ParseTuple(args, "Oet",&object,"utf-8",&Name))
        return NULL;
    std::string EncodedName = std::string(Name);
    PyMem_Free(Name);

    float fTolerance = 0.1f;
    MeshObject global_mesh;

    PY_TRY {
        Py::Sequence list(object);
        Base::Type meshId = Base::Type::fromName("Mesh::Feature");
        Base::Type partId = Base::Type::fromName("Part::Feature");
        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(meshId)) {
                    const MeshObject& mesh = static_cast<Mesh::Feature*>(obj)->Mesh.getValue();
                    MeshCore::MeshKernel kernel = mesh.getKernel();
                    kernel.Transform(mesh.getTransform());
                    if (global_mesh.countFacets() == 0)
                        global_mesh.setKernel(kernel);
                    else
                        global_mesh.addMesh(kernel);
                }
                else if (obj->getTypeId().isDerivedFrom(partId)) {
                    App::Property* shape = obj->getPropertyByName("Shape");
                    Base::Reference<MeshObject> mesh(new MeshObject());
                    if (shape && shape->getTypeId().isDerivedFrom(App::PropertyComplexGeoData::getClassTypeId())) {
                        std::vector<Base::Vector3d> aPoints;
                        std::vector<Data::ComplexGeoData::Facet> aTopo;
                        static_cast<App::PropertyComplexGeoData*>(shape)->getFaces(aPoints, aTopo,fTolerance);
                        mesh->addFacets(aTopo, aPoints);
                        if (global_mesh.countFacets() == 0)
                            global_mesh = *mesh;
                        else
                            global_mesh.addMesh(*mesh);
                    }
                }
                else {
                    Base::Console().Message("'%s' is not a mesh or shape, export will be ignored.\n", obj->Label.getValue());
                }
            }
        }

        // export mesh compound
        global_mesh.save(EncodedName.c_str());
    } PY_CATCH;

    Py_Return;
}
Exemplo n.º 4
0
App::DocumentObjectExecReturn *DrawProjGroup::execute(void)
{
    if (ScaleType.isValue("Automatic")) {

        //Recalculate scale
        double autoScale = calculateAutomaticScale();

        if(std::abs(Scale.getValue() - autoScale) > FLT_EPSILON) {
            // Set this Scale
            Scale.setValue(autoScale);

            //Rebuild the DPGI's
            const std::vector<App::DocumentObject *> &views = Views.getValues();
            for(std::vector<App::DocumentObject *>::const_iterator it = views.begin(); it != views.end(); ++it) {
                App::DocumentObject *docObj = *it;
                if(docObj->getTypeId().isDerivedFrom(DrawProjGroupItem::getClassTypeId())) {
                    DrawProjGroupItem *view = dynamic_cast<DrawProjGroupItem *>(*it);
                    view->ScaleType.setValue("Custom");
                    view->Scale.setValue(autoScale);
                    view->Scale.setStatus(App::Property::ReadOnly,true);
                    view->touch();
                }
            }
            resetPositions();
        }
    }

    // recalculate positions for children
    if (Views.getSize()) {
        distributeProjections();
    }
    //touch();

    return DrawViewCollection::execute();
}
Exemplo n.º 5
0
App::DocumentObjectExecReturn* RuledSurface::getShape(const App::PropertyLinkSub& link,
                                                      TopoDS_Shape& shape) const
{
    App::DocumentObject* obj = link.getValue();
    if (!(obj && obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())))
        return new App::DocumentObjectExecReturn("No shape linked.");

    // if no explicit sub-shape is selected use the whole part
    const std::vector<std::string>& element = link.getSubValues();
    if (element.empty()) {
        shape = static_cast<Part::Feature*>(obj)->Shape.getValue();
        return nullptr;
    }
    else if (element.size() != 1) {
        return new App::DocumentObjectExecReturn("Not exactly one sub-shape linked.");
    }

    const Part::TopoShape& part = static_cast<Part::Feature*>(obj)->Shape.getValue();
    if (!part.getShape().IsNull()) {
        if (!element[0].empty()) {
            shape = part.getSubShape(element[0].c_str());
        }
        else {
            // the sub-element is an empty string, so use the whole part
            shape = part.getShape();
        }
    }

    return nullptr;
}
Exemplo n.º 6
0
App::DocumentObjectExecReturn *Revolution::execute(void)
{
    App::DocumentObject* link = Source.getValue();
    if (!link)
        return new App::DocumentObjectExecReturn("No object linked");
    if (!link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))
        return new App::DocumentObjectExecReturn("Linked object is not a Part object");
    Part::Feature *base = static_cast<Part::Feature*>(Source.getValue());

    Base::Vector3d b = Base.getValue();
    Base::Vector3d v = Axis.getValue();
    gp_Pnt pnt(b.x,b.y,b.z);
    gp_Dir dir(v.x,v.y,v.z);
    Standard_Boolean isSolid = Solid.getValue() ? Standard_True : Standard_False;

    try {
        // Now, let's get the TopoDS_Shape
        //TopoDS_Shape revolve = base->Shape.getShape().revolve(gp_Ax1(pnt, dir),
        //    Angle.getValue()/180.0f*M_PI);
        TopoDS_Shape revolve = base->Shape.getShape().revolve(gp_Ax1(pnt, dir),
            Angle.getValue()/180.0f*M_PI,isSolid);
        if (revolve.IsNull())
            return new App::DocumentObjectExecReturn("Resulting shape is null");
        this->Shape.setValue(revolve);
        return App::DocumentObject::StdReturn;
    }
    catch (Standard_Failure) {
        Handle_Standard_Failure e = Standard_Failure::Caught();
        return new App::DocumentObjectExecReturn(e->GetMessageString());
    }
}
Exemplo n.º 7
0
    Py::Object write(const Py::Tuple& args)
    {
        char* Name;
        PyObject* pObj;
        if (!PyArg_ParseTuple(args.ptr(), "Oet",&pObj,"utf-8",&Name))
            throw Py::Exception();
        std::string EncodedName = std::string(Name);
        PyMem_Free(Name);
        Base::FileInfo file(EncodedName.c_str());
        
        if (PyObject_TypeCheck(pObj, &(App::DocumentObjectPy::Type))) {
            App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(pObj)->getDocumentObjectPtr();
            if (obj->getTypeId().isDerivedFrom(Base::Type::fromName("Path::Feature"))) {
                const Toolpath& path = static_cast<Path::Feature*>(obj)->Path.getValue();
                std::string gcode = path.toGCode();    
                std::ofstream ofile(EncodedName.c_str());
                ofile << gcode;
                ofile.close();
            }
            else {
                throw Py::RuntimeError("The given file is not a path");
            }
        }

        return Py::None();
    }
Exemplo n.º 8
0
    Py::Object exporter(const Py::Tuple& args)
    {
        PyObject* object;
        char* Name;
        if (!PyArg_ParseTuple(args.ptr(), "Oet",&object,"utf-8",&Name))
            throw Py::Exception();

        std::string EncodedName = std::string(Name);
        PyMem_Free(Name);

        Py::Sequence list(object);
        Base::Type meshId = Base::Type::fromName("Fem::FemMeshObject");
        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(meshId)) {
                    static_cast<FemMeshObject*>(obj)->FemMesh.getValue().write(EncodedName.c_str());
                    break;
                }
            }
        }

        return Py::None();
    }
Exemplo n.º 9
0
void TaskGrooveParameters::apply()
{
    App::DocumentObject* groove = GrooveView->getObject();
    std::string name = groove->getNameInDocument();

    // retrieve sketch and its support object
    App::DocumentObject* sketch = 0;
    App::DocumentObject* support = 0;
    if (groove->getTypeId().isDerivedFrom(PartDesign::Groove::getClassTypeId())) {
        sketch = static_cast<PartDesign::Groove*>(groove)->Sketch.getValue<Sketcher::SketchObject*>();
        if (sketch) {
            support = static_cast<Sketcher::SketchObject*>(sketch)->Support.getValue();
        }
    }

    //Gui::Command::openCommand("Groove changed");
    ui->grooveAngle->apply();
    std::string axis = getReferenceAxis().toStdString();
    Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.ReferenceAxis = %s",name.c_str(),axis.c_str());
    Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.Midplane = %i",name.c_str(), getMidplane() ? 1 : 0);
    Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.Reversed = %i",name.c_str(), getReversed() ? 1 : 0);
    Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.recompute()");
    if (groove->isValid()) {
        if (sketch)
            Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().hide(\"%s\")",sketch->getNameInDocument());
        if (support)
            Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().hide(\"%s\")",support->getNameInDocument());
    }
    Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().resetEdit()");
    Gui::Command::commitCommand();
 }
App::DocumentObjectExecReturn *Mirroring::execute(void)
{
    App::DocumentObject* link = Source.getValue();
    if (!link)
        return new App::DocumentObjectExecReturn("No object linked");
    if (!link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))
        return new App::DocumentObjectExecReturn("Linked object is not a Part object");
    Part::Feature *source = static_cast<Part::Feature*>(link);
    Base::Vector3f base = Base.getValue();
    Base::Vector3f norm = Normal.getValue();

    try {
        const TopoDS_Shape& shape = source->Shape.getValue();
        gp_Ax2 ax2(gp_Pnt(base.x,base.y,base.z), gp_Dir(norm.x,norm.y,norm.z));
        gp_Trsf mat;
        mat.SetMirror(ax2);
        TopLoc_Location loc = shape.Location();
        gp_Trsf placement = loc.Transformation();
        mat = placement * mat;
        BRepBuilderAPI_Transform mkTrf(shape, mat);
        this->Shape.setValue(mkTrf.Shape());
        return App::DocumentObject::StdReturn;
    }
    catch (Standard_Failure) {
        Handle_Standard_Failure e = Standard_Failure::Caught();
        return new App::DocumentObjectExecReturn(e->GetMessageString());
    }
}
Exemplo n.º 11
0
TopoDS_Shape ProfileBased::getVerifiedFace(bool silent) const {

    App::DocumentObject* result = Profile.getValue();
    const char* err = nullptr;

    if (!result) {
        err = "No profile linked";
    } else {
        if (result->getTypeId().isDerivedFrom(Part::Part2DObject::getClassTypeId())) {
            
            auto wires = getProfileWires();
            return Part::FaceMakerCheese::makeFace(wires);
        }
        else if(result->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
            if(Profile.getSubValues().empty())
                err = "Linked object has no subshape specified";
            else {
                
                const Part::TopoShape& shape = Profile.getValue<Part::Feature*>()->Shape.getShape();
                TopoDS_Shape sub = shape.getSubShape(Profile.getSubValues()[0].c_str());
                if(sub.ShapeType() == TopAbs_FACE) 
                    return TopoDS::Face(sub);
                else if(sub.ShapeType() == TopAbs_WIRE) {
                
                    auto wire = TopoDS::Wire(sub);
                    if(!wire.Closed())
                        err = "Linked wire is not closed";
                    else {
                        BRepBuilderAPI_MakeFace mk(wire);
                        mk.Build();
                        return TopoDS::Face(mk.Shape());
                    }                        
                }
                else 
                    err = "Linked Subshape cannot be used";
            }
        }
        else 
            err = "Linked object is neither Sketch, Part2DObject or Part::Feature";
    }

    if (!silent && err) {
        throw Base::RuntimeError (err);
    }

    return TopoDS_Face();
}
Exemplo n.º 12
0
void DlgFilletEdges::on_shapeObject_activated(int index)
{
    d->object = 0;
    QStandardItemModel *model = qobject_cast<QStandardItemModel*>(ui->treeView->model());
    model->removeRows(0, model->rowCount());

    QByteArray name = ui->shapeObject->itemData(index).toByteArray();
    App::Document* doc = App::GetApplication().getActiveDocument();
    if (!doc)
        return;
    App::DocumentObject* part = doc->getObject((const char*)name);
    if (part && part->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
        d->object = part;
        TopoDS_Shape myShape = static_cast<Part::Feature*>(part)->Shape.getValue();
        // build up map edge->face
        TopTools_IndexedDataMapOfShapeListOfShape edge2Face;
        TopExp::MapShapesAndAncestors(myShape, TopAbs_EDGE, TopAbs_FACE, edge2Face);
        TopTools_IndexedMapOfShape mapOfShape;
        TopExp::MapShapes(myShape, TopAbs_EDGE, mapOfShape);

        // populate the model
        d->edge_ids.clear();
        for (int i=1; i<= edge2Face.Extent(); ++i) {
            // set the index value as user data to use it in accept()
            const TopTools_ListOfShape& los = edge2Face.FindFromIndex(i);
            if (los.Extent() == 2) {
                // set the index value as user data to use it in accept()
                const TopoDS_Shape& edge = edge2Face.FindKey(i);
                // Now check also the continuity to only allow C0-continious
                // faces
                const TopoDS_Shape& face1 = los.First();
                const TopoDS_Shape& face2 = los.Last();
                GeomAbs_Shape cont = BRep_Tool::Continuity(TopoDS::Edge(edge),
                                                           TopoDS::Face(face1),
                                                           TopoDS::Face(face2));
                if (cont == GeomAbs_C0) {
                    int id = mapOfShape.FindIndex(edge);
                    d->edge_ids.push_back(id);
                }
            }
        }

        model->insertRows(0, d->edge_ids.size());
        int index = 0;
        for (std::vector<int>::iterator it = d->edge_ids.begin(); it != d->edge_ids.end(); ++it) {
            model->setData(model->index(index, 0), QVariant(tr("Edge%1").arg(*it)));
            model->setData(model->index(index, 0), QVariant(*it), Qt::UserRole);
            model->setData(model->index(index, 1), QVariant(QLocale::system().toString(1.0,'f',2)));
            model->setData(model->index(index, 2), QVariant(QLocale::system().toString(1.0,'f',2)));
            std::stringstream element;
            element << "Edge" << *it;
            if (Gui::Selection().isSelected(part, element.str().c_str()))
                model->setData(model->index(index, 0), Qt::Checked, Qt::CheckStateRole);
            else
                model->setData(model->index(index, 0), Qt::Unchecked, Qt::CheckStateRole);
            index++;
        }
    }
}
Part::Part2DObject* SketchBased::getVerifiedSketch() const {
    App::DocumentObject* result = Sketch.getValue();
    if (!result)
        throw Base::Exception("No sketch linked");
    if (!result->getTypeId().isDerivedFrom(Part::Part2DObject::getClassTypeId()))
        throw Base::Exception("Linked object is not a Sketch or Part2DObject");
    return static_cast<Part::Part2DObject*>(result);
}
Exemplo n.º 14
0
App::DocumentObjectExecReturn *Chamfer::execute(void)
{
    App::DocumentObject* link = Base.getValue();
    if (!link)
        return new App::DocumentObjectExecReturn("No object linked");
    if (!link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))
        return new App::DocumentObjectExecReturn("Linked object is not a Part object");
    Part::Feature *base = static_cast<Part::Feature*>(Base.getValue());
    const Part::TopoShape& TopShape = base->Shape.getShape();
    if (TopShape._Shape.IsNull())
        return new App::DocumentObjectExecReturn("Cannot chamfer invalid shape");

    const std::vector<std::string>& SubVals = Base.getSubValuesStartsWith("Edge");
    if (SubVals.size() == 0)
        return new App::DocumentObjectExecReturn("No edges specified");

    double size = Size.getValue();

    this->positionByBase();
    // create an untransformed copy of the base shape
    Part::TopoShape baseShape(TopShape);
    baseShape.setTransform(Base::Matrix4D());
    try {
        BRepFilletAPI_MakeChamfer mkChamfer(baseShape._Shape);

        TopTools_IndexedMapOfShape mapOfEdges;
        TopTools_IndexedDataMapOfShapeListOfShape mapEdgeFace;
        TopExp::MapShapesAndAncestors(baseShape._Shape, TopAbs_EDGE, TopAbs_FACE, mapEdgeFace);
        TopExp::MapShapes(baseShape._Shape, TopAbs_EDGE, mapOfEdges);

        for (std::vector<std::string>::const_iterator it=SubVals.begin(); it != SubVals.end(); ++it) {
            TopoDS_Edge edge = TopoDS::Edge(baseShape.getSubShape(it->c_str()));
            const TopoDS_Face& face = TopoDS::Face(mapEdgeFace.FindFromKey(edge).First());
            mkChamfer.Add(size, edge, face);
        }

        mkChamfer.Build();
        if (!mkChamfer.IsDone())
            return new App::DocumentObjectExecReturn("Failed to create chamfer");

        TopoDS_Shape shape = mkChamfer.Shape();
        if (shape.IsNull())
            return new App::DocumentObjectExecReturn("Resulting shape is null");

        TopTools_ListOfShape aLarg;
        aLarg.Append(baseShape._Shape);
        if (!BRepAlgo::IsValid(aLarg, shape, Standard_False, Standard_False)) {
            return new App::DocumentObjectExecReturn("Resulting shape is invalid");
        }

        this->Shape.setValue(shape);
        return App::DocumentObject::StdReturn;
    }
    catch (Standard_Failure) {
        Handle_Standard_Failure e = Standard_Failure::Caught();
        return new App::DocumentObjectExecReturn(e->GetMessageString());
    }
}
void DlgEvaluateMeshImp::slotCreatedObject(const App::DocumentObject& Obj)
{
    // add new mesh object to the list
    if (Obj.getTypeId().isDerivedFrom(Mesh::Feature::getClassTypeId())) {
        QString label = QString::fromUtf8(Obj.Label.getValue());
        QString name = QString::fromAscii(Obj.getNameInDocument());
        meshNameButton->addItem(label, name);
    }
}
Exemplo n.º 16
0
void CmdPartDesignMoveTip::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    std::vector<App::DocumentObject*> features = getSelection().getObjectsOfType(
            Part::Feature::getClassTypeId() );
    App::DocumentObject* selFeature;
    PartDesign::Body* body= nullptr;

    if ( features.size() == 1 ) {
        selFeature = features.front();
        if ( selFeature->getTypeId().isDerivedFrom ( PartDesign::Body::getClassTypeId() ) ) {
            body = static_cast<PartDesign::Body *> ( selFeature );
        } else {
            body = PartDesignGui::getBodyFor ( selFeature, /* messageIfNot =*/ false );
        }
    } else {
        selFeature = nullptr;
    }

    if (!selFeature) {
        QMessageBox::warning (0, QObject::tr( "Selection error" ),
                QObject::tr( "Select exactly one PartDesign feature or a body." ) );
        return;
    } else if (!body) {
        QMessageBox::warning (0, QObject::tr( "Selection error" ),
                QObject::tr( "Couldn't determine a body for the selected feature '%s'.", selFeature->Label.getValue() ) );
        return;
    } else if ( !selFeature->isDerivedFrom(PartDesign::Feature::getClassTypeId () ) &&
            selFeature != body && body->BaseFeature.getValue() != selFeature ) {
        QMessageBox::warning (0, QObject::tr( "Selection error" ),
                QObject::tr( "Only a solid feature can be the tip of a body." ) );
        return;
    }

    App::DocumentObject* oldTip = body->Tip.getValue();
    if (oldTip == selFeature) { // it's not generally an error, so print only a console message
        Base::Console().Message ("%s is already the tip of the body", selFeature->getNameInDocument () );
        return;
    }

    openCommand("Move tip to selected feature");

    if (selFeature == body) {
        doCommand(Doc,"App.activeDocument().%s.Tip = None", body->getNameInDocument());
    } else {
        doCommand(Doc,"App.activeDocument().%s.Tip = App.activeDocument().%s",body->getNameInDocument(),
                selFeature->getNameInDocument());

        // Adjust visibility to show only the Tip feature
        doCommand(Gui,"Gui.activeDocument().show(\"%s\")", selFeature->getNameInDocument());
    }

    // TOOD: Hide all datum features after the Tip feature? But the user might have already hidden some and wants to see
    // others, so we would have to remember their state somehow
    updateActive();
}
const QByteArray TaskSketchBasedParameters::onFaceName(const QString& text)
{
    if (text.length() == 0)
        return QByteArray();

    QStringList parts = text.split(QChar::fromLatin1(':'));
    if (parts.length() < 2)
        parts.push_back(QString::fromLatin1(""));
    // Check whether this is the name of an App::Plane or Part::Datum feature
    App::DocumentObject* obj = vp->getObject()->getDocument()->getObject(parts[0].toLatin1());
    if (obj == NULL)
        return QByteArray();

    PartDesign::Body* activeBody = Gui::Application::Instance->activeView()->getActiveObject<PartDesign::Body*>(PDBODYKEY);
    if (obj->getTypeId().isDerivedFrom(App::Plane::getClassTypeId())) {
        // everything is OK (we assume a Part can only have exactly 3 App::Plane objects located at the base of the feature tree)
        return QByteArray();
    } else if (obj->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId())) {
        if (!activeBody->hasFeature(obj))
            return QByteArray();
        return QByteArray();
    } else {
        // We must expect that "text" is the translation of "Face" followed by an ID.
        QString name;
        QTextStream str(&name);
        str << "^" << tr("Face") << "(\\d+)$";
        QRegExp rx(name);
        if (text.indexOf(rx) < 0) {
            return QByteArray();
        }

        int faceId = rx.cap(1).toInt();
        std::stringstream ss;
        ss << "Face" << faceId;

        std::vector<std::string> upToFaces(1,ss.str());
        PartDesign::ProfileBased* pcSketchBased = static_cast<PartDesign::ProfileBased*>(vp->getObject());
        pcSketchBased->UpToFace.setValue(obj, upToFaces);
        recomputeFeature();

        return QByteArray(ss.str().c_str());
    }
}
Exemplo n.º 18
0
TechDraw::DrawViewPart* DrawViewSection::getBaseDVP()
{
    TechDraw::DrawViewPart* baseDVP = nullptr;
    App::DocumentObject* base = BaseView.getValue();
    if (base != nullptr) {
        if (base->getTypeId().isDerivedFrom(TechDraw::DrawViewPart::getClassTypeId())) {
            baseDVP = static_cast<TechDraw::DrawViewPart*>(base);
        }
    }
    return baseDVP;
}
Part::Feature* SketchBased::getSupport() const {
    // get the support of the Sketch if any
    if (!Sketch.getValue())
        return 0;
    App::DocumentObject* SupportLink = static_cast<Part::Part2DObject*>(Sketch.getValue())->Support.getValue();
    Part::Feature* SupportObject = NULL;
    if (SupportLink && SupportLink->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))
        SupportObject = static_cast<Part::Feature*>(SupportLink);

    return SupportObject;
}
Exemplo n.º 20
0
TechDraw::DrawProjGroupItem* DrawViewSection::getBaseDPGI()
{
    TechDraw::DrawProjGroupItem* baseDPGI = nullptr;
    App::DocumentObject* base = BaseView.getValue();
    if (base != nullptr) {
        if (base->getTypeId().isDerivedFrom(TechDraw::DrawProjGroupItem::getClassTypeId())) {
            baseDPGI = static_cast<TechDraw::DrawProjGroupItem*>(base);
        }
    }
    return baseDPGI;
}
App::DocumentObjectExecReturn *TrajectoryDressUpObject::execute(void)
{
    Robot::Trajectory result;

    App::DocumentObject* link = Source.getValue();
    if (!link)
        return new App::DocumentObjectExecReturn("No object linked");
    if (!link->getTypeId().isDerivedFrom(Robot::TrajectoryObject::getClassTypeId()))
        return new App::DocumentObjectExecReturn("Linked object is not a Trajectory object");

    const std::vector<Waypoint*> &wps = static_cast<Robot::TrajectoryObject*>(link)->Trajectory.getValue().getWaypoints();
    for (std::vector<Waypoint*>::const_iterator it= wps.begin();it!=wps.end();++it) {
        Waypoint wpt = **it;
        if(UseSpeed.getValue())
            wpt.Velocity = Speed.getValue();
        if(UseAcceleration.getValue())
            wpt.Accelaration = Acceleration.getValue();
        switch(ContType.getValue()){
            case 0: break;
            case 1: wpt.Cont = true;break;
            case 2: wpt.Cont = false;break;
            default: assert(0); // must not happen!
        }
        switch(AddType.getValue()){
            // do nothing 
            case 0: break;
            // use orientation  
            case 1:
                wpt.EndPos.setRotation(PosAdd.getValue().getRotation());
                break;
            // add position 
            case 2:
                wpt.EndPos.setPosition(wpt.EndPos.getPosition() + PosAdd.getValue().getPosition());
                break;
            // add orientation 
            case 3:
                wpt.EndPos.setRotation(wpt.EndPos.getRotation() * PosAdd.getValue().getRotation());
                break;
            // add orientation & position 
            case 4:
                wpt.EndPos= wpt.EndPos * PosAdd.getValue();
                break;
            default: assert(0); // must not happen!
        }

        result.addWaypoint(wpt);
    }

    // set the resulting Trajectory to the object
    Trajectory.setValue(result);
    
    return App::DocumentObject::StdReturn;
}
Exemplo n.º 22
0
//*****************************************************************************************************
// Document
//*****************************************************************************************************
void Document::slotNewObject(const App::DocumentObject& Obj)
{
    //Base::Console().Log("Document::slotNewObject() called\n");
    std::string cName = Obj.getViewProviderName();
    if (cName.empty()) {
        // handle document object with no view provider specified
        Base::Console().Log("%s has no view provider specified\n", Obj.getTypeId().getName());
        return;
    }
  
    setModified(true);
    Base::BaseClass* base = static_cast<Base::BaseClass*>(Base::Type::createInstanceByName(cName.c_str(),true));
    if (base) {
        // type not derived from ViewProviderDocumentObject!!!
        assert(base->getTypeId().isDerivedFrom(Gui::ViewProviderDocumentObject::getClassTypeId()));
        ViewProviderDocumentObject *pcProvider = static_cast<ViewProviderDocumentObject*>(base);
        d->_ViewProviderMap[&Obj] = pcProvider;

        try {
            // if succesfully created set the right name and calculate the view
            //FIXME: Consider to change argument of attach() to const pointer
            pcProvider->attach(const_cast<App::DocumentObject*>(&Obj));
            pcProvider->updateView();
            pcProvider->setActiveMode();
        }
        catch(const Base::MemoryException& e){
            Base::Console().Error("Memory exception in '%s' thrown: %s\n",Obj.getNameInDocument(),e.what());
        }
        catch(Base::Exception &e){
            e.ReportException();
        }
#ifndef FC_DEBUG
        catch(...){
            Base::Console().Error("App::Document::_RecomputeFeature(): Unknown exception in Feature \"%s\" thrown\n",Obj.getNameInDocument());
        }
#endif

        std::list<Gui::BaseView*>::iterator vIt;
        // cycling to all views of the document
        for (vIt = d->baseViews.begin();vIt != d->baseViews.end();++vIt) {
            View3DInventor *activeView = dynamic_cast<View3DInventor *>(*vIt);
            if (activeView)
                activeView->getViewer()->addViewProvider(pcProvider);
        }
    
        // adding to the tree
        signalNewObject(*pcProvider);
    }
    else {
        Base::Console().Warning("Gui::Document::slotNewObject() no view provider for the object %s found\n",cName.c_str());
    }
}
Exemplo n.º 23
0
void ViewProviderViewClip::hide(void)
{
    //TODO: not sure that clip members need to be touched when hiding clip group
    App::DocumentObject* obj = getObject();
    if (!obj || obj->isRestoring())
        return;
    if (obj->getTypeId().isDerivedFrom(TechDraw::DrawViewClip::getClassTypeId())) {
        std::vector<App::DocumentObject*> inp = obj->getInList();
        for (std::vector<App::DocumentObject*>::iterator it = inp.begin(); it != inp.end(); ++it)
            (*it)->touch();
    }
    ViewProviderDrawingView::hide();
}
Exemplo n.º 24
0
App::DocumentObjectExecReturn *LuxFeature::execute(void)
{
    std::stringstream result;
    std::string ViewName = getNameInDocument();

    App::DocumentObject* link = Source.getValue();
    if (!link)
        return new App::DocumentObjectExecReturn("No object linked");
    if (!link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))
        return new App::DocumentObjectExecReturn("Linked object is not a Part object");
    TopoDS_Shape shape = static_cast<Part::Feature*>(link)->Shape.getShape().getShape();
    std::string Name(std::string("Lux_")+static_cast<Part::Feature*>(link)->getNameInDocument());
    if (shape.IsNull())
        return new App::DocumentObjectExecReturn("Linked shape object is empty");
    ShapeAnalysis_ShapeContents test;
    test.Clear();
    test.Perform(shape);
    if (test.NbFaces() < 1)
        return new App::DocumentObjectExecReturn("Shape contains no face to render");

    // write a material entry
    // This must not be done in LuxTools::writeShape!
    const App::Color& c = Color.getValue();
    long t = Transparency.getValue();
    if (t == 0) {
        result << "MakeNamedMaterial \"FreeCADMaterial_" << Name << "\"" << endl
               << "    \"color Kd\" [" << c.r << " " << c.g << " " << c.b << "]" << endl
               << "    \"float sigma\" [0.000000000000000]" << endl
               << "    \"string type\" [\"matte\"]" << endl << endl;
    } else {
        float trans = t/100.0f;
        result << "MakeNamedMaterial \"FreeCADMaterial_Base_" << Name << "\"" << endl
               << "    \"color Kd\" [" << c.r << " " << c.g << " " << c.b << "]" << endl
               << "    \"float sigma\" [0.000000000000000]" << endl
               << "    \"string type\" [\"matte\"]" << endl << endl
               << "MakeNamedMaterial \"FreeCADMaterial_Null_" << Name << "\"" << endl
               << "    \"string type\" [\"null\"]" << endl << endl
               << "MakeNamedMaterial \"FreeCADMaterial_" << Name << "\"" << endl
               << "    \"string namedmaterial1\" [\"FreeCADMaterial_Null_" << Name << "\"]" << endl
               << "    \"string namedmaterial2\" [\"FreeCADMaterial_Base_" << Name << "\"]" << endl
               << "    \"float amount\" [" << trans << "]" << endl
               << "    \"string type\" [\"mix\"]" << endl << endl;
    }
    
    LuxTools::writeShape(result,Name.c_str(),shape);
    
    // Apply the resulting fragment
    Result.setValue(result.str().c_str());

    return App::DocumentObject::StdReturn;
}
bool TaskDlgFeatureParameters::accept() {
    App::DocumentObject* feature = vp->getObject();

    try {
        // Iterate over parameter dialogs and apply all parameters from them
        for ( QWidget *wgt : Content ) {
            TaskFeatureParameters *param = qobject_cast<TaskFeatureParameters *> (wgt);
            if(!param)
                continue;
            
            param->saveHistory ();
            param->apply ();
        }
        // Make sure the feature is what we are expecting
        // Should be fine but you never know...
        if ( !feature->getTypeId().isDerivedFrom(PartDesign::Feature::getClassTypeId()) ) {
            throw Base::Exception("Bad object processed in the feature dialog.");
        }

        App::DocumentObject* previous = static_cast<PartDesign::Feature*>(feature)->getBaseObject(/* silent = */ true );

        if (previous) {
            Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().hide(\"%s\")",
                    previous->getNameInDocument());
        }

        Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.recompute()");

        if (!feature->isValid()) {
            throw Base::Exception(vp->getObject()->getStatusString());
        }

        // detach the task panel from the selection to avoid to invoke
        // eventually onAddSelection when the selection changes
        std::vector<QWidget*> subwidgets = getDialogContent();
        for (auto it : subwidgets) {
            TaskSketchBasedParameters* param = qobject_cast<TaskSketchBasedParameters*>(it);
            if (param)
                param->detachSelection();
        }

        Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().resetEdit()");
        Gui::Command::commitCommand();
    } catch (const Base::Exception& e) {
        // Generally the only thing that should fail is feature->isValid() others should be fine
        QMessageBox::warning( 0, tr("Input error"), QString::fromLatin1(e.what()));
        return false;
    }

    return true;
}
/**
 * Extracts the associated view providers of the objects of the associated object group group. 
 */
void ViewProviderDocumentObjectGroup::getViewProviders(std::vector<ViewProviderDocumentObject*>& vp) const
{
    App::DocumentObject* doc = getObject();
    if (doc->getTypeId().isDerivedFrom(App::DocumentObjectGroup::getClassTypeId())) {
        Gui::Document* gd = Application::Instance->getDocument(doc->getDocument());
        App::DocumentObjectGroup* grp = (App::DocumentObjectGroup*)doc;
        std::vector<App::DocumentObject*> obj = grp->getObjects();
        for (std::vector<App::DocumentObject*>::iterator it = obj.begin(); it != obj.end(); ++it) {
            ViewProvider* v = gd->getViewProvider(*it);
            if (v && v->getTypeId().isDerivedFrom(ViewProviderDocumentObject::getClassTypeId()))
                vp.push_back((ViewProviderDocumentObject*)v);
        }
    }
}
Exemplo n.º 27
0
void ViewProviderDatum::attach(App::DocumentObject *obj)
{
    ViewProviderGeometryObject::attach ( obj );

    // TODO remove this field (2015-09-08, Fat-Zer)
    App::DocumentObject* o = getObject();
    if (o->getTypeId() == PartDesign::Plane::getClassTypeId())
        datumType = QObject::tr("Plane");
    else if (o->getTypeId() == PartDesign::Line::getClassTypeId())
        datumType = QObject::tr("Line");
    else if (o->getTypeId() == PartDesign::Point::getClassTypeId())
        datumType = QObject::tr("Point");
    else if (o->getTypeId() == PartDesign::CoordinateSystem::getClassTypeId())
        datumType = QObject::tr("CoordinateSystem");

    SoShapeHints* hints = new SoShapeHints();
    hints->shapeType.setValue(SoShapeHints::UNKNOWN_SHAPE_TYPE);
    hints->vertexOrdering.setValue(SoShapeHints::COUNTERCLOCKWISE);
    SoDrawStyle* fstyle = new SoDrawStyle();
    fstyle->style = SoDrawStyle::FILLED;
    fstyle->lineWidth = 3;
    fstyle->pointSize = 5;
    pPickStyle->style = SoPickStyle::SHAPE;
    SoMaterialBinding* matBinding = new SoMaterialBinding;
    matBinding->value = SoMaterialBinding::OVERALL;

    SoSeparator* sep = new SoSeparator();
    sep->addChild(hints);
    sep->addChild(fstyle);
    sep->addChild(pPickStyle);
    sep->addChild(matBinding);
    sep->addChild(pcShapeMaterial);
    sep->addChild(pShapeSep);

    addDisplayMaskMode(sep, "Base");
}
Exemplo n.º 28
0
App::DocumentObjectExecReturn *Fillet::execute(void)
{
    App::DocumentObject* link = Base.getValue();
    if (!link)
        return new App::DocumentObjectExecReturn("No object linked");
    if (!link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))
        return new App::DocumentObjectExecReturn("Linked object is not a Part object");
    Part::Feature *base = static_cast<Part::Feature*>(Base.getValue());

    try {
#if defined(__GNUC__) && defined (FC_OS_LINUX)
        Base::SignalException se;
#endif
        BRepFilletAPI_MakeFillet mkFillet(base->Shape.getValue());
        TopTools_IndexedMapOfShape mapOfShape;
        TopExp::MapShapes(base->Shape.getValue(), TopAbs_EDGE, mapOfShape);

        std::vector<FilletElement> values = Edges.getValues();
        for (std::vector<FilletElement>::iterator it = values.begin(); it != values.end(); ++it) {
            int id = it->edgeid;
            double radius1 = it->radius1;
            double radius2 = it->radius2;
            const TopoDS_Edge& edge = TopoDS::Edge(mapOfShape.FindKey(id));
            mkFillet.Add(radius1, radius2, edge);
        }

        TopoDS_Shape shape = mkFillet.Shape();
        if (shape.IsNull())
            return new App::DocumentObjectExecReturn("Resulting shape is null");
        ShapeHistory history = buildHistory(mkFillet, TopAbs_FACE, shape, base->Shape.getValue());
        this->Shape.setValue(shape);

        // make sure the 'PropertyShapeHistory' is not safed in undo/redo (#0001889)
        PropertyShapeHistory prop;
        prop.setValue(history);
        prop.setContainer(this);
        prop.touch();

        return App::DocumentObject::StdReturn;
    }
    catch (Standard_Failure) {
        Handle_Standard_Failure e = Standard_Failure::Caught();
        return new App::DocumentObjectExecReturn(e->GetMessageString());
    }
    catch (...) {
        return new App::DocumentObjectExecReturn("A fatal error occurred when making fillets");
    }
}
Exemplo n.º 29
0
App::DocumentObjectExecReturn *DrawViewSpreadsheet::execute(void)
{
    App::DocumentObject* link = Source.getValue();
    std::string scellstart = CellStart.getValue();
    std::string scellend = CellEnd.getValue();
    if (!link)
        return new App::DocumentObjectExecReturn("No spreadsheet linked");
    if (!link->getTypeId().isDerivedFrom(Spreadsheet::Sheet::getClassTypeId()))
        return new App::DocumentObjectExecReturn("The linked object is not a spreadsheet");
    if ( (scellstart.empty()) || (scellend.empty()) )
        return new App::DocumentObjectExecReturn("Empty cell value");

    Symbol.setValue(getSheetImage());

    return TechDraw::DrawView::execute();
}
Exemplo n.º 30
0
App::DocumentObjectExecReturn *Offset2D::execute(void)
{
    App::DocumentObject* source = Source.getValue();
    if (!(source && source->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())))
        return new App::DocumentObjectExecReturn("No source shape linked.");
    double offset = Value.getValue();
    short mode = (short)Mode.getValue();
    short join = (short)Join.getValue();
    bool fill = Fill.getValue();
    bool inter = Intersection.getValue();
    if (mode == 2)
        return new App::DocumentObjectExecReturn("Mode 'Recto-Verso' is not supported for 2D offset.");
    const TopoShape& shape = static_cast<Part::Feature*>(source)->Shape.getShape();
    this->Shape.setValue(shape.makeOffset2D(offset, join, fill, mode == 0, inter));
    return App::DocumentObject::StdReturn;
}