本文整理汇总了C++中app::DocumentObject类的典型用法代码示例。如果您正苦于以下问题:C++ DocumentObject类的具体用法?C++ DocumentObject怎么用?C++ DocumentObject使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DocumentObject类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。
示例1: onChanged
void ViewProviderDrawingView::onChanged(const App::Property *prop)
{
App::DocumentObject* obj = getObject();
if (!obj || obj->isRestoring()) {
Gui::ViewProviderDocumentObject::onChanged(prop);
return;
}
if (prop == &Visibility) {
if(Visibility.getValue()) {
show();
} else {
hide();
}
} else if (prop == &KeepLabel) {
QGIView* qgiv = getQView();
if (qgiv) {
qgiv->updateView(true);
}
}
Gui::ViewProviderDocumentObject::onChanged(prop);
}
开发者ID:AjinkyaDahale,项目名称:FreeCAD,代码行数:23,代码来源:ViewProviderDrawingView.cpp
示例2: onChanged
void DrawViewSection::onChanged(const App::Property* prop)
{
if (!isRestoring()) {
//Base::Console().Message("TRACE - DVS::onChanged(%s) - %s\n",prop->getName(),Label.getValue());
if (prop == &SectionSymbol) {
std::string lblText = "Section " +
std::string(SectionSymbol.getValue()) +
" - " +
std::string(SectionSymbol.getValue());
Label.setValue(lblText);
}
if (prop == &SectionOrigin) {
App::DocumentObject* base = BaseView.getValue();
if (base != nullptr) {
base->touch();
}
}
}
if (prop == &FileHatchPattern ||
prop == &NameGeomPattern ) {
if ((!FileHatchPattern.isEmpty()) &&
(!NameGeomPattern.isEmpty())) {
std::vector<PATLineSpec> specs =
DrawGeomHatch::getDecodedSpecsFromFile(FileHatchPattern.getValue(),NameGeomPattern.getValue());
m_lineSets.clear();
for (auto& hl: specs) {
//hl.dump("hl from section");
LineSet ls;
ls.setPATLineSpec(hl);
m_lineSets.push_back(ls);
}
}
}
DrawView::onChanged(prop);
}
开发者ID:itain,项目名称:FreeCAD,代码行数:37,代码来源:DrawViewSection.cpp
示例3: originalSelected
const bool TaskTransformedParameters::originalSelected(const Gui::SelectionChanges& msg)
{
if (msg.Type == Gui::SelectionChanges::AddSelection && originalSelectionMode) {
if (strcmp(msg.pDocName, getObject()->getDocument()->getName()) != 0)
return false;
PartDesign::Transformed* pcTransformed = getObject();
App::DocumentObject* selectedObject = pcTransformed->getDocument()->getObject(msg.pObjectName);
if (selectedObject->isDerivedFrom(PartDesign::Additive::getClassTypeId()) ||
selectedObject->isDerivedFrom(PartDesign::Subtractive::getClassTypeId())) {
// Do the same like in TaskDlgTransformedParameters::accept() but without doCommand
std::vector<App::DocumentObject*> originals(1,selectedObject);
pcTransformed->Originals.setValues(originals);
recomputeFeature();
originalSelectionMode = false;
return true;
}
}
return false;
}
开发者ID:inferiorhumanorgans,项目名称:FreeCAD_bsd,代码行数:24,代码来源:TaskTransformedParameters.cpp
示例4: attach
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");
}
开发者ID:sanguinariojoe,项目名称:FreeCAD,代码行数:36,代码来源:ViewProviderDatum.cpp
示例5: activated
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();
}
开发者ID:crobarcro,项目名称:FreeCAD,代码行数:56,代码来源:CommandBody.cpp
示例6: slotChangedObject
void ShapeBinder::slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop)
{
App::Document* doc = getDocument();
if (!doc || doc->testStatus(App::Document::Restoring))
return;
if (this == &Obj)
return;
if (!TraceSupport.getValue())
return;
if (!Prop.getTypeId().isDerivedFrom(App::PropertyPlacement::getClassTypeId()))
return;
Part::Feature* obj = nullptr;
std::vector<std::string> subs;
ShapeBinder::getFilteredReferences(&Support, obj, subs);
if (obj) {
if (obj == &Obj) {
// the directly referenced object has changed
enforceRecompute();
}
else if (Obj.hasExtension(App::GroupExtension::getExtensionClassTypeId())) {
// check if the changed property belongs to a group-like object
// like Body or Part
std::vector<App::DocumentObject*> chain;
std::vector<App::DocumentObject*> list = getInListRecursive();
chain.insert(chain.end(), list.begin(), list.end());
list = obj->getInListRecursive();
chain.insert(chain.end(), list.begin(), list.end());
auto it = std::find(chain.begin(), chain.end(), &Obj);
if (it != chain.end()) {
enforceRecompute();
}
}
}
}
开发者ID:frankhardy,项目名称:FreeCAD,代码行数:36,代码来源:ShapeBinder.cpp
示例7: DocumentObjectExecReturn
App::DocumentObjectExecReturn *Revolution::execute(void)
{
App::DocumentObject* link = Sketch.getValue();
if (!link)
return new App::DocumentObjectExecReturn("No sketch linked");
if (!link->getTypeId().isDerivedFrom(Part::Part2DObject::getClassTypeId()))
return new App::DocumentObjectExecReturn("Linked object is not a Sketch or Part2DObject");
Part::Part2DObject* pcSketch=static_cast<Part::Part2DObject*>(link);
TopoDS_Shape shape = pcSketch->Shape.getShape()._Shape;
if (shape.IsNull())
return new App::DocumentObjectExecReturn("Linked shape object is empty");
// this is a workaround for an obscure OCC bug which leads to empty tessellations
// for some faces. Making an explicit copy of the linked shape seems to fix it.
// The error only happens when re-computing the shape.
if (!this->Shape.getValue().IsNull()) {
BRepBuilderAPI_Copy copy(shape);
shape = copy.Shape();
if (shape.IsNull())
return new App::DocumentObjectExecReturn("Linked shape object is empty");
}
TopExp_Explorer ex;
std::vector<TopoDS_Wire> wires;
for (ex.Init(shape, TopAbs_WIRE); ex.More(); ex.Next()) {
wires.push_back(TopoDS::Wire(ex.Current()));
}
if (wires.empty()) // there can be several wires
return new App::DocumentObjectExecReturn("Linked shape object is not a wire");
// get the Sketch plane
Base::Placement SketchPlm = pcSketch->Placement.getValue();
// get reference axis
App::DocumentObject *pcReferenceAxis = ReferenceAxis.getValue();
const std::vector<std::string> &subReferenceAxis = ReferenceAxis.getSubValues();
if (pcReferenceAxis && pcReferenceAxis == pcSketch) {
bool hasValidAxis=false;
Base::Axis axis;
if (subReferenceAxis[0] == "V_Axis") {
hasValidAxis = true;
axis = pcSketch->getAxis(Part::Part2DObject::V_Axis);
}
else if (subReferenceAxis[0] == "H_Axis") {
hasValidAxis = true;
axis = pcSketch->getAxis(Part::Part2DObject::H_Axis);
}
else if (subReferenceAxis[0].size() > 4 && subReferenceAxis[0].substr(0,4) == "Axis") {
int AxId = std::atoi(subReferenceAxis[0].substr(4,4000).c_str());
if (AxId >= 0 && AxId < pcSketch->getAxisCount()) {
hasValidAxis = true;
axis = pcSketch->getAxis(AxId);
}
}
if (hasValidAxis) {
axis *= SketchPlm;
Base::Vector3d base=axis.getBase();
Base::Vector3d dir=axis.getDirection();
Base.setValue(base.x,base.y,base.z);
Axis.setValue(dir.x,dir.y,dir.z);
}
}
// get revolve axis
Base::Vector3f b = Base.getValue();
gp_Pnt pnt(b.x,b.y,b.z);
Base::Vector3f v = Axis.getValue();
gp_Dir dir(v.x,v.y,v.z);
// get the support of the Sketch if any
App::DocumentObject* pcSupport = pcSketch->Support.getValue();
Part::Feature *SupportObject = 0;
if (pcSupport && pcSupport->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))
SupportObject = static_cast<Part::Feature*>(pcSupport);
TopoDS_Shape aFace = makeFace(wires);
if (aFace.IsNull())
return new App::DocumentObjectExecReturn("Creating a face from sketch failed");
// Rotate the face by half the angle to get revolution symmetric to sketch plane
if (Midplane.getValue()) {
gp_Trsf mov;
mov.SetRotation(gp_Ax1(pnt, dir), Base::toRadians<double>(Angle.getValue()) * (-1.0) / 2.0);
TopLoc_Location loc(mov);
aFace.Move(loc);
}
this->positionBySketch();
TopLoc_Location invObjLoc = this->getLocation().Inverted();
pnt.Transform(invObjLoc.Transformation());
dir.Transform(invObjLoc.Transformation());
// Reverse angle if selected
double angle = Base::toRadians<double>(Angle.getValue());
if (Reversed.getValue() && !Midplane.getValue())
angle *= (-1.0);
try {
//.........这里部分代码省略.........
开发者ID:emagdalena,项目名称:FreeCAD,代码行数:101,代码来源:FeatureRevolution.cpp
示例8: Exception
const std::list<gp_Trsf> PolarPattern::getTransformations(const std::vector<App::DocumentObject*>)
{
float angle = Angle.getValue();
if (angle < Precision::Confusion())
throw Base::Exception("Pattern angle too small");
int occurrences = Occurrences.getValue();
if (occurrences < 2)
throw Base::Exception("At least two occurrences required");
bool reversed = Reversed.getValue();
double offset;
if (std::abs(angle - 360.0) < Precision::Confusion())
offset = Base::toRadians<double>(angle) / occurrences; // Because e.g. two occurrences in 360 degrees need to be 180 degrees apart
else
offset = Base::toRadians<double>(angle) / (occurrences - 1);
App::DocumentObject* refObject = Axis.getValue();
if (refObject == NULL)
throw Base::Exception("No axis reference specified");
if (!refObject->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))
throw Base::Exception("Axis reference must be edge of a feature");
std::vector<std::string> subStrings = Axis.getSubValues();
if (subStrings.empty() || subStrings[0].empty())
throw Base::Exception("No axis reference specified");
gp_Pnt axbase;
gp_Dir axdir;
if (refObject->getTypeId().isDerivedFrom(Part::Part2DObject::getClassTypeId())) {
Part::Part2DObject* refSketch = static_cast<Part::Part2DObject*>(refObject);
Base::Axis axis;
if (subStrings[0] == "H_Axis")
axis = refSketch->getAxis(Part::Part2DObject::H_Axis);
else if (subStrings[0] == "V_Axis")
axis = refSketch->getAxis(Part::Part2DObject::V_Axis);
else if (subStrings[0] == "N_Axis")
axis = refSketch->getAxis(Part::Part2DObject::N_Axis);
else if (subStrings[0].size() > 4 && subStrings[0].substr(0,4) == "Axis") {
int AxId = std::atoi(subStrings[0].substr(4,4000).c_str());
if (AxId >= 0 && AxId < refSketch->getAxisCount())
axis = refSketch->getAxis(AxId);
}
axis *= refSketch->Placement.getValue();
axbase = gp_Pnt(axis.getBase().x, axis.getBase().y, axis.getBase().z);
axdir = gp_Dir(axis.getDirection().x, axis.getDirection().y, axis.getDirection().z);
} else {
Part::Feature* refFeature = static_cast<Part::Feature*>(refObject);
Part::TopoShape refShape = refFeature->Shape.getShape();
TopoDS_Shape ref = refShape.getSubShape(subStrings[0].c_str());
if (ref.ShapeType() == TopAbs_EDGE) {
TopoDS_Edge refEdge = TopoDS::Edge(ref);
if (refEdge.IsNull())
throw Base::Exception("Failed to extract axis edge");
BRepAdaptor_Curve adapt(refEdge);
if (adapt.GetType() != GeomAbs_Line)
throw Base::Exception("Axis edge must be a straight line");
axbase = adapt.Value(adapt.FirstParameter());
axdir = adapt.Line().Direction();
} else {
throw Base::Exception("Axis reference must be an edge");
}
}
TopLoc_Location invObjLoc = this->getLocation().Inverted();
axbase.Transform(invObjLoc.Transformation());
axdir.Transform(invObjLoc.Transformation());
gp_Ax2 axis(axbase, axdir);
if (reversed)
axis.SetDirection(axis.Direction().Reversed());
// Note: The original feature is NOT included in the list of transformations! Therefore
// we start with occurrence number 1, not number 0
std::list<gp_Trsf> transformations;
gp_Trsf trans;
transformations.push_back(trans); // identity transformation
for (int i = 1; i < occurrences; i++) {
trans.SetRotation(axis.Axis(), i * offset);
transformations.push_back(trans);
}
return transformations;
}
开发者ID:juanchijc,项目名称:FreeCAD_sf_master,代码行数:85,代码来源:FeaturePolarPattern.cpp
示例9: DocumentObjectExecReturn
App::DocumentObjectExecReturn *FeatureViewPart::execute(void)
{
std::stringstream result;
std::string ViewName = Label.getValue();
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()._Shape;
if (shape.IsNull())
return new App::DocumentObjectExecReturn("Linked shape object is empty");
Handle( HLRBRep_Algo ) brep_hlr = new HLRBRep_Algo;
brep_hlr->Add( shape );
gp_Ax2 transform(gp_Pnt(0,0,0),gp_Dir(0,0,1));
HLRAlgo_Projector projector( transform );
brep_hlr->Projector( projector );
brep_hlr->Update();
brep_hlr->Hide();
// extracting the result sets:
HLRBRep_HLRToShape shapes( brep_hlr );
TopoDS_Shape VisiblyEdges;
VisiblyEdges = shapes.VCompound();
TopoDS_Shape HiddenEdges;
HiddenEdges = shapes.HCompound();
BRepMesh::Mesh(VisiblyEdges,0.1);
//HLRBRep_HLRToShape Tool(Hider);
//TopoDS_Shape V = Tool.VCompound ();// artes vives vues
//TopoDS_Shape V1 = Tool.Rg1LineVCompound();// artes rgulires vues
//TopoDS_Shape VN = Tool.RgNLineVCompound();// artes de couture vues
//TopoDS_Shape VO = Tool.OutLineVCompound();// contours apparents vus
//TopoDS_Shape VI = Tool.IsoLineVCompound();// isoparamtriques vues
//TopoDS_Shape H = Tool.HCompound ();// artes vives caches
//TopoDS_Shape H1 = Tool.Rg1LineHCompound();// artes rgulires caches
//TopoDS_Shape HN = Tool.RgNLineHCompound();// artes de couture caches
//TopoDS_Shape HO = Tool.OutLineHCompound();// contours apparents cachs
//TopoDS_Shape HI = Tool.IsoLineHCompound();// isoparamtriques caches
result << "<g"
<< " id=\"" << ViewName << "\"" << endl
<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke-width=\"0.35\"" << endl
<< " stroke-linecap=\"butt\"" << endl
<< " stroke-linejoin=\"miter\"" << endl
<< " transform=\"translate("<< X.getValue()<<","<<Y.getValue()<<") scale("<< Scale.getValue()<<","<<Scale.getValue()<<")\"" << endl
<< " fill=\"none\"" << endl
<< " >" << endl;
TopExp_Explorer edges( VisiblyEdges, TopAbs_EDGE );
for (int i = 1 ; edges.More(); edges.Next(),i++ ) {
TopoDS_Edge edge = TopoDS::Edge( edges.Current() );
TopLoc_Location location;
Handle( Poly_Polygon3D ) polygon = BRep_Tool::Polygon3D( edge, location );
if ( !polygon.IsNull() ) {
const TColgp_Array1OfPnt& nodes = polygon->Nodes();
char c = 'M';
result << "<path id= \"" << ViewName << i << "\" d=\" ";
for ( int i = nodes.Lower(); i<= nodes.Upper(); i++ ){
result << c << " " << nodes(i).X() << " " << nodes(i).Y()<< " " ;
c = 'L';
}
result << "\" />" << endl;
}
}
result << "</g>" << endl;
// Apply the resulting fragment
ViewResult.setValue(result.str().c_str());
return App::DocumentObject::StdReturn;
}
开发者ID:Barleyman,项目名称:FreeCAD_sf_master,代码行数:79,代码来源:FeatureViewPart.cpp
示例10: accept
bool SweepWidget::accept()
{
if (d->loop.isRunning())
return false;
Gui::SelectionFilter edgeFilter ("SELECT Part::Feature SUBELEMENT Edge COUNT 1..");
Gui::SelectionFilter partFilter ("SELECT Part::Feature COUNT 1");
bool matchEdge = edgeFilter.match();
bool matchPart = partFilter.match();
if (!matchEdge && !matchPart) {
QMessageBox::critical(this, tr("Sweep path"), tr("Select one or more connected edges you want to sweep along."));
return false;
}
// get the selected object
std::string selection;
std::string spineObject, spineLabel;
const std::vector<Gui::SelectionObject>& result = matchEdge
? edgeFilter.Result[0] : partFilter.Result[0];
selection = result.front().getAsPropertyLinkSubString();
spineObject = result.front().getFeatName();
spineLabel = result.front().getObject()->Label.getValue();
QString list, solid, frenet;
if (d->ui.checkSolid->isChecked())
solid = QString::fromLatin1("True");
else
solid = QString::fromLatin1("False");
if (d->ui.checkFrenet->isChecked())
frenet = QString::fromLatin1("True");
else
frenet = QString::fromLatin1("False");
QTextStream str(&list);
int count = d->ui.selector->selectedTreeWidget()->topLevelItemCount();
if (count < 1) {
QMessageBox::critical(this, tr("Too few elements"), tr("At least one edge or wire is required."));
return false;
}
for (int i=0; i<count; i++) {
QTreeWidgetItem* child = d->ui.selector->selectedTreeWidget()->topLevelItem(i);
QString name = child->data(0, Qt::UserRole).toString();
if (name == QLatin1String(spineObject.c_str())) {
QMessageBox::critical(this, tr("Wrong selection"), tr("'%1' cannot be used as profile and path.")
.arg(QString::fromUtf8(spineLabel.c_str())));
return false;
}
str << "App.getDocument('" << d->document.c_str() << "')." << name << ", ";
}
try {
Gui::WaitCursor wc;
QString cmd;
cmd = QString::fromLatin1(
"App.getDocument('%5').addObject('Part::Sweep','Sweep')\n"
"App.getDocument('%5').ActiveObject.Sections=[%1]\n"
"App.getDocument('%5').ActiveObject.Spine=%2\n"
"App.getDocument('%5').ActiveObject.Solid=%3\n"
"App.getDocument('%5').ActiveObject.Frenet=%4\n"
)
.arg(list)
.arg(QLatin1String(selection.c_str()))
.arg(solid)
.arg(frenet)
.arg(QString::fromLatin1(d->document.c_str()));
Gui::Document* doc = Gui::Application::Instance->getDocument(d->document.c_str());
if (!doc) throw Base::Exception("Document doesn't exist anymore");
doc->openCommand("Sweep");
Gui::Application::Instance->runPythonCode((const char*)cmd.toLatin1(), false, false);
doc->getDocument()->recompute();
App::DocumentObject* obj = doc->getDocument()->getActiveObject();
if (obj && !obj->isValid()) {
std::string msg = obj->getStatusString();
doc->abortCommand();
throw Base::Exception(msg);
}
doc->commitCommand();
}
catch (const Base::Exception& e) {
QMessageBox::warning(this, tr("Input error"), QString::fromLatin1(e.what()));
return false;
}
return true;
}
开发者ID:3DPrinterGuy,项目名称:FreeCAD,代码行数:87,代码来源:TaskSweep.cpp
示例11: Exception
const std::list<gp_Trsf> LinearPattern::getTransformations(const std::vector<App::DocumentObject*>)
{
std::string stdDirection = StdDirection.getValue();
float distance = Length.getValue();
if (distance < Precision::Confusion())
throw Base::Exception("Pattern length too small");
int occurrences = Occurrences.getValue();
if (occurrences < 2)
throw Base::Exception("At least two occurrences required");
bool reversed = Reversed.getValue();
gp_Dir dir;
double offset = distance / (occurrences - 1);
if (!stdDirection.empty()) {
// Note: The placement code commented out below had the defect of working always on the
// absolute X,Y,Z direction, not on the relative coordinate system of the Body feature.
// It requires positionBySupport() to be called in Transformed::Execute() AFTER
// the call to getTransformations()
// New code thanks to logari81
if (stdDirection == "X") {
//dir = Base::Axis(Base::Vector3d(0,0,0), Base::Vector3d(1,0,0));
dir = gp_Dir(1,0,0);
} else if (stdDirection == "Y") {
//dir = Base::Axis(Base::Vector3d(0,0,0), Base::Vector3d(0,1,0));
dir = gp_Dir(0,1,0);
} else if(stdDirection == "Z") {
//dir = Base::Axis(Base::Vector3d(0,0,0), Base::Vector3d(0,0,1));
dir = gp_Dir(0,0,1);
} else {
throw Base::Exception("Invalid direction (must be X, Y or Z)");
}
} else {
App::DocumentObject* refObject = Direction.getValue();
if (refObject == NULL)
throw Base::Exception("No direction specified");
if (!refObject->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))
throw Base::Exception("Direction reference must be edge or face of a feature");
std::vector<std::string> subStrings = Direction.getSubValues();
if (subStrings.empty() || subStrings[0].empty())
throw Base::Exception("No direction reference specified");
Part::Feature* refFeature = static_cast<Part::Feature*>(refObject);
Part::TopoShape refShape = refFeature->Shape.getShape();
TopoDS_Shape ref = refShape.getSubShape(subStrings[0].c_str());
if (ref.ShapeType() == TopAbs_FACE) {
TopoDS_Face refFace = TopoDS::Face(ref);
if (refFace.IsNull())
throw Base::Exception("Failed to extract direction plane");
BRepAdaptor_Surface adapt(refFace);
if (adapt.GetType() != GeomAbs_Plane)
throw Base::Exception("Direction face must be planar");
dir = adapt.Plane().Axis().Direction();
//gp_Dir d = adapt.Plane().Axis().Direction();
//dir = Base::Axis(Base::Vector3d(0,0,0), Base::Vector3d(d.X(), d.Y(), d.Z()));
} else if (ref.ShapeType() == TopAbs_EDGE) {
TopoDS_Edge refEdge = TopoDS::Edge(ref);
if (refEdge.IsNull())
throw Base::Exception("Failed to extract direction edge");
BRepAdaptor_Curve adapt(refEdge);
if (adapt.GetType() != GeomAbs_Line)
throw Base::Exception("Direction edge must be a straight line");
//gp_Dir d = adapt.Line().Direction();
//dir = Base::Axis(Base::Vector3d(0,0,0), Base::Vector3d(d.X(), d.Y(), d.Z()));
dir = adapt.Line().Direction();
} else {
throw Base::Exception("Direction reference must be edge or face");
}
TopLoc_Location invObjLoc = this->getLocation().Inverted();
dir.Transform(invObjLoc.Transformation());
}
// get the support placement
// TODO: Check for NULL pointer
/*Part::Feature* supportFeature = static_cast<Part::Feature*>(originals.front());
if (supportFeature == NULL)
throw Base::Exception("Cannot work on invalid support shape");
Base::Placement supportPlacement = supportFeature->Placement.getValue();
dir *= supportPlacement;
gp_Vec direction(dir.getDirection().x, dir.getDirection().y, dir.getDirection().z);*/
gp_Vec direction(dir.X(), dir.Y(), dir.Z());
if (reversed)
direction.Reverse();
// Note: The original feature is NOT included in the list of transformations! Therefore
// we start with occurrence number 1, not number 0
std::list<gp_Trsf> transformations;
gp_Trsf trans;
transformations.push_back(trans); // identity transformation
for (int i = 1; i < occurrences; i++) {
trans.SetTranslation(direction * i * offset);
transformations.push_back(trans);
}
return transformations;
//.........这里部分代码省略.........
开发者ID:Daedalus12,项目名称:FreeCAD_sf_master,代码行数:101,代码来源:FeatureLinearPattern.cpp
示例12: DocumentObjectExecReturn
App::DocumentObjectExecReturn *Draft::execute(void)
{
// Get parameters
// Base shape
Part::TopoShape TopShape;
try {
TopShape = getBaseShape();
} catch (Base::Exception& e) {
return new App::DocumentObjectExecReturn(e.what());
}
// Faces where draft should be applied
// Note: Cannot be const reference currently because of BRepOffsetAPI_DraftAngle::Remove() bug, see below
std::vector<std::string> SubVals = Base.getSubValuesStartsWith("Face");
if (SubVals.size() == 0)
return new App::DocumentObjectExecReturn("No faces specified");
// Draft angle
double angle = Angle.getValue() / 180.0 * M_PI;
// Pull direction
gp_Dir pullDirection;
App::DocumentObject* refDirection = PullDirection.getValue();
if (refDirection != NULL) {
if (refDirection->getTypeId().isDerivedFrom(PartDesign::Line::getClassTypeId())) {
PartDesign::Line* line = static_cast<PartDesign::Line*>(refDirection);
Base::Vector3d d = line->getDirection();
pullDirection = gp_Dir(d.x, d.y, d.z);
} else if (refDirection->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
std::vector<std::string> subStrings = PullDirection.getSubValues();
if (subStrings.empty() || subStrings[0].empty())
throw Base::Exception("No pull direction reference specified");
Part::Feature* refFeature = static_cast<Part::Feature*>(refDirection);
Part::TopoShape refShape = refFeature->Shape.getShape();
TopoDS_Shape ref = refShape.getSubShape(subStrings[0].c_str());
if (ref.ShapeType() == TopAbs_EDGE) {
TopoDS_Edge refEdge = TopoDS::Edge(ref);
if (refEdge.IsNull())
throw Base::Exception("Failed to extract pull direction reference edge");
BRepAdaptor_Curve adapt(refEdge);
if (adapt.GetType() != GeomAbs_Line)
throw Base::Exception("Pull direction reference edge must be linear");
pullDirection = adapt.Line().Direction();
} else {
throw Base::Exception("Pull direction reference must be an edge or a datum line");
}
} else {
throw Base::Exception("Pull direction reference must be an edge of a feature or a datum line");
}
TopLoc_Location invObjLoc = this->getLocation().Inverted();
pullDirection.Transform(invObjLoc.Transformation());
}
// Neutral plane
gp_Pln neutralPlane;
App::DocumentObject* refPlane = NeutralPlane.getValue();
if (refPlane == NULL) {
// Try to guess a neutral plane from the first selected face
// Get edges of first selected face
TopoDS_Shape face = TopShape.getSubShape(SubVals[0].c_str());
TopTools_IndexedMapOfShape mapOfEdges;
TopExp::MapShapes(face, TopAbs_EDGE, mapOfEdges);
bool found = false;
for (int i = 1; i <= mapOfEdges.Extent(); i++) {
// Note: What happens if mapOfEdges(i) is the degenerated edge of a cone?
// But in that case the draft is not possible anyway!
BRepAdaptor_Curve c(TopoDS::Edge(mapOfEdges(i)));
gp_Pnt p1 = c.Value(c.FirstParameter());
gp_Pnt p2 = c.Value(c.LastParameter());
if (c.IsClosed()) {
// Edge is a circle or a circular arc (other types are not allowed for drafting)
neutralPlane = gp_Pln(p1, c.Circle().Axis().Direction());
found = true;
break;
} else {
// Edge is linear
// Find midpoint of edge and create auxiliary plane through midpoint normal to edge
gp_Pnt pm = c.Value((c.FirstParameter() + c.LastParameter()) / 2.0);
Handle(Geom_Plane) aux = new Geom_Plane(pm, gp_Dir(p2.X() - p1.X(), p2.Y() - p1.Y(), p2.Z() - p1.Z()));
// Intersect plane with face. Is there no easier way?
BRepAdaptor_Surface adapt(TopoDS::Face(face), Standard_False);
Handle(Geom_Surface) sf = adapt.Surface().Surface();
GeomAPI_IntSS intersector(aux, sf, Precision::Confusion());
if (!intersector.IsDone())
continue;
Handle(Geom_Curve) icurve = intersector.Line(1);
if (!icurve->IsKind(STANDARD_TYPE(Geom_Line)))
continue;
// TODO: How to extract the line from icurve without creating an edge first?
TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(icurve);
BRepAdaptor_Curve c(edge);
neutralPlane = gp_Pln(pm, c.Line().Direction());
found = true;
break;
//.........这里部分代码省略.........
开发者ID:crobarcro,项目名称:FreeCAD,代码行数:101,代码来源:FeatureDraft.cpp
示例13: sExport
PyObject* Application::sExport(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
{
PyObject* object;
char* Name;
if (!PyArg_ParseTuple(args, "Oet",&object,"utf-8",&Name))
return NULL;
std::string Utf8Name = std::string(Name);
PyMem_Free(Name);
PY_TRY {
App::Document* doc = 0;
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();
doc = obj->getDocument();
break;
}
}
QString fileName = QString::fromUtf8(Utf8Name.c_str());
QFileInfo fi;
fi.setFile(fileName);
QString ext = fi.suffix().toLower();
if (ext == QLatin1String("iv") || ext == QLatin1String("wrl") ||
ext == QLatin1String("vrml") || ext == QLatin1String("wrz")) {
// build up the graph
SoSeparator* sep = new SoSeparator();
sep->ref();
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();
Gui::ViewProvider* vp = Gui::Application::Instance->getViewProvider(obj);
if (vp) {
sep->addChild(vp->getRoot());
}
}
}
SoGetPrimitiveCountAction action;
action.setCanApproximate(true);
action.apply(sep);
bool binary = false;
if (action.getTriangleCount() > 100000 ||
action.getPointCount() > 30000 ||
action.getLineCount() > 10000)
binary = true;
SoFCDB::writeToFile(sep, Utf8Name.c_str(), binary);
sep->unref();
}
else if (ext == QLatin1String("pdf")) {
// get the view that belongs to the found document
Gui::Document* gui_doc = Application::Instance->getDocument(doc);
if (gui_doc) {
Gui::MDIView* view = gui_doc->getActiveView();
if (view) {
View3DInventor* view3d = qobject_cast<View3DInventor*>(view);
if (view3d)
view3d->viewAll();
QPrinter printer(QPrinter::ScreenResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(fileName);
view->print(&printer);
}
}
}
else {
Base::Console().Error("File type '%s' not supported\n", ext.toLatin1().constData());
}
} PY_CATCH;
Py_Return;
}
开发者ID:Jonham,项目名称:FreeCAD,代码行数:81,代码来源:ApplicationPy.cpp
示例14: apply
void DlgExtrusion::apply()
{
if (ui->treeWidget->selectedItems().isEmpty()) {
QMessageBox::critical(this, windowTitle(),
tr("Select a shape for extrusion, first."));
return;
}
Gui::WaitCursor wc;
App::Document* activeDoc = App::GetApplication().getDocument(this->document.c_str());
if (!activeDoc) {
QMessageBox::critical(this, windowTitle(),
tr("The document '%1' doesn't exist.").arg(QString::fromUtf8(this->label.c_str())));
return;
}
activeDoc->openTransaction("Extrude");
Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()
.GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Part");
bool addBaseName = hGrp->GetBool("AddBaseObjectName", false);
QString shape, type, name, label;
QList<QTreeWidgetItem *> items = ui->treeWidget->selectedItems();
for (QList<QTreeWidgetItem *>::iterator it = items.begin(); it != items.end(); ++it) {
shape = (*it)->data(0, Qt::UserRole).toString();
type = QString::fromLatin1("Part::Extrusion");
if (addBaseName) {
QString baseName = QString::fromLatin1("Extrude_%1").arg(shape);
label = QString::fromLatin1("%1_Extrude").arg((*it)->text(0));
name = QString::fromLatin1(activeDoc->getUniqueObjectName((const char*)baseName.toLatin1()).c_str());
}
else {
name = QString::fromLatin1(activeDoc->getUniqueObjectName("Extrude").c_str());
label = name;
}
double len = ui->dirLen->value();
double dirX = ui->dirX->value();
double dirY = ui->dirY->value();
double dirZ = ui->dirZ->value();
double angle = ui->taperAngle->value().getValue();
bool makeSolid = ui->makeSolid->isChecked();
// inspect geometry
App::DocumentObject* obj = activeDoc->getObject((const char*)shape.toLatin1());
if (!obj || !obj->isDerivedFrom(Part::Feature::getClassTypeId())) continue;
Part::Feature* fea = static_cast<Part::Feature*>(obj);
const TopoDS_Shape& data = fea->Shape.getValue();
if (data.IsNull()) continue;
// check for planes
if (ui->checkNormal->isChecked() && data.ShapeType() == TopAbs_FACE) {
BRepAdaptor_Surface adapt(TopoDS::Face(data));
if (adapt.GetType() == GeomAbs_Plane) {
double u = 0.5*(adapt.FirstUParameter() + adapt.LastUParameter());
double v = 0.5*(adapt.FirstVParameter() + adapt.LastVParameter());
BRepLProp_SLProps prop(adapt,u,v,1,Precision::Confusion());
if (prop.IsNormalDefined()) {
gp_Pnt pnt; gp_Vec vec;
// handles the orientation state of the shape
BRepGProp_Face(TopoDS::Face(data)).Normal(u,v,pnt,vec);
dirX = vec.X();
dirY = vec.Y();
dirZ = vec.Z();
}
}
}
QString code = QString::fromLatin1(
"FreeCAD.getDocument(\"%1\").addObject(\"%2\",\"%3\")\n"
"FreeCAD.getDocument(\"%1\").%3.Base = FreeCAD.getDocument(\"%1\").%4\n"
"FreeCAD.getDocument(\"%1\").%3.Dir = (%5,%6,%7)\n"
"FreeCAD.getDocument(\"%1\").%3.Solid = (%8)\n"
"FreeCAD.getDocument(\"%1\").%3.TaperAngle = (%9)\n"
"FreeCADGui.getDocument(\"%1\").%4.Visibility = False\n"
"FreeCAD.getDocument(\"%1\").%3.Label = '%10'\n")
.arg(QString::fromLatin1(this->document.c_str()))
.arg(type).arg(name).arg(shape)
.arg(dirX*len)
.arg(dirY*len)
.arg(dirZ*len)
.arg(makeSolid ? QLatin1String("True") : QLatin1String("False"))
.arg(angle)
.arg(label);
Gui::Application::Instance->runPythonCode((const char*)code.toLatin1());
QByteArray to = name.toLatin1();
QByteArray from = shape.toLatin1();
Gui::Command::copyVisual(to, "ShapeColor", from);
Gui::Command::copyVisual(to, "LineColor", from);
Gui::Command::copyVisual(to, "PointColor", from);
}
activeDoc->commitTransaction();
try {
ui->statusLabel->clear();
activeDoc->recompute();
ui->statusLabel->setText(QString::fromLatin1
("<span style=\" color:#55aa00;\">%1</span>").arg(tr("Succeeded")));
}
catch (const std::exception& e) {
//.........这里部分代码省略.........
开发者ID:AllenBootung,项目名称:FreeCAD,代码行数:101,代码来源:DlgExtrusion.cpp
示例15: makeCopy
App::DocumentObject* TaskFeaturePick::makeCopy(App::DocumentObject* obj, std::string sub, bool independent) {
App::DocumentObject* copy = nullptr;
// Check for null to avoid segfault
if (!obj)
return copy;
if( independent &&
(obj->isDerivedFrom(Sketcher::SketchObject::getClassTypeId()) ||
obj->isDerivedFrom(PartDesign::FeaturePrimitive::getClassTypeId()))) {
//we do know that the created instance is a document object, as obj is one. But we do not know which
//exact type
auto name = std::string("Copy") + std::string(ob
|
请发表评论