diff --git a/src/Mod/TechDraw/App/DrawComplexSection.cpp b/src/Mod/TechDraw/App/DrawComplexSection.cpp index cc3de3c2ec07..a39dc6bb21b2 100644 --- a/src/Mod/TechDraw/App/DrawComplexSection.cpp +++ b/src/Mod/TechDraw/App/DrawComplexSection.cpp @@ -81,6 +81,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -129,12 +132,12 @@ using DU = DrawUtil; PROPERTY_SOURCE(TechDraw::DrawComplexSection, TechDraw::DrawViewSection) -const char *DrawComplexSection::ProjectionStrategyEnums[] = {"Offset", "Aligned", "NoParallel", +const char* DrawComplexSection::ProjectionStrategyEnums[] = {"Offset", "Aligned", "NoParallel", nullptr}; DrawComplexSection::DrawComplexSection() { - static const char *fgroup = "Cutting Tool"; + static const char* fgroup = "Cutting Tool"; ADD_PROPERTY_TYPE(CuttingToolWireObject, (nullptr), fgroup, App::Prop_None, "A sketch that describes the cutting tool"); @@ -147,7 +150,7 @@ DrawComplexSection::DrawComplexSection() TopoDS_Shape DrawComplexSection::getShapeToCut() { // Base::Console().Message("DCS::getShapeToCut()\n"); - App::DocumentObject *base = BaseView.getValue(); + App::DocumentObject* base = BaseView.getValue(); TopoDS_Shape shapeToCut; if (base && base == this) { shapeToCut = getSourceShape(); @@ -244,6 +247,7 @@ TopoDS_Shape DrawComplexSection::makeCuttingTool(double dMax) TopoDS_Shape DrawComplexSection::getShapeToPrepare() const { + // Base::Console().Message("DCS::getShapeToPrepare()\n"); if (ProjectionStrategy.getValue() == 0) { //Offset. Use regular section behaviour return DrawViewSection::getShapeToPrepare(); @@ -253,49 +257,86 @@ TopoDS_Shape DrawComplexSection::getShapeToPrepare() const } //get the shape ready for projection and cut surface finding -TopoDS_Shape DrawComplexSection::prepareShape(const TopoDS_Shape &cutShape, double shapeSize) +TopoDS_Shape DrawComplexSection::prepareShape(const TopoDS_Shape& cutShape, double shapeSize) { -// Base::Console().Message("DCS::prepareShape() - strategy: %d\n", ProjectionStrategy.getValue()); + // Base::Console().Message("DCS::prepareShape() - strategy: %d\n", ProjectionStrategy.getValue()); if (ProjectionStrategy.getValue() == 0) { //Offset. Use regular section behaviour return DrawViewSection::prepareShape(cutShape, shapeSize); } //"Aligned" projection (Aligned Section) - TopoDS_Shape alignedResult; - try { - alignedResult = makeAlignedPieces(cutShape, m_toolFaceShape, shapeSize); - } - catch (Base::RuntimeError& e) { - Base::Console().Error("Complex Section - %s\n", e.what()); + if (m_alignResult.IsNull()) { return TopoDS_Shape(); } - if (alignedResult.IsNull()) { - return TopoDS_Shape(); + TopoDS_Shape centeredShape = TechDraw::centerShapeXY(m_alignResult, getProjectionCS()); + // m_preparedShape = scaleShape(m_alignResult, getScale()); + m_preparedShape = scaleShape(centeredShape, getScale()); + if (!DrawUtil::fpCompare(Rotation.getValue(), 0.0)) { + m_preparedShape = + TechDraw::rotateShape(m_preparedShape, getProjectionCS(), Rotation.getValue()); } - TopoDS_Shape preparedShape = scaleShape(alignedResult, getScale()); - if (!DrawUtil::fpCompare(Rotation.getValue(), 0.0)) { - preparedShape = TechDraw::rotateShape(preparedShape, - getProjectionCS(), - Rotation.getValue()); + return m_preparedShape; +} + + +void DrawComplexSection::makeSectionCut(TopoDS_Shape& baseShape) +{ + // Base::Console().Message("DCS::makeSectionCut() - %s - baseShape.IsNull: %d\n", + // getNameInDocument(), baseShape.IsNull()); + if (ProjectionStrategy.getValue() == 0) { + //Offset. Use regular section behaviour + return DrawViewSection::makeSectionCut(baseShape); } - return preparedShape; + try { + connectAlignWatcher = + QObject::connect(&m_alignWatcher, &QFutureWatcherBase::finished, &m_alignWatcher, + [this] { this->onSectionCutFinished(); }); + m_alignFuture = QtConcurrent::run(this, &DrawComplexSection::makeAlignedPieces, baseShape); + m_alignWatcher.setFuture(m_alignFuture); + waitingForAlign(true); + } + catch (...) { + Base::Console().Message("DCS::makeSectionCut - failed to make alignedPieces"); + return; + } + + return DrawViewSection::makeSectionCut(baseShape); +} + + +void DrawComplexSection::onSectionCutFinished() +{ + // Base::Console().Message("DCS::onSectionCutFinished() - %s - cut: %d align: %d\n", + // getNameInDocument(), m_cutFuture.isRunning(), m_alignFuture.isRunning()); + if (m_cutFuture.isRunning() || //waitingForCut() + m_alignFuture.isRunning()) {//waitingForAlign() + //can not continue yet. return until the other thread ends + return; + } + + DrawViewSection::onSectionCutFinished(); + + QObject::disconnect(connectAlignWatcher); } //for Aligned strategy, cut the rawShape by each segment of the tool //TODO: this process should replace the "makeSectionCut" from DVS -TopoDS_Shape DrawComplexSection::makeAlignedPieces(const TopoDS_Shape &rawShape, - const TopoDS_Shape &toolFaceShape, - double extrudeDistance) +void DrawComplexSection::makeAlignedPieces(const TopoDS_Shape& rawShape) { -// Base::Console().Message("DCS::makeAlignedPieces()\n"); + // Base::Console().Message("DCS::makeAlignedPieces() - rawShape.isNull: %d\n", rawShape.IsNull()); + + if (!canBuild(getSectionCS(), CuttingToolWireObject.getValue())) { + throw Base::RuntimeError("Profile is parallel to Section Normal"); + } + std::vector pieces; - std::vector pieceXSizeAll; //size in sectionCS.XDirection (width) - std::vector pieceYSizeAll; //size in sectionCS.Direction (depth) - std::vector pieceZSizeAll; //size in sectionCS.YDirection (height) + std::vector pieceXSizeAll;//size in sectionCS.XDirection (width) + std::vector pieceYSizeAll;//size in sectionCS.Direction (depth) + std::vector pieceZSizeAll;//size in sectionCS.YDirection (height) //make a CS from the section CS ZX plane to allow piece positioning (left-right) //with the section view vertical centerline and (in-out, forward-backward) with @@ -312,13 +353,13 @@ TopoDS_Shape DrawComplexSection::makeAlignedPieces(const TopoDS_Shape &rawShape, throw Base::RuntimeError("Can not make wire from cutting tool (2)"); } gp_Vec gProfileVec = makeProfileVector(profileWire); + gp_Vec rotateAxis = (getSectionCS().Direction()).Crossed(gProfileVec); + //now we want to know what the profileVector looks like on the page (only X,Y coords) + //so we know if we are going to stack views vertically or horizontally and if the segments + //will occur (left to right or right to left) or (top to bottom or bottom to top) gProfileVec = projectVector(gProfileVec).Normalized(); - if (!canBuild(getSectionCS(), CuttingToolWireObject.getValue())) { - throw Base::RuntimeError("Profile is parallel to Section Normal"); - } - bool isProfileVertical = true; if (fabs(gProfileVec.Dot(gp::OY().Direction().XYZ())) != 1.0) { //profile is not parallel with stdY (paper space Up). @@ -337,11 +378,9 @@ TopoDS_Shape DrawComplexSection::makeAlignedPieces(const TopoDS_Shape &rawShape, verticalReverser = -1.0; } - gp_Vec rotateAxis = getSectionCS().Direction().Crossed(gProfileVec); - //make a tool for each segment of the toolFaceShape and intersect it with the //raw shape - TopExp_Explorer expFaces(toolFaceShape, TopAbs_FACE); + TopExp_Explorer expFaces(m_toolFaceShape, TopAbs_FACE); for (int iPiece = 0; expFaces.More(); expFaces.Next(), iPiece++) { TopoDS_Face face = TopoDS::Face(expFaces.Current()); gp_Vec segmentNormal = gp_Vec(getFaceNormal(face)); @@ -350,12 +389,12 @@ TopoDS_Shape DrawComplexSection::makeAlignedPieces(const TopoDS_Shape &rawShape, continue; } //we only want to reverse the segment normal if it is not perpendicular to section normal - if (segmentNormal.Dot(-gProjectionUnit) != 0.0 + if (segmentNormal.Dot(gProjectionUnit) != 0.0 && segmentNormal.Angle(gProjectionUnit) <= M_PI_2) { segmentNormal.Reverse(); } - gp_Vec extrudeDir = segmentNormal * extrudeDistance; + gp_Vec extrudeDir = segmentNormal * m_shapeSize; BRepPrimAPI_MakePrism mkPrism(face, extrudeDir); TopoDS_Shape segmentTool = mkPrism.Shape(); TopoDS_Shape intersect = shapeShapeIntersect(segmentTool, rawShape); @@ -410,7 +449,8 @@ TopoDS_Shape DrawComplexSection::makeAlignedPieces(const TopoDS_Shape &rawShape, gp_Vec netDisplacement = -1.0 * gp_Vec(findCentroid(pieceAligned).XYZ()) + yVector; //if we are going to space along X, we need to bring the pieces back into alignment //with the XY plane. If we are stacking the pieces along Z, we don't want a vertical adjustment. - gp_Vec xyDisplacement = isProfileVertical ? gp_Vec(0.0, 0.0, 0.0) : gp_Vec(gp::OZ().Direction()); + gp_Vec xyDisplacement = + isProfileVertical ? gp_Vec(0.0, 0.0, 0.0) : gp_Vec(gp::OZ().Direction()); double dot = gp_Vec(gp::OZ().Direction()).Dot(alignedCS.Direction()); xyDisplacement = xyDisplacement * dot * (pieceZSize / 2.0); netDisplacement = netDisplacement + xyDisplacement; @@ -425,19 +465,22 @@ TopoDS_Shape DrawComplexSection::makeAlignedPieces(const TopoDS_Shape &rawShape, } if (pieces.empty()) { - return TopoDS_Compound(); + m_alignResult = TopoDS_Compound(); + return; } int pieceCount = pieces.size(); if (pieceCount < 2) { //no need to space out the pieces - return TopoDS::Compound(pieces.front()); + m_alignResult = TopoDS::Compound(pieces.front()); + return; } //space the pieces "horizontally" (stdX) or "vertically" (stdZ) double movementReverser = isProfileVertical ? verticalReverser : horizReverser; //TODO: non-cardinal profiles! - gp_Vec movementAxis = isProfileVertical ? gp_Vec(gp::OZ().Direction()) : gp_Vec(gp::OX().Direction()); + gp_Vec movementAxis = + isProfileVertical ? gp_Vec(gp::OZ().Direction()) : gp_Vec(gp::OX().Direction()); gp_Vec gMovementVector = movementAxis * movementReverser; int stopAt = pieces.size(); @@ -459,7 +502,7 @@ TopoDS_Shape DrawComplexSection::makeAlignedPieces(const TopoDS_Shape &rawShape, BRep_Builder builder; TopoDS_Compound comp; builder.MakeCompound(comp); - for (auto &piece : pieces) { + for (auto& piece : pieces) { builder.Add(comp, piece); } @@ -480,7 +523,7 @@ TopoDS_Shape DrawComplexSection::makeAlignedPieces(const TopoDS_Shape &rawShape, BRepTools::Write(alignedCompound, "DCSmap50AlignedCompound.brep");//debug } - return alignedCompound; + m_alignResult = alignedCompound; } //! tries to find the intersection faces of the cut shape and the cutting tool. @@ -488,9 +531,9 @@ TopoDS_Shape DrawComplexSection::makeAlignedPieces(const TopoDS_Shape &rawShape, //! case is a compound of individual cuts) with the "effective" (flattened) section plane. //! Profiles containing curves need special handling. TopoDS_Compound -DrawComplexSection::findSectionPlaneIntersections(const TopoDS_Shape &shapeToIntersect) +DrawComplexSection::findSectionPlaneIntersections(const TopoDS_Shape& shapeToIntersect) { -// Base::Console().Message("DCS::findSectionPlaneIntersections() - %s\n", getNameInDocument()); + // Base::Console().Message("DCS::findSectionPlaneIntersections() - %s\n", getNameInDocument()); if (shapeToIntersect.IsNull()) { // this shouldn't happen Base::Console().Warning("DCS::findSectionPlaneInter - %s - cut shape is Null\n", @@ -505,10 +548,10 @@ DrawComplexSection::findSectionPlaneIntersections(const TopoDS_Shape &shapeToInt } //Intersect cutShape with each segment of the cutting tool -TopoDS_Compound DrawComplexSection::singleToolIntersections(const TopoDS_Shape &cutShape) +TopoDS_Compound DrawComplexSection::singleToolIntersections(const TopoDS_Shape& cutShape) { // Base::Console().Message("DCS::singleToolInterSections()\n"); - App::DocumentObject *toolObj = CuttingToolWireObject.getValue(); + App::DocumentObject* toolObj = CuttingToolWireObject.getValue(); if (!isLinearProfile(toolObj)) { //TODO: special handling here // Base::Console().Message("DCS::singleToolIntersection - profile has curves\n"); @@ -534,20 +577,22 @@ TopoDS_Compound DrawComplexSection::singleToolIntersections(const TopoDS_Shape & continue; } std::vector commonFaces = faceShapeIntersect(face, m_toolFaceShape); - for (auto &cFace : commonFaces) { builder.Add(result, cFace); } + for (auto& cFace : commonFaces) { + builder.Add(result, cFace); + } } return result; } //Intersect cutShape with the effective (flattened) cutting plane to generate cut surface faces -TopoDS_Compound DrawComplexSection::alignedToolIntersections(const TopoDS_Shape &cutShape) +TopoDS_Compound DrawComplexSection::alignedToolIntersections(const TopoDS_Shape& cutShape) { -// Base::Console().Message("DCS::alignedToolIntersections()\n"); + // Base::Console().Message("DCS::alignedToolIntersections()\n"); BRep_Builder builder; TopoDS_Compound result; builder.MakeCompound(result); - App::DocumentObject *toolObj = CuttingToolWireObject.getValue(); + App::DocumentObject* toolObj = CuttingToolWireObject.getValue(); if (!isLinearProfile(toolObj)) { //TODO: special handling here // Base::Console().Message("DCS::alignedToolIntersection - profile has curves\n"); @@ -567,7 +612,9 @@ TopoDS_Compound DrawComplexSection::alignedToolIntersections(const TopoDS_Shape continue; } std::vector commonFaces = faceShapeIntersect(face, cuttingFace); - for (auto &cFace : commonFaces) { builder.Add(result, cFace); } + for (auto& cFace : commonFaces) { + builder.Add(result, cFace); + } } if (debugSection()) { BRepTools::Write(cuttingFace, "DCSAlignedCuttingFace.brep"); //debug @@ -579,7 +626,7 @@ TopoDS_Compound DrawComplexSection::alignedToolIntersections(const TopoDS_Shape TopoDS_Compound DrawComplexSection::alignSectionFaces(TopoDS_Shape faceIntersections) { -// Base::Console().Message("DCS::alignSectionFaces() - faceIntersections.null: %d\n", faceIntersections.IsNull()); + // Base::Console().Message("DCS::alignSectionFaces() - faceIntersections.null: %d\n", faceIntersections.IsNull()); if (ProjectionStrategy.getValue() == 0) { //Offset. Use regular section behaviour return DrawViewSection::alignSectionFaces(faceIntersections); @@ -596,15 +643,25 @@ TopoDS_Shape DrawComplexSection::getShapeToIntersect() //Aligned return m_preparedShape; } + +TopoDS_Shape DrawComplexSection::getShapeForDetail() const +{ + if (ProjectionStrategy.getValue() == 0) {//Offset + return DrawViewSection::getShapeForDetail(); + } + //Aligned + return m_preparedShape; +} + TopoDS_Wire DrawComplexSection::makeProfileWire() const { - App::DocumentObject *toolObj = CuttingToolWireObject.getValue(); + App::DocumentObject* toolObj = CuttingToolWireObject.getValue(); return makeProfileWire(toolObj); } -TopoDS_Wire DrawComplexSection::makeProfileWire(App::DocumentObject *toolObj) +TopoDS_Wire DrawComplexSection::makeProfileWire(App::DocumentObject* toolObj) { -// Base::Console().Message("DCS::makeProfileWire()\n"); + // Base::Console().Message("DCS::makeProfileWire()\n"); if (!isProfileObject(toolObj)) { return TopoDS_Wire(); } @@ -627,7 +684,7 @@ TopoDS_Wire DrawComplexSection::makeProfileWire(App::DocumentObject *toolObj) gp_Vec DrawComplexSection::makeProfileVector(TopoDS_Wire profileWire) { -// Base::Console().Message("DCS::makeProfileVector()\n"); + // Base::Console().Message("DCS::makeProfileVector()\n"); TopoDS_Vertex tvFirst, tvLast; TopExp::Vertices(profileWire, tvFirst, tvLast); gp_Pnt gpFirst = BRep_Tool::Pnt(tvFirst); @@ -642,7 +699,7 @@ BaseGeomPtrVector DrawComplexSection::makeSectionLineGeometry() { // Base::Console().Message("DCS::makeSectionLineGeometry()\n"); BaseGeomPtrVector result; - DrawViewPart *baseDvp = dynamic_cast(BaseView.getValue()); + DrawViewPart* baseDvp = dynamic_cast(BaseView.getValue()); if (baseDvp) { TopoDS_Wire lineWire = makeSectionLineWire(); TopoDS_Shape projectedWire = @@ -673,7 +730,7 @@ std::pair DrawComplexSection::sectionLineEnds() Base::Vector3d first = Base::Vector3d(gpFirst.X(), gpFirst.Y(), gpFirst.Z()); Base::Vector3d last = Base::Vector3d(gpLast.X(), gpLast.Y(), gpLast.Z()); - DrawViewPart *baseDvp = dynamic_cast(BaseView.getValue()); + DrawViewPart* baseDvp = dynamic_cast(BaseView.getValue()); if (baseDvp) { first = baseDvp->projectPoint(first); last = baseDvp->projectPoint(last); @@ -688,7 +745,7 @@ std::pair DrawComplexSection::sectionArrowDirs() { // Base::Console().Message("DCS::sectionArrowDirs()\n"); std::pair result; - App::DocumentObject *toolObj = CuttingToolWireObject.getValue(); + App::DocumentObject* toolObj = CuttingToolWireObject.getValue(); TopoDS_Wire profileWire = makeProfileWire(toolObj); if (profileWire.IsNull()) { return result; @@ -707,7 +764,9 @@ std::pair DrawComplexSection::sectionArrowDirs() std::vector faces; TopExp_Explorer expl(toolFaceShape, TopAbs_FACE); - for (; expl.More(); expl.Next()) { faces.push_back(TopoDS::Face(expl.Current())); } + for (; expl.More(); expl.Next()) { + faces.push_back(TopoDS::Face(expl.Current())); + } gp_Vec gDir0 = gp_Vec(getFaceNormal(faces.front())); gp_Vec gDir1 = gp_Vec(getFaceNormal(faces.back())); @@ -727,7 +786,7 @@ std::pair DrawComplexSection::sectionArrowDirs() Base::Vector3d vDir1 = DU::toVector3d(gDir1); vDir0.Normalize(); vDir1.Normalize(); - DrawViewPart *baseDvp = dynamic_cast(BaseView.getValue()); + DrawViewPart* baseDvp = dynamic_cast(BaseView.getValue()); if (baseDvp) { vDir0 = baseDvp->projectPoint(vDir0, true); vDir1 = baseDvp->projectPoint(vDir1, true); @@ -742,8 +801,8 @@ std::pair DrawComplexSection::sectionArrowDirs() TopoDS_Wire DrawComplexSection::makeSectionLineWire() { TopoDS_Wire lineWire; - App::DocumentObject *toolObj = CuttingToolWireObject.getValue(); - DrawViewPart *baseDvp = dynamic_cast(BaseView.getValue()); + App::DocumentObject* toolObj = CuttingToolWireObject.getValue(); + DrawViewPart* baseDvp = dynamic_cast(BaseView.getValue()); if (baseDvp) { Base::Vector3d centroid = baseDvp->getCurrentCentroid(); TopoDS_Shape sTrans = @@ -775,7 +834,7 @@ ChangePointVector DrawComplexSection::getChangePointsFromSectionLine() // Base::Console().Message("DCS::getChangePointsFromSectionLine()\n"); ChangePointVector result; std::vector allPoints; - DrawViewPart *baseDvp = dynamic_cast(BaseView.getValue()); + DrawViewPart* baseDvp = dynamic_cast(BaseView.getValue()); if (baseDvp) { TopoDS_Wire lineWire = makeSectionLineWire(); TopoDS_Shape projectedWire = @@ -825,7 +884,7 @@ ChangePointVector DrawComplexSection::getChangePointsFromSectionLine() gp_Ax2 DrawComplexSection::getCSFromBase(const std::string sectionName) const { // Base::Console().Message("DCS::getCSFromBase()\n"); - App::DocumentObject *base = BaseView.getValue(); + App::DocumentObject* base = BaseView.getValue(); if (!base || !base->getTypeId().isDerivedFrom( TechDraw::DrawViewPart::getClassTypeId())) {//is second clause necessary? @@ -838,17 +897,18 @@ gp_Ax2 DrawComplexSection::getCSFromBase(const std::string sectionName) const //simple projection of a 3d vector onto the paper space gp_Vec DrawComplexSection::projectVector(const gp_Vec& vec) const { - HLRAlgo_Projector projector( getProjectionCS() ); + HLRAlgo_Projector projector(getProjectionCS()); gp_Pnt2d prjPnt; projector.Project(gp_Pnt(vec.XYZ()), prjPnt); return gp_Vec(prjPnt.X(), prjPnt.Y(), 0.0); } //static +//TODO: centralize all the projection routines scattered around the module! gp_Vec DrawComplexSection::projectVector(const gp_Vec& vec, gp_Ax2 sectionCS) { -// Base::Console().Message("DCS::projectVector(%s, CS)\n", DU::formatVector(vec).c_str()); - HLRAlgo_Projector projector( sectionCS ); + // Base::Console().Message("DCS::projectVector(%s, CS)\n", DU::formatVector(vec).c_str()); + HLRAlgo_Projector projector(sectionCS); gp_Pnt2d prjPnt; projector.Project(gp_Pnt(vec.XYZ()), prjPnt); return gp_Vec(prjPnt.X(), prjPnt.Y(), 0.0); @@ -875,7 +935,7 @@ gp_Pln DrawComplexSection::getSectionPlane() const bool DrawComplexSection::isBaseValid() const { - App::DocumentObject *base = BaseView.getValue(); + App::DocumentObject* base = BaseView.getValue(); if (!base) { //complex section is not based on an existing DVP return true; @@ -893,7 +953,7 @@ bool DrawComplexSection::isBaseValid() const //the shape after extrusion. As long as the profile is within the extent of the shape in the //extrude direction we should be ok. the extrude direction has to be perpendicular to the profile and SectionNormal bool DrawComplexSection::validateProfilePosition(TopoDS_Wire profileWire, gp_Ax2 sectionCS, - gp_Dir &gClosestBasis) const + gp_Dir& gClosestBasis) const { // Base::Console().Message("DCS::validateProfilePosition()\n"); gp_Vec gProfileVector = makeProfileVector(profileWire); @@ -955,7 +1015,7 @@ bool DrawComplexSection::showSegment(gp_Dir segmentNormal) const //Can we make a ComplexSection using this profile and sectionNormal? bool DrawComplexSection::canBuild(gp_Ax2 sectionCS, App::DocumentObject* profileObject) { -// Base::Console().Message("DCS::canBuild()\n"); + // Base::Console().Message("DCS::canBuild()\n"); if (!isProfileObject(profileObject)) { return false; } @@ -965,9 +1025,9 @@ bool DrawComplexSection::canBuild(gp_Ax2 sectionCS, App::DocumentObject* profile return true; } gp_Vec gProfileVec = makeProfileVector(makeProfileWire(profileObject)); - gProfileVec = projectVector(gProfileVec, sectionCS).Normalized(); + // gProfileVec = projectVector(gProfileVec, sectionCS).Normalized(); double dot = fabs(gProfileVec.Dot(sectionCS.Direction())); - if ( DU::fpCompare(dot, 1.0, EWTOLERANCE)) { + if (DU::fpCompare(dot, 1.0, EWTOLERANCE)) { return false; } return true; @@ -977,7 +1037,7 @@ bool DrawComplexSection::canBuild(gp_Ax2 sectionCS, App::DocumentObject* profile //make a "face" (not necessarily a TopoDS_Face since the extrusion of a wire is a shell) //from a single open wire by displacing the wire extruding it -TopoDS_Shape DrawComplexSection::extrudeWireToFace(TopoDS_Wire &wire, gp_Dir extrudeDir, +TopoDS_Shape DrawComplexSection::extrudeWireToFace(TopoDS_Wire& wire, gp_Dir extrudeDir, double extrudeDist) { gp_Trsf mov; @@ -992,7 +1052,7 @@ TopoDS_Shape DrawComplexSection::extrudeWireToFace(TopoDS_Wire &wire, gp_Dir ext //returns the normal of the face to be extruded into a cutting tool //the face is expected to be planar -gp_Dir DrawComplexSection::getFaceNormal(TopoDS_Face &face) +gp_Dir DrawComplexSection::getFaceNormal(TopoDS_Face& face) { BRepAdaptor_Surface adapt(face); double uParmFirst = adapt.FirstUParameter(); @@ -1010,7 +1070,7 @@ gp_Dir DrawComplexSection::getFaceNormal(TopoDS_Face &face) return normalDir; } -bool DrawComplexSection::boxesIntersect(TopoDS_Face &face, TopoDS_Shape &shape) +bool DrawComplexSection::boxesIntersect(TopoDS_Face& face, TopoDS_Shape& shape) { Bnd_Box box0, box1; BRepBndLib::Add(face, box0); @@ -1023,8 +1083,8 @@ bool DrawComplexSection::boxesIntersect(TopoDS_Face &face, TopoDS_Shape &shape) return true; } -TopoDS_Shape DrawComplexSection::shapeShapeIntersect(const TopoDS_Shape &shape0, - const TopoDS_Shape &shape1) +TopoDS_Shape DrawComplexSection::shapeShapeIntersect(const TopoDS_Shape& shape0, + const TopoDS_Shape& shape1) { BRepAlgoAPI_Common anOp; anOp.SetFuzzyValue(EWTOLERANCE); @@ -1042,8 +1102,8 @@ TopoDS_Shape DrawComplexSection::shapeShapeIntersect(const TopoDS_Shape &shape0, } //find all the intersecting regions of face and shape -std::vector DrawComplexSection::faceShapeIntersect(const TopoDS_Face &face, - const TopoDS_Shape &shape) +std::vector DrawComplexSection::faceShapeIntersect(const TopoDS_Face& face, + const TopoDS_Shape& shape) { // Base::Console().Message("DCS::faceShapeIntersect()\n"); TopoDS_Shape intersect = shapeShapeIntersect(face, shape); @@ -1081,12 +1141,14 @@ TopoDS_Wire DrawComplexSection::makeNoseToTailWire(TopoDS_Wire inWire) } BRepBuilderAPI_MakeWire mkWire; - for (auto &edge : sortedList) { mkWire.Add(edge); } + for (auto& edge : sortedList) { + mkWire.Add(edge); + } return mkWire.Wire(); } //static -bool DrawComplexSection::isProfileObject(App::DocumentObject *obj) +bool DrawComplexSection::isProfileObject(App::DocumentObject* obj) { //if the object's shape is a wire or an edge, then it can be a profile object TopoDS_Shape shape = Part::Feature::getShape(obj); @@ -1100,7 +1162,7 @@ bool DrawComplexSection::isProfileObject(App::DocumentObject *obj) return false; } -bool DrawComplexSection::isMultiSegmentProfile(App::DocumentObject *obj) +bool DrawComplexSection::isMultiSegmentProfile(App::DocumentObject* obj) { //if the object's shape is a wire or an edge, then it can be a profile object TopoDS_Shape shape = Part::Feature::getShape(obj); @@ -1129,7 +1191,7 @@ bool DrawComplexSection::isMultiSegmentProfile(App::DocumentObject *obj) } //check if the profile has curves in it -bool DrawComplexSection::isLinearProfile(App::DocumentObject *obj) +bool DrawComplexSection::isLinearProfile(App::DocumentObject* obj) { TopoDS_Shape shape = Part::Feature::getShape(obj); if (shape.IsNull()) { @@ -1180,7 +1242,7 @@ namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawComplexSectionPython, TechDraw::DrawComplexSection) -template<> const char *TechDraw::DrawComplexSectionPython::getViewProviderName() const +template<> const char* TechDraw::DrawComplexSectionPython::getViewProviderName() const { return "TechDrawGui::ViewProviderDrawingView"; } diff --git a/src/Mod/TechDraw/App/DrawComplexSection.h b/src/Mod/TechDraw/App/DrawComplexSection.h index 146f288329d6..d06e730c8390 100644 --- a/src/Mod/TechDraw/App/DrawComplexSection.h +++ b/src/Mod/TechDraw/App/DrawComplexSection.h @@ -50,23 +50,31 @@ class TechDrawExport DrawComplexSection: public DrawViewSection TopoDS_Shape makeCuttingTool(double dMax) override; gp_Ax2 getCSFromBase(const std::string sectionName) const override; bool isBaseValid() const override; - TopoDS_Compound findSectionPlaneIntersections(const TopoDS_Shape &cutShape) override; - TopoDS_Shape prepareShape(const TopoDS_Shape &cutShape, double shapeSize) override; + TopoDS_Compound findSectionPlaneIntersections(const TopoDS_Shape& cutShape) override; + TopoDS_Shape prepareShape(const TopoDS_Shape& cutShape, double shapeSize) override; TopoDS_Shape getShapeToPrepare() const override; TopoDS_Shape getShapeToIntersect() override; gp_Pln getSectionPlane() const override; TopoDS_Compound alignSectionFaces(TopoDS_Shape faceIntersections) override; std::pair sectionLineEnds() override; - bool boxesIntersect(TopoDS_Face &face, TopoDS_Shape &shape); - TopoDS_Shape shapeShapeIntersect(const TopoDS_Shape &shape0, const TopoDS_Shape &shape1); - std::vector faceShapeIntersect(const TopoDS_Face &face, const TopoDS_Shape &shape); - TopoDS_Shape extrudeWireToFace(TopoDS_Wire &wire, gp_Dir extrudeDir, double extrudeDist); - TopoDS_Shape makeAlignedPieces(const TopoDS_Shape &rawShape, const TopoDS_Shape &toolFaceShape, - double extrudeDistance); - TopoDS_Shape distributeAlignedPieces(std::vector pieces); - TopoDS_Compound singleToolIntersections(const TopoDS_Shape &cutShape); - TopoDS_Compound alignedToolIntersections(const TopoDS_Shape &cutShape); + void makeSectionCut(TopoDS_Shape& baseShape) override; + + void waitingForAlign(bool s) { m_waitingForAlign = s; } + bool waitingForAlign(void) const { return m_waitingForAlign; } + + TopoDS_Shape getShapeForDetail() const override; + +public Q_SLOTS: + void onSectionCutFinished(void) override; + + bool boxesIntersect(TopoDS_Face& face, TopoDS_Shape& shape); + TopoDS_Shape shapeShapeIntersect(const TopoDS_Shape& shape0, const TopoDS_Shape& shape1); + std::vector faceShapeIntersect(const TopoDS_Face& face, const TopoDS_Shape& shape); + TopoDS_Shape extrudeWireToFace(TopoDS_Wire& wire, gp_Dir extrudeDir, double extrudeDist); + void makeAlignedPieces(const TopoDS_Shape& rawShape); + TopoDS_Compound singleToolIntersections(const TopoDS_Shape& cutShape); + TopoDS_Compound alignedToolIntersections(const TopoDS_Shape& cutShape); BaseGeomPtrVector makeSectionLineGeometry(); std::pair sectionArrowDirs(); @@ -75,27 +83,34 @@ class TechDrawExport DrawComplexSection: public DrawViewSection ChangePointVector getChangePointsFromSectionLine() override; bool validateProfilePosition(TopoDS_Wire profileWire, gp_Ax2 sectionCS, - gp_Dir &gClosestBasis) const; + gp_Dir& gClosestBasis) const; bool showSegment(gp_Dir segmentNormal) const; gp_Vec projectVector(const gp_Vec& vec) const; TopoDS_Wire makeProfileWire() const; - static TopoDS_Wire makeProfileWire(App::DocumentObject *toolObj); + static TopoDS_Wire makeProfileWire(App::DocumentObject* toolObj); static TopoDS_Wire makeNoseToTailWire(TopoDS_Wire inWire); static gp_Vec makeProfileVector(TopoDS_Wire profileWire); - static bool isProfileObject(App::DocumentObject *obj); - static bool isMultiSegmentProfile(App::DocumentObject *obj); - static bool isLinearProfile(App::DocumentObject *obj); + static bool isProfileObject(App::DocumentObject* obj); + static bool isMultiSegmentProfile(App::DocumentObject* obj); + static bool isLinearProfile(App::DocumentObject* obj); static bool isTrulyEmpty(TopoDS_Shape inShape); static bool canBuild(gp_Ax2 sectionCS, App::DocumentObject* profileObject); static gp_Vec projectVector(const gp_Vec& vec, gp_Ax2 sectionCS); private: - gp_Dir getFaceNormal(TopoDS_Face &face); + gp_Dir getFaceNormal(TopoDS_Face& face); TopoDS_Shape m_toolFaceShape; + TopoDS_Shape m_alignResult; + TopoDS_Shape m_preparedShape;//saved for detail views + + QMetaObject::Connection connectAlignWatcher; + QFutureWatcher m_alignWatcher; + QFuture m_alignFuture; + bool m_waitingForAlign; - static const char *ProjectionStrategyEnums[]; + static const char* ProjectionStrategyEnums[]; }; using DrawComplexSectionPython = App::FeaturePythonT; diff --git a/src/Mod/TechDraw/App/DrawView.cpp b/src/Mod/TechDraw/App/DrawView.cpp index 2abda6ef8462..f8d4c46bb0af 100644 --- a/src/Mod/TechDraw/App/DrawView.cpp +++ b/src/Mod/TechDraw/App/DrawView.cpp @@ -323,12 +323,7 @@ std::vector DrawView::findAllParentPages() const DrawViewCollection *collection = nullptr; std::vector parentsAll = getInList(); - //prune the duplicates - std::sort(parentsAll.begin(), parentsAll.end()); - auto last = std::unique(parentsAll.begin(), parentsAll.end()); - parentsAll.erase(last, parentsAll.end()); - - for (auto& parent : parentsAll) { + for (auto& parent : parentsAll) { if (parent->getTypeId().isDerivedFrom(DrawPage::getClassTypeId())) { page = static_cast(parent); } else if (parent->getTypeId().isDerivedFrom(DrawViewCollection::getClassTypeId())) { @@ -341,10 +336,14 @@ std::vector DrawView::findAllParentPages() const } } + //prune the duplicates + std::sort(result.begin(), result.end()); + auto last = std::unique(result.begin(), result.end()); + result.erase(last, result.end()); + return result; } - bool DrawView::isInClip() { std::vector parent = getInList(); diff --git a/src/Mod/TechDraw/App/DrawViewDetail.cpp b/src/Mod/TechDraw/App/DrawViewDetail.cpp index fea6116fe80c..95414012c657 100644 --- a/src/Mod/TechDraw/App/DrawViewDetail.cpp +++ b/src/Mod/TechDraw/App/DrawViewDetail.cpp @@ -23,30 +23,30 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #endif #include @@ -54,8 +54,9 @@ #include #include -#include "DrawViewDetail.h" +#include "DrawComplexSection.h" #include "DrawUtil.h" +#include "DrawViewDetail.h" #include "DrawViewSection.h" #include "GeometryObject.h" #include "Preferences.h" @@ -69,26 +70,25 @@ using namespace TechDraw; PROPERTY_SOURCE(TechDraw::DrawViewDetail, TechDraw::DrawViewPart) -DrawViewDetail::DrawViewDetail() : - m_waitingForDetail(false), - m_saveDvp(nullptr), - m_saveDvs(nullptr) +DrawViewDetail::DrawViewDetail() : m_waitingForDetail(false), m_saveDvp(nullptr), m_saveDvs(nullptr) { - static const char *dgroup = "Detail"; + static const char* dgroup = "Detail"; - ADD_PROPERTY_TYPE(BaseView ,(nullptr), dgroup, App::Prop_None, "2D View source for this Section"); + ADD_PROPERTY_TYPE(BaseView, (nullptr), dgroup, App::Prop_None, + "2D View source for this Section"); BaseView.setScope(App::LinkScope::Global); - ADD_PROPERTY_TYPE(AnchorPoint ,(0, 0,0) ,dgroup, App::Prop_None, "Location of detail in BaseView"); + ADD_PROPERTY_TYPE(AnchorPoint, (0, 0, 0), dgroup, App::Prop_None, + "Location of detail in BaseView"); ADD_PROPERTY_TYPE(Radius, (10.0), dgroup, App::Prop_None, "Size of detail area"); - ADD_PROPERTY_TYPE(Reference ,("1"), dgroup, App::Prop_None, "An identifier for this detail"); + ADD_PROPERTY_TYPE(Reference, ("1"), dgroup, App::Prop_None, "An identifier for this detail"); getParameters(); m_fudge = 1.01; //hide Properties not relevant to DVDetail - Direction.setStatus(App::Property::ReadOnly, true); //Should be same as BaseView - Rotation.setStatus(App::Property::ReadOnly, true); //same as BaseView - ScaleType.setValue("Custom"); //dvd uses scale from BaseView + Direction.setStatus(App::Property::ReadOnly, true);//Should be same as BaseView + Rotation.setStatus(App::Property::ReadOnly, true); //same as BaseView + ScaleType.setValue("Custom"); //dvd uses scale from BaseView } DrawViewDetail::~DrawViewDetail() @@ -106,10 +106,8 @@ short DrawViewDetail::mustExecute() const TechDraw::DrawView::mustExecute(); } - if (AnchorPoint.isTouched() || - Radius.isTouched() || - BaseView.isTouched() || - Reference.isTouched()) { + if (AnchorPoint.isTouched() || Radius.isTouched() || BaseView.isTouched() + || Reference.isTouched()) { return 1; } @@ -124,16 +122,13 @@ void DrawViewDetail::onChanged(const App::Property* prop) } if (prop == &Reference) { - std::string lblText = "Detail " + - std::string(Reference.getValue()); + std::string lblText = "Detail " + std::string(Reference.getValue()); Label.setValue(lblText); } - if (prop == &Reference || - prop == &Radius || - prop == &BaseView) { + if (prop == &Reference || prop == &Radius || prop == &BaseView) { requestPaint(); } - if (prop == &AnchorPoint) { + if (prop == &AnchorPoint) { // to see AnchorPoint changes repainting is not enough, we must recompute recomputeFeature(true); } @@ -141,15 +136,15 @@ void DrawViewDetail::onChanged(const App::Property* prop) DrawViewPart::onChanged(prop); } -App::DocumentObjectExecReturn *DrawViewDetail::execute() +App::DocumentObjectExecReturn* DrawViewDetail::execute() { -// Base::Console().Message("DVD::execute() - %s\n", getNameInDocument()); + // Base::Console().Message("DVD::execute() - %s\n", getNameInDocument()); if (!keepUpdated()) { return DrawView::execute(); } App::DocumentObject* baseObj = BaseView.getValue(); - if (!baseObj) { + if (!baseObj) { return DrawView::execute(); } @@ -159,15 +154,18 @@ App::DocumentObjectExecReturn *DrawViewDetail::execute() } DrawViewPart* dvp = static_cast(baseObj); + TopoDS_Shape shape = dvp->getShapeForDetail(); DrawViewSection* dvs = nullptr; - TopoDS_Shape shape; if (dvp->isDerivedFrom(TechDraw::DrawViewSection::getClassTypeId())) { - dvs= static_cast(dvp); - shape = dvs->getCutShape(); - } else { - //getSourceShapeFused will complain if called on section - shape = dvp->getSourceShapeFused(); + dvs = static_cast(dvp); } + // TopoDS_Shape shape; + // shape = dvs->getCutShape(); + // } + // else { + // //getSourceShapeFused will complain if called on section + // shape = dvp->getSourceShapeFused(); + // } if (shape.IsNull()) { return DrawView::execute(); @@ -178,33 +176,31 @@ App::DocumentObjectExecReturn *DrawViewDetail::execute() //block touch/onChanged stuff Base::Vector3d newX = getXDirection(); XDirection.setValue(newX); - XDirection.purgeTouched(); //don't trigger updates! + XDirection.purgeTouched();//don't trigger updates! //unblock } detailExec(shape, dvp, dvs); addShapes2d(); - dvp->requestPaint(); //to refresh detail highlight in base view + dvp->requestPaint();//to refresh detail highlight in base view return DrawView::execute(); } //try to create a detail of the solids & shells in shape //if there are no solids/shells in shape, use the edges in shape -void DrawViewDetail::detailExec(TopoDS_Shape& shape, - DrawViewPart* dvp, - DrawViewSection* dvs) +void DrawViewDetail::detailExec(TopoDS_Shape& shape, DrawViewPart* dvp, DrawViewSection* dvs) { - if (waitingForHlr() || - waitingForDetail()) { + if (waitingForHlr() || waitingForDetail()) { return; } //note that &m_detailWatcher in the third parameter is not strictly required, but using the //4 parameter signature instead of the 3 parameter signature prevents clazy warning: //https://github.com/KDE/clazy/blob/1.11/docs/checks/README-connect-3arg-lambda.md - connectDetailWatcher = QObject::connect(&m_detailWatcher, &QFutureWatcherBase::finished, - &m_detailWatcher, [this] { this->onMakeDetailFinished(); }); + connectDetailWatcher = + QObject::connect(&m_detailWatcher, &QFutureWatcherBase::finished, &m_detailWatcher, + [this] { this->onMakeDetailFinished(); }); m_detailFuture = QtConcurrent::run(this, &DrawViewDetail::makeDetailShape, shape, dvp, dvs); m_detailWatcher.setFuture(m_detailFuture); waitingForDetail(true); @@ -213,9 +209,7 @@ void DrawViewDetail::detailExec(TopoDS_Shape& shape, //this runs in a separate thread since it can sometimes take a long time //make a common of the input shape and a cylinder (or prism depending on //the matting style) -void DrawViewDetail::makeDetailShape(TopoDS_Shape& shape, - DrawViewPart* dvp, - DrawViewSection* dvs) +void DrawViewDetail::makeDetailShape(TopoDS_Shape& shape, DrawViewPart* dvp, DrawViewSection* dvs) { showProgressMessage(getNameInDocument(), "is making detail shape"); @@ -232,30 +226,33 @@ void DrawViewDetail::makeDetailShape(TopoDS_Shape& shape, m_saveDvp = dvp; m_saveDvs = dvs; - gp_Pnt gpCenter = TechDraw::findCentroid(copyShape, - dirDetail); + gp_Pnt gpCenter = TechDraw::findCentroid(copyShape, dirDetail); Base::Vector3d shapeCenter = Base::Vector3d(gpCenter.X(), gpCenter.Y(), gpCenter.Z()); - m_saveCentroid = shapeCenter; //centroid of original shape + m_saveCentroid = shapeCenter;//centroid of original shape if (!dvs) { //section cutShape should already be on origin - copyShape = TechDraw::moveShape(copyShape, //centre shape on origin - -shapeCenter); + copyShape = TechDraw::moveShape(copyShape,//centre shape on origin + -shapeCenter); } shapeCenter = Base::Vector3d(0.0, 0.0, 0.0); - m_viewAxis = dvp->getProjectionCS(shapeCenter); //save the CS for later - Base::Vector3d anchor = AnchorPoint.getValue(); //this is a 2D point in unrotated base view coords - anchor = DrawUtil::toR3(m_viewAxis, anchor); //actual anchor coords in R3 + m_viewAxis = dvp->getProjectionCS(shapeCenter);//save the CS for later + Base::Vector3d anchor = AnchorPoint.getValue();//this is a 2D point in base view local coords + // double baseRotationRad = dvp->Rotation.getValue() * M_PI / 180.0; + // anchor.RotateZ(baseRotationRad); + + anchor = DrawUtil::toR3(m_viewAxis, anchor);//actual anchor coords in R3 + Bnd_Box bbxSource; bbxSource.SetGap(0.0); BRepBndLib::AddOptimal(copyShape, bbxSource); double diag = sqrt(bbxSource.SquareExtent()); - Base::Vector3d toolPlaneOrigin = anchor + dirDetail * diag * -1.0; //center tool about anchor + Base::Vector3d toolPlaneOrigin = anchor + dirDetail * diag * -1.0;//center tool about anchor double extrudeLength = 2.0 * toolPlaneOrigin.Length(); gp_Pnt gpnt(toolPlaneOrigin.x, toolPlaneOrigin.y, toolPlaneOrigin.z); @@ -270,22 +267,26 @@ void DrawViewDetail::makeDetailShape(TopoDS_Shape& shape, gp_Pln gpln(gpnt, gdir); BRepBuilderAPI_MakeFace mkFace(gpln, -radius, radius, -radius, radius); extrusionFace = mkFace.Face(); - if(extrusionFace.IsNull()) { - Base::Console().Warning("DVD::makeDetailShape - %s - failed to create tool base face\n", getNameInDocument()); + if (extrusionFace.IsNull()) { + Base::Console().Warning("DVD::makeDetailShape - %s - failed to create tool base face\n", + getNameInDocument()); return; } tool = BRepPrimAPI_MakePrism(extrusionFace, extrudeDir, false, true).Shape(); - if(tool.IsNull()) { - Base::Console().Warning("DVD::makeDetailShape - %s - failed to create tool (prism)\n", getNameInDocument()); + if (tool.IsNull()) { + Base::Console().Warning("DVD::makeDetailShape - %s - failed to create tool (prism)\n", + getNameInDocument()); return; } - } else { + } + else { //circular mat gp_Ax2 cs(gpnt, gdir); BRepPrimAPI_MakeCylinder mkTool(cs, radius, extrudeLength); tool = mkTool.Shape(); - if(tool.IsNull()) { - Base::Console().Warning("DVD::detailExec - %s - failed to create tool (cylinder)\n", getNameInDocument()); + if (tool.IsNull()) { + Base::Console().Warning("DVD::detailExec - %s - failed to create tool (cylinder)\n", + getNameInDocument()); return; } } @@ -296,7 +297,7 @@ void DrawViewDetail::makeDetailShape(TopoDS_Shape& shape, BRep_Builder builder; TopoDS_Compound pieces; builder.MakeCompound(pieces); - if (solidCount > 0) { + if (solidCount > 0) { TopExp_Explorer expl(copyShape, TopAbs_SOLID); for (; expl.More(); expl.Next()) { const TopoDS_Solid& s = TopoDS::Solid(expl.Current()); @@ -343,56 +344,48 @@ void DrawViewDetail::makeDetailShape(TopoDS_Shape& shape, } if (debugDetail()) { - BRepTools::Write(tool, "DVDTool.brep"); //debug - BRepTools::Write(copyShape, "DVDCopy.brep"); //debug - BRepTools::Write(pieces, "DVDCommon.brep"); //debug + BRepTools::Write(tool, "DVDTool.brep"); //debug + BRepTools::Write(copyShape, "DVDCopy.brep");//debug + BRepTools::Write(pieces, "DVDCommon.brep"); //debug } gp_Pnt inputCenter; try { //centroid of result - inputCenter = TechDraw::findCentroid(pieces, - dirDetail); - Base::Vector3d centroid(inputCenter.X(), - inputCenter.Y(), - inputCenter.Z()); - m_saveCentroid += centroid; //center of massaged shape - - if ((solidCount > 0) || - (shellCount > 0)) { + inputCenter = TechDraw::findCentroid(pieces, dirDetail); + Base::Vector3d centroid(inputCenter.X(), inputCenter.Y(), inputCenter.Z()); + m_saveCentroid += centroid;//center of massaged shape + + if ((solidCount > 0) || (shellCount > 0)) { //align shape with detail anchor - TopoDS_Shape centeredShape = TechDraw::moveShape(pieces, - anchor * -1.0); - m_scaledShape = TechDraw::scaleShape(centeredShape, - getScale()); + TopoDS_Shape centeredShape = TechDraw::moveShape(pieces, anchor * -1.0); + m_scaledShape = TechDraw::scaleShape(centeredShape, getScale()); if (debugDetail()) { - BRepTools::Write(m_scaledShape, "DVDScaled.brep"); //debug + BRepTools::Write(m_scaledShape, "DVDScaled.brep");//debug } - } else { + } + else { //no solids, no shells, do what you can with edges TopoDS_Shape projectedEdges = projectEdgesOntoFace(copyShape, extrusionFace, gdir); - TopoDS_Shape centeredShape = TechDraw::moveShape(projectedEdges, - anchor * -1.0); + TopoDS_Shape centeredShape = TechDraw::moveShape(projectedEdges, anchor * -1.0); if (debugDetail()) { - BRepTools::Write(projectedEdges, "DVDProjectedEdges.brep"); //debug - BRepTools::Write(centeredShape, "DVDCenteredShape.brep"); //debug + BRepTools::Write(projectedEdges, "DVDProjectedEdges.brep");//debug + BRepTools::Write(centeredShape, "DVDCenteredShape.brep"); //debug } - m_scaledShape = TechDraw::scaleShape(centeredShape, - getScale()); + m_scaledShape = TechDraw::scaleShape(centeredShape, getScale()); } Base::Vector3d stdOrg(0.0, 0.0, 0.0); m_viewAxis = dvp->getProjectionCS(stdOrg); if (!DrawUtil::fpCompare(Rotation.getValue(), 0.0)) { - m_scaledShape = TechDraw::rotateShape(m_scaledShape, - m_viewAxis, - Rotation.getValue()); + m_scaledShape = TechDraw::rotateShape(m_scaledShape, m_viewAxis, Rotation.getValue()); } - } //end try block + }//end try block catch (Standard_Failure& e1) { - Base::Console().Message("DVD::makeDetailShape - failed to create detail %s - %s **\n", getNameInDocument(), e1.GetMessageString()); + Base::Console().Message("DVD::makeDetailShape - failed to create detail %s - %s **\n", + getNameInDocument(), e1.GetMessageString()); return; } @@ -401,11 +394,12 @@ void DrawViewDetail::makeDetailShape(TopoDS_Shape& shape, void DrawViewDetail::postHlrTasks(void) { -// Base::Console().Message("DVD::postHlrTasks()\n"); + // Base::Console().Message("DVD::postHlrTasks()\n"); DrawViewPart::postHlrTasks(); geometryObject->pruneVertexGeom(Base::Vector3d(0.0, 0.0, 0.0), - Radius.getValue() * getScale()); //remove vertices beyond clipradius + Radius.getValue() + * getScale());//remove vertices beyond clipradius //second pass if required if (ScaleType.isValue("Automatic") && !checkFit()) { @@ -424,28 +418,24 @@ void DrawViewDetail::onMakeDetailFinished(void) QObject::disconnect(connectDetailWatcher); //ancestor's buildGeometryObject will run HLR and face finding in a separate thread - m_tempGeometryObject = buildGeometryObject(m_scaledShape, m_viewAxis); - + m_tempGeometryObject = buildGeometryObject(m_scaledShape, m_viewAxis); } bool DrawViewDetail::waitingForResult() const { - if (DrawViewPart::waitingForResult() || - waitingForDetail()) { + if (DrawViewPart::waitingForResult() || waitingForDetail()) { return true; } return false; } -TopoDS_Shape DrawViewDetail::projectEdgesOntoFace(TopoDS_Shape &edgeShape, - TopoDS_Face &projFace, +TopoDS_Shape DrawViewDetail::projectEdgesOntoFace(TopoDS_Shape& edgeShape, TopoDS_Face& projFace, gp_Dir& projDir) { BRep_Builder builder; TopoDS_Compound edges; builder.MakeCompound(edges); TopExp_Explorer Ex(edgeShape, TopAbs_EDGE); - while (Ex.More()) - { + while (Ex.More()) { TopoDS_Edge e = TopoDS::Edge(Ex.Current()); BRepProj_Projection mkProj(e, projFace, projDir); if (mkProj.IsDone()) { @@ -454,7 +444,7 @@ TopoDS_Shape DrawViewDetail::projectEdgesOntoFace(TopoDS_Shape &edgeShape, Ex.Next(); } if (debugDetail()) { - BRepTools::Write(edges, "DVDEdges.brep"); //debug + BRepTools::Write(edges, "DVDEdges.brep");//debug } return TopoDS_Shape(std::move(edges)); @@ -467,22 +457,22 @@ std::vector DrawViewDetail::getDetailRefs() const return std::vector(); } -double DrawViewDetail::getFudgeRadius() -{ - return Radius.getValue() * m_fudge; -} +double DrawViewDetail::getFudgeRadius() { return Radius.getValue() * m_fudge; } bool DrawViewDetail::debugDetail() const { - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/debug"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/debug"); return hGrp->GetBool("debugDetail", false); } void DrawViewDetail::unsetupObject() { -// Base::Console().Message("DVD::unsetupObject()\n"); + // Base::Console().Message("DVD::unsetupObject()\n"); App::DocumentObject* baseObj = BaseView.getValue(); DrawView* base = dynamic_cast(baseObj); if (base) { @@ -490,20 +480,20 @@ void DrawViewDetail::unsetupObject() } } -void DrawViewDetail::getParameters() -{ -} +void DrawViewDetail::getParameters() {} // Python Drawing feature --------------------------------------------------------- -namespace App { +namespace App +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewDetailPython, TechDraw::DrawViewDetail) -template<> const char* TechDraw::DrawViewDetailPython::getViewProviderName() const { +template<> const char* TechDraw::DrawViewDetailPython::getViewProviderName() const +{ return "TechDrawGui::ViewProviderViewPart"; } /// @endcond // explicit template instantiation template class TechDrawExport FeaturePythonT; -} +}// namespace App diff --git a/src/Mod/TechDraw/App/DrawViewDimension.cpp b/src/Mod/TechDraw/App/DrawViewDimension.cpp index 30f9f1320d8c..aecea1d5301a 100644 --- a/src/Mod/TechDraw/App/DrawViewDimension.cpp +++ b/src/Mod/TechDraw/App/DrawViewDimension.cpp @@ -193,6 +193,7 @@ void DrawViewDimension::onChanged(const App::Property* prop) Base::Console().Warning("%s has no 3D References but is Type: True\n", getNameInDocument()); MeasureType.setValue("Projected"); } + return; } else if (prop == &References3D) { //have to rebuild the Measurement object // Base::Console().Message("DVD::onChanged - References3D\n"); @@ -202,6 +203,7 @@ void DrawViewDimension::onChanged(const App::Property* prop) } else if (MeasureType.isValue("True")) { //empty 3dRefs, but True MeasureType.touch(); //run MeasureType logic for this case } + return; } else if (prop == &Type) { //why?? FormatSpec.setValue(getDefaultFormatSpec().c_str()); @@ -215,6 +217,7 @@ void DrawViewDimension::onChanged(const App::Property* prop) OverTolerance.setUnit(Base::Unit::Length); UnderTolerance.setUnit(Base::Unit::Length); } + return; } else if (prop == &TheoreticalExact) { // if TheoreticalExact disable tolerances and set them to zero @@ -237,7 +240,7 @@ void DrawViewDimension::onChanged(const App::Property* prop) FormatSpecUnderTolerance.setReadOnly(false); } } - requestPaint(); + return; } else if (prop == &EqualTolerance) { // if EqualTolerance set negated overtolerance for untertolerance @@ -261,7 +264,7 @@ void DrawViewDimension::onChanged(const App::Property* prop) FormatSpecUnderTolerance.setReadOnly(false); } } - requestPaint(); + return; } else if (prop == &OverTolerance) { // if EqualTolerance set negated overtolerance for untertolerance @@ -269,27 +272,19 @@ void DrawViewDimension::onChanged(const App::Property* prop) UnderTolerance.setValue(-1.0 * OverTolerance.getValue()); UnderTolerance.setUnit(OverTolerance.getUnit()); } - requestPaint(); + return; } else if (prop == &FormatSpecOverTolerance) { if (!ArbitraryTolerances.getValue()) { FormatSpecUnderTolerance.setValue(FormatSpecOverTolerance.getValue()); } - requestPaint(); + return; } else if (prop == &FormatSpecUnderTolerance) { if (!ArbitraryTolerances.getValue()) { FormatSpecOverTolerance.setValue(FormatSpecUnderTolerance.getValue()); } - requestPaint(); - } - else if ( (prop == &FormatSpec) || - (prop == &Arbitrary) || - (prop == &ArbitraryTolerances) || - (prop == &MeasureType) || - (prop == &UnderTolerance) || - (prop == &Inverted) ) { - requestPaint(); + return; } } @@ -353,21 +348,9 @@ void DrawViewDimension::handleChangedPropertyType(Base::XMLReader &reader, const short DrawViewDimension::mustExecute() const { if (!isRestoring()) { - if ( - References2D.isTouched() || - Type.isTouched() || - FormatSpec.isTouched() || - Arbitrary.isTouched() || - FormatSpecOverTolerance.isTouched() || - FormatSpecUnderTolerance.isTouched() || - ArbitraryTolerances.isTouched() || - MeasureType.isTouched() || - TheoreticalExact.isTouched() || - EqualTolerance.isTouched() || - OverTolerance.isTouched() || - UnderTolerance.isTouched() || - Inverted.isTouched() - ) { + if (References2D.isTouched() || + References3D.isTouched() || + Type.isTouched() ) { return true; } } @@ -377,6 +360,7 @@ short DrawViewDimension::mustExecute() const App::DocumentObjectExecReturn *DrawViewDimension::execute() { +// Base::Console().Message("DVD::execute() - %s\n", getNameInDocument()); if (!keepUpdated()) { return App::DocumentObject::StdReturn; } @@ -396,12 +380,7 @@ App::DocumentObjectExecReturn *DrawViewDimension::execute() //can't do anything until Source has geometry if (!getViewPart()->hasGeometry()) { //happens when loading saved document - //if (isRestoring() || - // getDocument()->testStatus(App::Document::Status::Restoring)) { - return App::DocumentObject::StdReturn; - //} else { - // return App::DocumentObject::StdReturn; - //} + return App::DocumentObject::StdReturn; } //now we can check if Reference2ds have valid targets. diff --git a/src/Mod/TechDraw/App/DrawViewPart.cpp b/src/Mod/TechDraw/App/DrawViewPart.cpp index 509e8ec1d818..8a33893643bb 100644 --- a/src/Mod/TechDraw/App/DrawViewPart.cpp +++ b/src/Mod/TechDraw/App/DrawViewPart.cpp @@ -25,23 +25,18 @@ #include "PreCompiled.h" #ifndef _PreComp_ -#include -#include -#include -#include #include #include -#include #include #include -#include #include +#include #include -#include -#include -#include -#include +#include +#include +#include #include +#include #include #include #include @@ -51,6 +46,11 @@ #include #include #include +#include +#include +#include +#include +#include #endif #include @@ -60,8 +60,6 @@ #include #include -#include "DrawViewPart.h" -#include "DrawViewPartPy.h" // generated from DrawViewPartPy.xml #include "Cosmetic.h" #include "DrawGeomHatch.h" #include "DrawHatch.h" @@ -71,6 +69,8 @@ #include "DrawViewBalloon.h" #include "DrawViewDetail.h" #include "DrawViewDimension.h" +#include "DrawViewPart.h" +#include "DrawViewPartPy.h"// generated from DrawViewPartPy.xml #include "DrawViewSection.h" #include "EdgeWalker.h" #include "Geometry.h" @@ -87,53 +87,60 @@ using DU = DrawUtil; //PROPERTY_SOURCE(TechDraw::DrawViewPart, TechDraw::DrawView) -PROPERTY_SOURCE_WITH_EXTENSIONS(TechDraw::DrawViewPart, - TechDraw::DrawView) +PROPERTY_SOURCE_WITH_EXTENSIONS(TechDraw::DrawViewPart, TechDraw::DrawView) -DrawViewPart::DrawViewPart(void) : - geometryObject(nullptr), - m_tempGeometryObject(nullptr), - m_waitingForFaces(false), - m_waitingForHlr(false) +DrawViewPart::DrawViewPart(void) + : geometryObject(nullptr), m_tempGeometryObject(nullptr), m_waitingForFaces(false), + m_waitingForHlr(false) { - static const char *group = "Projection"; - static const char *sgroup = "HLR Parameters"; + static const char* group = "Projection"; + static const char* sgroup = "HLR Parameters"; nowUnsetting = false; m_handleFaces = false; CosmeticExtension::initExtension(this); - Base::Reference hGrp = App::GetApplication(). - GetUserParameter().GetGroup("BaseApp")-> - GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/General"); double defDist = hGrp->GetFloat("FocusDistance", 100.0); //properties that affect Geometry - ADD_PROPERTY_TYPE(Source ,(nullptr), group, App::Prop_None, "3D Shape to view"); + ADD_PROPERTY_TYPE(Source, (nullptr), group, App::Prop_None, "3D Shape to view"); Source.setScope(App::LinkScope::Global); Source.setAllowExternal(true); - ADD_PROPERTY_TYPE(XSource ,(nullptr), group, App::Prop_None, "External 3D Shape to view"); + ADD_PROPERTY_TYPE(XSource, (nullptr), group, App::Prop_None, "External 3D Shape to view"); - ADD_PROPERTY_TYPE(Direction ,(0.0, -1.0, 0.0), - group, App::Prop_None, "Projection Plane normal. The direction you are looking from."); - ADD_PROPERTY_TYPE(XDirection ,(0.0, 0.0, 0.0), - group, App::Prop_None, "Projection Plane X Axis in R3. Rotates/Mirrors View"); - ADD_PROPERTY_TYPE(Perspective ,(false), group, App::Prop_None, + ADD_PROPERTY_TYPE(Direction, (0.0, -1.0, 0.0), group, App::Prop_None, + "Projection Plane normal. The direction you are looking from."); + ADD_PROPERTY_TYPE(XDirection, (0.0, 0.0, 0.0), group, App::Prop_None, + "Projection Plane X Axis in R3. Rotates/Mirrors View"); + ADD_PROPERTY_TYPE(Perspective, (false), group, App::Prop_None, "Perspective(true) or Orthographic(false) projection"); ADD_PROPERTY_TYPE(Focus, (defDist), group, App::Prop_None, "Perspective view focus distance"); //properties that control HLR algo bool coarseView = hGrp->GetBool("CoarseView", false); ADD_PROPERTY_TYPE(CoarseView, (coarseView), sgroup, App::Prop_None, "Coarse View on/off"); - ADD_PROPERTY_TYPE(SmoothVisible ,(prefSmoothViz()), sgroup, App::Prop_None, "Show Visible Smooth lines"); - ADD_PROPERTY_TYPE(SeamVisible ,(prefSeamViz()), sgroup, App::Prop_None, "Show Visible Seam lines"); - ADD_PROPERTY_TYPE(IsoVisible ,(prefIsoViz()), sgroup, App::Prop_None, "Show Visible Iso u, v lines"); - ADD_PROPERTY_TYPE(HardHidden ,(prefHardHid()), sgroup, App::Prop_None, "Show Hidden Hard lines"); - ADD_PROPERTY_TYPE(SmoothHidden ,(prefSmoothHid()), sgroup, App::Prop_None, "Show Hidden Smooth lines"); - ADD_PROPERTY_TYPE(SeamHidden ,(prefSeamHid()), sgroup, App::Prop_None, "Show Hidden Seam lines"); - ADD_PROPERTY_TYPE(IsoHidden ,(prefIsoHid()), sgroup, App::Prop_None, "Show Hidden Iso u, v lines"); - ADD_PROPERTY_TYPE(IsoCount ,(prefIsoCount()), sgroup, App::Prop_None, "Number of iso parameters lines"); + ADD_PROPERTY_TYPE(SmoothVisible, (prefSmoothViz()), sgroup, App::Prop_None, + "Show Visible Smooth lines"); + ADD_PROPERTY_TYPE(SeamVisible, (prefSeamViz()), sgroup, App::Prop_None, + "Show Visible Seam lines"); + ADD_PROPERTY_TYPE(IsoVisible, (prefIsoViz()), sgroup, App::Prop_None, + "Show Visible Iso u, v lines"); + ADD_PROPERTY_TYPE(HardHidden, (prefHardHid()), sgroup, App::Prop_None, + "Show Hidden Hard lines"); + ADD_PROPERTY_TYPE(SmoothHidden, (prefSmoothHid()), sgroup, App::Prop_None, + "Show Hidden Smooth lines"); + ADD_PROPERTY_TYPE(SeamHidden, (prefSeamHid()), sgroup, App::Prop_None, + "Show Hidden Seam lines"); + ADD_PROPERTY_TYPE(IsoHidden, (prefIsoHid()), sgroup, App::Prop_None, + "Show Hidden Iso u, v lines"); + ADD_PROPERTY_TYPE(IsoCount, (prefIsoCount()), sgroup, App::Prop_None, + "Number of iso parameters lines"); //initialize bbox to non-garbage bbox = Base::BoundBox3d(Base::Vector3d(0.0, 0.0, 0.0), 0.0); @@ -155,7 +162,7 @@ DrawViewPart::~DrawViewPart() std::vector DrawViewPart::getSourceShape2d() const { -// Base::Console().Message("DVP::getSourceShape2d()\n"); + // Base::Console().Message("DVP::getSourceShape2d()\n"); std::vector result; const std::vector& links = getAllSources(); result = ShapeExtractor::getShapes2d(links); @@ -164,9 +171,9 @@ std::vector DrawViewPart::getSourceShape2d() const TopoDS_Shape DrawViewPart::getSourceShape() const { -// Base::Console().Message("DVP::getSourceShape()\n"); + // Base::Console().Message("DVP::getSourceShape()\n"); const std::vector& links = getAllSources(); - if (links.empty()) { + if (links.empty()) { return TopoDS_Shape(); } return ShapeExtractor::getShapes(links); @@ -174,17 +181,22 @@ TopoDS_Shape DrawViewPart::getSourceShape() const TopoDS_Shape DrawViewPart::getSourceShapeFused() const { -// Base::Console().Message("DVP::getSourceShapeFused()\n"); + // Base::Console().Message("DVP::getSourceShapeFused()\n"); const std::vector& links = getAllSources(); - if (links.empty()) { + if (links.empty()) { return TopoDS_Shape(); } return ShapeExtractor::getShapesFused(links); } +TopoDS_Shape DrawViewPart::getShapeForDetail() const +{ + return TechDraw::rotateShape(getSourceShapeFused(), getProjectionCS(), Rotation.getValue()); +} + std::vector DrawViewPart::getAllSources() const { -// Base::Console().Message("DVP::getAllSources()\n"); + // Base::Console().Message("DVP::getAllSources()\n"); std::vector links = Source.getValues(); std::vector xLinks = XSource.getValues(); @@ -200,7 +212,7 @@ std::vector DrawViewPart::getAllSources() const void DrawViewPart::addShapes2d(void) { std::vector shapes = getSourceShape2d(); - for (auto& s: shapes) { + for (auto& s : shapes) { //just vertices for now if (s.ShapeType() == TopAbs_VERTEX) { gp_Pnt gp = BRep_Tool::Pnt(TopoDS::Vertex(s)); @@ -210,26 +222,27 @@ void DrawViewPart::addShapes2d(void) Base::Vector3d projected = projectPoint(vp * getScale()); TechDraw::VertexPtr v1(std::make_shared(projected)); geometryObject->addVertex(v1); - } else if (s.ShapeType() == TopAbs_EDGE) { - //not supporting edges yet. -// Base::Console().Message("DVP::add2dShapes - found loose edge - isNull: %d\n", s.IsNull()); -// TopoDS_Shape sTrans = TechDraw::moveShape(s, -// m_saveCentroid * -1.0); -// TopoDS_Shape sScale = TechDraw::scaleShape(sTrans, -// getScale()); -// TopoDS_Shape sMirror = TechDraw::mirrorShape(sScale); -// TopoDS_Edge edge = TopoDS::Edge(sMirror); -// BaseGeomPtr bg = projectEdge(edge); - -// geometryObject->addEdge(bg); + } + else if (s.ShapeType() == TopAbs_EDGE) { + //not supporting edges yet. + // Base::Console().Message("DVP::add2dShapes - found loose edge - isNull: %d\n", s.IsNull()); + // TopoDS_Shape sTrans = TechDraw::moveShape(s, + // m_saveCentroid * -1.0); + // TopoDS_Shape sScale = TechDraw::scaleShape(sTrans, + // getScale()); + // TopoDS_Shape sMirror = TechDraw::mirrorShape(sScale); + // TopoDS_Edge edge = TopoDS::Edge(sMirror); + // BaseGeomPtr bg = projectEdge(edge); + + // geometryObject->addEdge(bg); //save connection between source feat and this edge } } } -App::DocumentObjectExecReturn *DrawViewPart::execute(void) +App::DocumentObjectExecReturn* DrawViewPart::execute(void) { -// Base::Console().Message("DVP::execute() - %s\n", getNameInDocument()); + // Base::Console().Message("DVP::execute() - %s\n", getNameInDocument()); if (!keepUpdated()) { return DrawView::execute(); } @@ -240,8 +253,7 @@ App::DocumentObjectExecReturn *DrawViewPart::execute(void) TopoDS_Shape shape = getSourceShape(); if (shape.IsNull()) { - Base::Console().Message("DVP::execute - %s - Source shape is Null.\n", - getNameInDocument()); + Base::Console().Message("DVP::execute - %s - Source shape is Null.\n", getNameInDocument()); return DrawView::execute(); } @@ -249,7 +261,7 @@ App::DocumentObjectExecReturn *DrawViewPart::execute(void) if (!checkXDirection()) { Base::Vector3d newX = getXDirection(); XDirection.setValue(newX); - XDirection.purgeTouched(); //don't trigger updates! + XDirection.purgeTouched();//don't trigger updates! } m_saveShape = shape; @@ -264,24 +276,12 @@ short DrawViewPart::mustExecute() const return TechDraw::DrawView::mustExecute(); } - if (Direction.isTouched() || - Source.isTouched() || - XSource.isTouched() || - Perspective.isTouched() || - Focus.isTouched() || - Rotation.isTouched() || - SmoothVisible.isTouched() || - SeamVisible.isTouched() || - IsoVisible.isTouched() || - HardHidden.isTouched() || - SmoothHidden.isTouched() || - SeamHidden.isTouched() || - IsoHidden.isTouched() || - IsoCount.isTouched() || - CoarseView.isTouched() || - CosmeticVertexes.isTouched() || - CosmeticEdges.isTouched() || - CenterLines.isTouched()) { + if (Direction.isTouched() || Source.isTouched() || XSource.isTouched() + || Perspective.isTouched() || Focus.isTouched() || Rotation.isTouched() + || SmoothVisible.isTouched() || SeamVisible.isTouched() || IsoVisible.isTouched() + || HardHidden.isTouched() || SmoothHidden.isTouched() || SeamHidden.isTouched() + || IsoHidden.isTouched() || IsoCount.isTouched() || CoarseView.isTouched() + || CosmeticVertexes.isTouched() || CosmeticEdges.isTouched() || CenterLines.isTouched()) { return 1; } @@ -302,7 +302,7 @@ void DrawViewPart::onChanged(const App::Property* prop) void DrawViewPart::partExec(TopoDS_Shape& shape) { -// Base::Console().Message("DVP::partExec() - %s\n", getNameInDocument()); + // Base::Console().Message("DVP::partExec() - %s\n", getNameInDocument()); if (waitingForHlr()) { //finish what we are already doing before starting a new cycle return; @@ -310,67 +310,63 @@ void DrawViewPart::partExec(TopoDS_Shape& shape) //we need to keep using the old geometryObject until the new one is fully populated m_tempGeometryObject = makeGeometryForShape(shape); - if (CoarseView.getValue()){ - onHlrFinished(); //poly algo does not run in separate thread, so we need to invoke - //the post hlr processing manually + if (CoarseView.getValue()) { + onHlrFinished();//poly algo does not run in separate thread, so we need to invoke + //the post hlr processing manually } } //prepare the shape for HLR processing by centering, scaling and rotating it GeometryObjectPtr DrawViewPart::makeGeometryForShape(TopoDS_Shape& shape) { -// Base::Console().Message("DVP::makeGeometryForShape() - %s\n", getNameInDocument()); + // Base::Console().Message("DVP::makeGeometryForShape() - %s\n", getNameInDocument()); gp_Pnt inputCenter; Base::Vector3d stdOrg(0.0, 0.0, 0.0); gp_Ax2 viewAxis = getProjectionCS(stdOrg); - inputCenter = TechDraw::findCentroid(shape, - viewAxis); - Base::Vector3d centroid(inputCenter.X(), - inputCenter.Y(), - inputCenter.Z()); + inputCenter = TechDraw::findCentroid(shape, viewAxis); + Base::Vector3d centroid(inputCenter.X(), inputCenter.Y(), inputCenter.Z()); //center shape on origin - TopoDS_Shape centeredShape = TechDraw::moveShape(shape, - centroid * -1.0); + TopoDS_Shape centeredShape = TechDraw::moveShape(shape, centroid * -1.0); m_saveCentroid = centroid; m_saveShape = centeredShape; - TopoDS_Shape scaledShape = TechDraw::scaleShape(centeredShape, - getScale()); + TopoDS_Shape scaledShape = TechDraw::scaleShape(centeredShape, getScale()); if (!DrawUtil::fpCompare(Rotation.getValue(), 0.0)) { - scaledShape = TechDraw::rotateShape(scaledShape, - viewAxis, - Rotation.getValue()); //conventional rotation - } - BRepTools::Write(scaledShape, "DVPScaled.brep"); //debug - GeometryObjectPtr go = buildGeometryObject(scaledShape, viewAxis); + scaledShape = TechDraw::rotateShape(scaledShape, viewAxis, + Rotation.getValue());//conventional rotation + } + BRepTools::Write(scaledShape, "DVPScaled.brep");//debug + GeometryObjectPtr go = buildGeometryObject(scaledShape, viewAxis); return go; } //create a geometry object and trigger the HLR process in another thread -TechDraw::GeometryObjectPtr DrawViewPart::buildGeometryObject(TopoDS_Shape& shape, const gp_Ax2 &viewAxis) +TechDraw::GeometryObjectPtr DrawViewPart::buildGeometryObject(TopoDS_Shape& shape, + const gp_Ax2& viewAxis) { -// Base::Console().Message("DVP::buildGeometryObject() - %s\n", getNameInDocument()); + // Base::Console().Message("DVP::buildGeometryObject() - %s\n", getNameInDocument()); showProgressMessage(getNameInDocument(), "is finding hidden lines"); - TechDraw::GeometryObjectPtr go(std::make_shared(getNameInDocument(), this)); + TechDraw::GeometryObjectPtr go( + std::make_shared(getNameInDocument(), this)); go->setIsoCount(IsoCount.getValue()); go->isPerspective(Perspective.getValue()); go->setFocus(Focus.getValue()); go->usePolygonHLR(CoarseView.getValue()); - if (CoarseView.getValue()){ + if (CoarseView.getValue()) { //the polygon approximation HLR process runs quickly, so doesn't need to be in a //separate thread - go->projectShapeWithPolygonAlgo(shape, - viewAxis); - } else { + go->projectShapeWithPolygonAlgo(shape, viewAxis); + } + else { //projectShape (the HLR process) runs in a separate thread since it can take a long time //note that &m_hlrWatcher in the third parameter is not strictly required, but using the //4 parameter signature instead of the 3 parameter signature prevents clazy warning: //https://github.com/KDE/clazy/blob/1.11/docs/checks/README-connect-3arg-lambda.md connectHlrWatcher = QObject::connect(&m_hlrWatcher, &QFutureWatcherBase::finished, - &m_hlrWatcher, [this] { this->onHlrFinished(); } ); + &m_hlrWatcher, [this] { this->onHlrFinished(); }); m_hlrFuture = QtConcurrent::run(go.get(), &GeometryObject::projectShape, shape, viewAxis); m_hlrWatcher.setFuture(m_hlrFuture); waitingForHlr(true); @@ -381,12 +377,12 @@ TechDraw::GeometryObjectPtr DrawViewPart::buildGeometryObject(TopoDS_Shape& shap //continue processing after hlr thread completes void DrawViewPart::onHlrFinished(void) { -// Base::Console().Message("DVP::onHlrFinished() - %s\n", getNameInDocument()); + // Base::Console().Message("DVP::onHlrFinished() - %s\n", getNameInDocument()); //now that the new GeometryObject is fully populated, we can replace the old one if (m_tempGeometryObject) { - geometryObject = m_tempGeometryObject; //replace with new - m_tempGeometryObject = nullptr; //superfluous? + geometryObject = m_tempGeometryObject;//replace with new + m_tempGeometryObject = nullptr; //superfluous? } if (!geometryObject) { throw Base::RuntimeError("DrawViewPart has lost its geometry"); @@ -399,24 +395,26 @@ void DrawViewPart::onHlrFinished(void) QObject::disconnect(connectHlrWatcher); showProgressMessage(getNameInDocument(), "has finished finding hidden lines"); - postHlrTasks(); //application level tasks that depend on HLR/GO being complete + postHlrTasks();//application level tasks that depend on HLR/GO being complete //start face finding in a separate thread. We don't find faces when using the polygon //HLR method. - if (handleFaces() && !CoarseView.getValue() ) { + if (handleFaces() && !CoarseView.getValue()) { try { //note that &m_faceWatcher in the third parameter is not strictly required, but using the //4 parameter signature instead of the 3 parameter signature prevents clazy warning: //https://github.com/KDE/clazy/blob/1.11/docs/checks/README-connect-3arg-lambda.md - connectFaceWatcher = QObject::connect(&m_faceWatcher, &QFutureWatcherBase::finished, - &m_faceWatcher, [this] { this->onFacesFinished(); }); + connectFaceWatcher = + QObject::connect(&m_faceWatcher, &QFutureWatcherBase::finished, &m_faceWatcher, + [this] { this->onFacesFinished(); }); m_faceFuture = QtConcurrent::run(this, &DrawViewPart::extractFaces); m_faceWatcher.setFuture(m_faceFuture); waitingForFaces(true); } catch (Standard_Failure& e) { waitingForFaces(false); - Base::Console().Error("DVP::partExec - %s - extractFaces failed - %s **\n", getNameInDocument(), e.GetMessageString()); + Base::Console().Error("DVP::partExec - %s - extractFaces failed - %s **\n", + getNameInDocument(), e.GetMessageString()); throw Base::RuntimeError("DVP::onHlrFinished - error extracting faces"); } } @@ -425,7 +423,7 @@ void DrawViewPart::onHlrFinished(void) //run any tasks that need to been done after geometry is available void DrawViewPart::postHlrTasks(void) { -// Base::Console().Message("DVP::postHlrTasks() - %s\n", getNameInDocument()); + // Base::Console().Message("DVP::postHlrTasks() - %s\n", getNameInDocument()); //add geometry that doesn't come from HLR addCosmeticVertexesToGeom(); addCosmeticEdgesToGeom(); @@ -438,8 +436,7 @@ void DrawViewPart::postHlrTasks(void) for (auto& b : bals) { b->recomputeFeature(); } - // Dimensions need to be recomputed now, unless their recomputation must be postponed - // until face creation, in which case they are recomputed after that + // Dimensions need to be recomputed now if face finding is not going to take place. if (!handleFaces() || CoarseView.getValue()) { std::vector dims = getDimensions(); for (auto& d : dims) { @@ -448,8 +445,7 @@ void DrawViewPart::postHlrTasks(void) } //second pass if required - if (ScaleType.isValue("Automatic") && - !checkFit()) { + if (ScaleType.isValue("Automatic") && !checkFit()) { double newScale = autoScale(); Scale.setValue(newScale); Scale.purgeTouched(); @@ -467,9 +463,8 @@ void DrawViewPart::postFaceExtractionTasks(void) // Some centerlines depend on faces so we could not add CL geometry before now addCenterLinesToGeom(); - // Dimensions need to be recomputed here because their - // references will be invalid until all the geometry exists, - // specifically cosmetic centerlines + // Dimensions need to be recomputed because their references will be invalid + // until all the geometry (including centerlines dependent on faces) exists. std::vector dims = getDimensions(); for (auto& d : dims) { d->recomputeFeature(); @@ -482,9 +477,9 @@ void DrawViewPart::postFaceExtractionTasks(void) //! make faces from the edge geometry void DrawViewPart::extractFaces() { -// Base::Console().Message("DVP::extractFaces() - %s waitingForHlr: %d waitingForFaces: %d\n", -// getNameInDocument(), waitingForHlr(), waitingForFaces()); - if ( !geometryObject ) { + // Base::Console().Message("DVP::extractFaces() - %s waitingForHlr: %d waitingForFaces: %d\n", + // getNameInDocument(), waitingForHlr(), waitingForFaces()); + if (!geometryObject) { //geometry is in flux, can not make faces right now return; } @@ -492,10 +487,10 @@ void DrawViewPart::extractFaces() showProgressMessage(getNameInDocument(), "is extracting faces"); const std::vector& goEdges = - geometryObject->getVisibleFaceEdges(SmoothVisible.getValue(),SeamVisible.getValue()); + geometryObject->getVisibleFaceEdges(SmoothVisible.getValue(), SeamVisible.getValue()); if (goEdges.empty()) { -// Base::Console().Message("DVP::extractFaces - %s - no face edges available!\n", getNameInDocument()); //debug + // Base::Console().Message("DVP::extractFaces - %s - no face edges available!\n", getNameInDocument()); //debug return; } @@ -503,10 +498,9 @@ void DrawViewPart::extractFaces() std::vector closedEdges; std::vector cleanEdges = DrawProjectSplit::scrubEdges(goEdges, closedEdges); - if (cleanEdges.empty() && - closedEdges.empty()) { + if (cleanEdges.empty() && closedEdges.empty()) { //how does this happen? something wrong somewhere -// Base::Console().Message("DVP::extractFaces - no clean or closed wires\n"); //debug + // Base::Console().Message("DVP::extractFaces - no clean or closed wires\n"); //debug return; } @@ -515,16 +509,16 @@ void DrawViewPart::extractFaces() std::vector sortedWires; try { if (!cleanEdges.empty()) { - sortedWires = eWalker.execute(cleanEdges, true); //include outer wire + sortedWires = eWalker.execute(cleanEdges, true);//include outer wire } } - catch (Base::Exception &e) { + catch (Base::Exception& e) { throw Base::RuntimeError(e.what()); } geometryObject->clearFaceGeom(); std::vector closedWires; - for (auto& e: closedEdges) { + for (auto& e : closedEdges) { BRepBuilderAPI_MakeWire mkWire(e); TopoDS_Wire w = mkWire.Wire(); closedWires.push_back(w); @@ -537,19 +531,22 @@ void DrawViewPart::extractFaces() } if (sortedWires.empty()) { - Base::Console().Warning("DVP::extractFaces - %s - Can't make faces from projected edges\n", getNameInDocument()); - } else { - BRepTools::Write(DrawUtil::vectorToCompound(sortedWires), "DVPSortedWires.brep"); //debug - constexpr double minWireArea = 0.000001; //arbitrary very small face size + Base::Console().Warning( + "DVP::extractFaces - %s - Can't make faces from projected edges\n", + getNameInDocument()); + } + else { + BRepTools::Write(DrawUtil::vectorToCompound(sortedWires), "DVPSortedWires.brep");//debug + constexpr double minWireArea = 0.000001;//arbitrary very small face size std::vector::iterator itWire = sortedWires.begin(); for (; itWire != sortedWires.end(); itWire++) { if (!BRep_Tool::IsClosed(*itWire)) { - continue; //can not make a face from open wire + continue;//can not make a face from open wire } double area = ShapeAnalysis::ContourArea(*itWire); if (area <= minWireArea) { - continue; //can not make a face from wire with no area + continue;//can not make a face from wire with no area } TechDraw::FacePtr f(std::make_shared()); @@ -560,22 +557,25 @@ void DrawViewPart::extractFaces() } } } - } else { //use original method + } + else {//use original method //make a copy of the input edges so the loose tolerances of face finding are //not applied to the real edge geometry. See TopoDS_Shape::TShape(). std::vector copyEdges; bool copyGeometry = true; bool copyMesh = false; - for (const auto& e: goEdges) { + for (const auto& e : goEdges) { BRepBuilderAPI_Copy copier(e->occEdge, copyGeometry, copyMesh); copyEdges.push_back(TopoDS::Edge(copier.Shape())); } std::vector nonZero; - for (auto& e: copyEdges) { //drop any zero edges (shouldn't be any by now!!!) + for (auto& e : copyEdges) {//drop any zero edges (shouldn't be any by now!!!) if (!DrawUtil::isZeroEdge(e)) { nonZero.push_back(e); - } else { - Base::Console().Log("INFO - DVP::extractFaces for %s found ZeroEdge!\n",getNameInDocument()); + } + else { + Base::Console().Log("INFO - DVP::extractFaces for %s found ZeroEdge!\n", + getNameInDocument()); } } @@ -584,65 +584,70 @@ void DrawViewPart::extractFaces() std::vector splits; std::vector::iterator itOuter = nonZero.begin(); int iOuter = 0; - for (; itOuter != nonZero.end(); ++itOuter, iOuter++) { //*** itOuter != nonZero.end() - 1 + for (; itOuter != nonZero.end(); ++itOuter, iOuter++) {//*** itOuter != nonZero.end() - 1 TopoDS_Vertex v1 = TopExp::FirstVertex((*itOuter)); TopoDS_Vertex v2 = TopExp::LastVertex((*itOuter)); Bnd_Box sOuter; BRepBndLib::AddOptimal(*itOuter, sOuter); sOuter.SetGap(0.1); if (sOuter.IsVoid()) { - Base::Console().Log("DVP::Extract Faces - outer Bnd_Box is void for %s\n",getNameInDocument()); + Base::Console().Log("DVP::Extract Faces - outer Bnd_Box is void for %s\n", + getNameInDocument()); continue; } if (DrawUtil::isZeroEdge(*itOuter)) { - Base::Console().Log("DVP::extractFaces - outerEdge: %d is ZeroEdge\n",iOuter); //this is not finding ZeroEdges - continue; //skip zero length edges. shouldn't happen ;) + Base::Console().Log("DVP::extractFaces - outerEdge: %d is ZeroEdge\n", + iOuter);//this is not finding ZeroEdges + continue; //skip zero length edges. shouldn't happen ;) } int iInner = 0; - std::vector::iterator itInner = nonZero.begin(); //***sb itOuter + 1; - for (; itInner != nonZero.end(); ++itInner,iInner++) { + std::vector::iterator itInner = nonZero.begin();//***sb itOuter + 1; + for (; itInner != nonZero.end(); ++itInner, iInner++) { if (iInner == iOuter) { continue; } if (DrawUtil::isZeroEdge((*itInner))) { - continue; //skip zero length edges. shouldn't happen ;) + continue;//skip zero length edges. shouldn't happen ;) } Bnd_Box sInner; BRepBndLib::AddOptimal(*itInner, sInner); sInner.SetGap(0.1); if (sInner.IsVoid()) { - Base::Console().Log("INFO - DVP::Extract Faces - inner Bnd_Box is void for %s\n",getNameInDocument()); + Base::Console().Log( + "INFO - DVP::Extract Faces - inner Bnd_Box is void for %s\n", + getNameInDocument()); continue; } - if (sOuter.IsOut(sInner)) { //bboxes of edges don't intersect, don't bother + if (sOuter.IsOut(sInner)) {//bboxes of edges don't intersect, don't bother continue; } double param = -1; - if (DrawProjectSplit::isOnEdge((*itInner),v1,param,false)) { + if (DrawProjectSplit::isOnEdge((*itInner), v1, param, false)) { gp_Pnt pnt1 = BRep_Tool::Pnt(v1); splitPoint s1; s1.i = iInner; - s1.v = Base::Vector3d(pnt1.X(),pnt1.Y(),pnt1.Z()); + s1.v = Base::Vector3d(pnt1.X(), pnt1.Y(), pnt1.Z()); s1.param = param; splits.push_back(s1); } - if (DrawProjectSplit::isOnEdge((*itInner),v2,param,false)) { + if (DrawProjectSplit::isOnEdge((*itInner), v2, param, false)) { gp_Pnt pnt2 = BRep_Tool::Pnt(v2); splitPoint s2; s2.i = iInner; - s2.v = Base::Vector3d(pnt2.X(),pnt2.Y(),pnt2.Z()); + s2.v = Base::Vector3d(pnt2.X(), pnt2.Y(), pnt2.Z()); s2.param = param; splits.push_back(s2); } - } //inner loop - } //outer loop + }//inner loop + } //outer loop - std::vector sorted = DrawProjectSplit::sortSplits(splits,true); - auto last = std::unique(sorted.begin(), sorted.end(), DrawProjectSplit::splitEqual); //duplicates to back - sorted.erase(last, sorted.end()); //remove dupl splits - std::vector newEdges = DrawProjectSplit::splitEdges(nonZero,sorted); + std::vector sorted = DrawProjectSplit::sortSplits(splits, true); + auto last = std::unique(sorted.begin(), sorted.end(), + DrawProjectSplit::splitEqual);//duplicates to back + sorted.erase(last, sorted.end()); //remove dupl splits + std::vector newEdges = DrawProjectSplit::splitEdges(nonZero, sorted); if (newEdges.empty()) { Base::Console().Log("DVP::extractFaces - no newEdges\n"); @@ -658,9 +663,12 @@ void DrawViewPart::extractFaces() EdgeWalker eWalker; sortedWires = eWalker.execute(newEdges); if (sortedWires.empty()) { - Base::Console().Warning("DVP::extractFaces - %s -Can't make faces from projected edges\n", getNameInDocument()); + Base::Console().Warning( + "DVP::extractFaces - %s -Can't make faces from projected edges\n", + getNameInDocument()); return; - } else { + } + else { std::vector::iterator itWire = sortedWires.begin(); for (; itWire != sortedWires.end(); itWire++) { //version 1: 1 wire/face - no voids in face @@ -679,7 +687,7 @@ void DrawViewPart::extractFaces() //continue processing after extractFaces thread completes void DrawViewPart::onFacesFinished(void) { -// Base::Console().Message("DVP::onFacesFinished() - %s\n", getNameInDocument()); + // Base::Console().Message("DVP::onFacesFinished() - %s\n", getNameInDocument()); waitingForFaces(false); QObject::disconnect(connectFaceWatcher); showProgressMessage(getNameInDocument(), "has finished extracting faces"); @@ -695,9 +703,8 @@ std::vector DrawViewPart::getHatches() const { std::vector result; std::vector children = getInList(); - for (auto& child: children) { - if ( child->getTypeId().isDerivedFrom(DrawHatch::getClassTypeId()) && - !child->isRemoving() ) { + for (auto& child : children) { + if (child->getTypeId().isDerivedFrom(DrawHatch::getClassTypeId()) && !child->isRemoving()) { TechDraw::DrawHatch* hatch = dynamic_cast(child); result.push_back(hatch); } @@ -710,9 +717,9 @@ std::vector DrawViewPart::getGeomHatches() const { std::vector result; std::vector children = getInList(); - for (auto& child: children) { - if ( child->getTypeId().isDerivedFrom(DrawGeomHatch::getClassTypeId()) && - !child->isRemoving() ) { + for (auto& child : children) { + if (child->getTypeId().isDerivedFrom(DrawGeomHatch::getClassTypeId()) + && !child->isRemoving()) { TechDraw::DrawGeomHatch* geom = dynamic_cast(child); result.push_back(geom); } @@ -728,7 +735,8 @@ std::vector DrawViewPart::getDimensions() const std::vector result; std::vector children = getInList(); std::sort(children.begin(), children.end(), std::less()); - std::vector::iterator newEnd = std::unique(children.begin(), children.end()); + std::vector::iterator newEnd = + std::unique(children.begin(), children.end()); for (std::vector::iterator it = children.begin(); it != newEnd; ++it) { if ((*it)->getTypeId().isDerivedFrom(DrawViewDimension::getClassTypeId())) { TechDraw::DrawViewDimension* dim = dynamic_cast(*it); @@ -743,7 +751,8 @@ std::vector DrawViewPart::getBalloons() const std::vector result; std::vector children = getInList(); std::sort(children.begin(), children.end(), std::less()); - std::vector::iterator newEnd = std::unique(children.begin(), children.end()); + std::vector::iterator newEnd = + std::unique(children.begin(), children.end()); for (std::vector::iterator it = children.begin(); it != newEnd; ++it) { if ((*it)->getTypeId().isDerivedFrom(DrawViewBalloon::getClassTypeId())) { TechDraw::DrawViewBalloon* balloon = dynamic_cast(*it); @@ -765,8 +774,7 @@ const std::vector DrawViewPart::getVertexGeometry() const const std::vector DrawViewPart::getFaceGeometry() const { std::vector result; - if ( waitingForFaces() || - !geometryObject ) { + if (waitingForFaces() || !geometryObject) { return std::vector(); } return geometryObject->getFaceGeometry(); @@ -783,13 +791,15 @@ const BaseGeomPtrVector DrawViewPart::getEdgeGeometry() const //! returns existing BaseGeom of 2D Edge(idx) TechDraw::BaseGeomPtr DrawViewPart::getGeomByIndex(int idx) const { - const std::vector &geoms = getEdgeGeometry(); + const std::vector& geoms = getEdgeGeometry(); if (geoms.empty()) { - Base::Console().Log("DVP::getGeomByIndex(%d) - no Edge Geometry. Probably restoring?\n", idx); + Base::Console().Log("DVP::getGeomByIndex(%d) - no Edge Geometry. Probably restoring?\n", + idx); return nullptr; } if ((unsigned)idx >= geoms.size()) { - Base::Console().Error("DVP::getGeomByIndex(%d) - invalid index - size: %d\n", idx, geoms.size()); + Base::Console().Error("DVP::getGeomByIndex(%d) - invalid index - size: %d\n", idx, + geoms.size()); return nullptr; } return geoms.at(idx); @@ -798,9 +808,10 @@ TechDraw::BaseGeomPtr DrawViewPart::getGeomByIndex(int idx) const //! returns existing geometry of 2D Vertex(idx) TechDraw::VertexPtr DrawViewPart::getProjVertexByIndex(int idx) const { - const std::vector &geoms = getVertexGeometry(); + const std::vector& geoms = getVertexGeometry(); if (geoms.empty()) { - Base::Console().Log("DVP::getProjVertexByIndex(%d) - no Vertex Geometry. Probably restoring?\n", idx); + Base::Console().Log( + "DVP::getProjVertexByIndex(%d) - no Vertex Geometry. Probably restoring?\n", idx); return nullptr; } if ((unsigned)idx >= geoms.size()) { @@ -819,7 +830,7 @@ TechDraw::VertexPtr DrawViewPart::getProjVertexByCosTag(std::string cosTag) return result; } - for (auto& gv: gVerts) { + for (auto& gv : gVerts) { if (gv->cosmeticTag == cosTag) { result = gv; break; @@ -834,14 +845,15 @@ std::vector DrawViewPart::getFaceEdgesByIndex(int idx) co { std::vector result; const std::vector& faces = getFaceGeometry(); - if (idx < (int) faces.size()) { + if (idx < (int)faces.size()) { TechDraw::FacePtr projFace = faces.at(idx); - for (auto& w: projFace->wires) { - for (auto& g:w->geoms) { + for (auto& w : projFace->wires) { + for (auto& g : w->geoms) { if (g->cosmetic) { //if g is cosmetic, we should skip it Base::Console().Log("DVP::getFaceEdgesByIndex - found cosmetic edge\n"); - } else { + } + else { result.push_back(g); } } @@ -856,10 +868,10 @@ std::vector DrawViewPart::getWireForFace(int idx) const std::vector edges; const std::vector& faces = getFaceGeometry(); TechDraw::FacePtr ourFace = faces.at(idx); - for (auto& w:ourFace->wires) { + for (auto& w : ourFace->wires) { edges.clear(); int i = 0; - for (auto& g:w->geoms) { + for (auto& g : w->geoms) { edges.push_back(g->occEdge); i++; } @@ -870,14 +882,11 @@ std::vector DrawViewPart::getWireForFace(int idx) const return result; } -Base::BoundBox3d DrawViewPart::getBoundingBox() const -{ - return bbox; -} +Base::BoundBox3d DrawViewPart::getBoundingBox() const { return bbox; } double DrawViewPart::getBoxX() const { - Base::BoundBox3d bbx = getBoundingBox(); //bbox is already scaled & centered! + Base::BoundBox3d bbx = getBoundingBox();//bbox is already scaled & centered! return (bbx.MaxX - bbx.MinX); } @@ -889,7 +898,7 @@ double DrawViewPart::getBoxY() const QRectF DrawViewPart::getRect() const { -// Base::Console().Message("DVP::getRect() - %s\n", getNameInDocument()); + // Base::Console().Message("DVP::getRect() - %s\n", getNameInDocument()); double x = getBoxX(); double y = getBoxY(); QRectF result(0.0, 0.0, x, y); @@ -923,12 +932,10 @@ TopoDS_Shape DrawViewPart::getShape() const //alignment vector is already projected onto our CS, so only has X,Y components double DrawViewPart::getSizeAlongVector(Base::Vector3d alignmentVector) { -// Base::Console().Message("DVP::GetSizeAlongVector(%s)\n", DrawUtil::formatVector(alignmentVector).c_str()); + // Base::Console().Message("DVP::GetSizeAlongVector(%s)\n", DrawUtil::formatVector(alignmentVector).c_str()); double alignmentAngle = atan2(alignmentVector.y, alignmentVector.x) * -1.0; - gp_Ax2 OXYZ; //shape has already been projected and we will rotate around Z - TopoDS_Shape rotatedShape = rotateShape(getShape(), - OXYZ, - alignmentAngle * 180.0 / M_PI); + gp_Ax2 OXYZ;//shape has already been projected and we will rotate around Z + TopoDS_Shape rotatedShape = rotateShape(getShape(), OXYZ, alignmentAngle * 180.0 / M_PI); Bnd_Box shapeBox; shapeBox.SetGap(0.0); BRepBndLib::AddOptimal(rotatedShape, shapeBox); @@ -941,13 +948,13 @@ double DrawViewPart::getSizeAlongVector(Base::Vector3d alignmentVector) //used to project a pt (ex SectionOrigin) onto paper plane Base::Vector3d DrawViewPart::projectPoint(const Base::Vector3d& pt, bool invert) const { -// Base::Console().Message("DVP::projectPoint(%s, %d\n", -// DrawUtil::formatVector(pt).c_str(), invert); + // Base::Console().Message("DVP::projectPoint(%s, %d\n", + // DrawUtil::formatVector(pt).c_str(), invert); Base::Vector3d stdOrg(0.0, 0.0, 0.0); gp_Ax2 viewAxis = getProjectionCS(stdOrg); gp_Pnt gPt(pt.x, pt.y, pt.z); - HLRAlgo_Projector projector( viewAxis ); + HLRAlgo_Projector projector(viewAxis); gp_Pnt2d prjPnt; projector.Project(gPt, prjPnt); Base::Vector3d result(prjPnt.X(), prjPnt.Y(), 0.0); @@ -976,7 +983,7 @@ BaseGeomPtr DrawViewPart::projectEdge(const TopoDS_Edge& e) const //simple projection of inWire with conversion of the result to TD geometry BaseGeomPtrVector DrawViewPart::projectWire(const TopoDS_Wire& inWire) const { -// Base::Console().Message("DVP::projectWire() - inWire.IsNull: %d\n", inWire.IsNull()); + // Base::Console().Message("DVP::projectWire() - inWire.IsNull: %d\n", inWire.IsNull()); BaseGeomPtrVector result; Base::Vector3d stdOrg(0.0, 0.0, 0.0); @@ -984,7 +991,7 @@ BaseGeomPtrVector DrawViewPart::projectWire(const TopoDS_Wire& inWire) const BRepAlgo_NormalProjection projector(paper); projector.Add(inWire); projector.Build(); - BRepTools::Write(projector.Projection(), "DVPprojectedWire.brep"); //debug + BRepTools::Write(projector.Projection(), "DVPprojectedWire.brep");//debug TopExp_Explorer expShape(projector.Projection(), TopAbs_EDGE); for (; expShape.More(); expShape.Next()) { @@ -996,8 +1003,7 @@ BaseGeomPtrVector DrawViewPart::projectWire(const TopoDS_Wire& inWire) const bool DrawViewPart::waitingForResult() const { - if (waitingForHlr() || - waitingForFaces()) { + if (waitingForHlr() || waitingForFaces()) { return true; } return false; @@ -1012,12 +1018,12 @@ bool DrawViewPart::hasGeometry(void) const if (waitingForHlr()) { return false; } - const std::vector &verts = getVertexGeometry(); - const std::vector &edges = getEdgeGeometry(); - if (verts.empty() && - edges.empty() ) { + const std::vector& verts = getVertexGeometry(); + const std::vector& edges = getEdgeGeometry(); + if (verts.empty() && edges.empty()) { return false; - } else { + } + else { return true; } return false; @@ -1030,8 +1036,8 @@ bool DrawViewPart::hasGeometry(void) const //in the derived view. gp_Ax2 DrawViewPart::localVectorToCS(const Base::Vector3d localUnit) const { -// Base::Console().Message("DVP::localVectorToCS(%s)\n", DU::formatVector((localUnit)).c_str()); - double angle = atan2(localUnit.y, localUnit.x); //radians + // Base::Console().Message("DVP::localVectorToCS(%s)\n", DU::formatVector((localUnit)).c_str()); + double angle = atan2(localUnit.y, localUnit.x);//radians gp_Ax1 rotateAxisDir(gp_Pnt(0.0, 0.0, 0.0), getProjectionCS().Direction()); gp_Vec gOldX = getProjectionCS().XDirection(); gp_Vec gNewDirection = gOldX.Rotated(rotateAxisDir, angle); @@ -1044,37 +1050,28 @@ gp_Ax2 DrawViewPart::localVectorToCS(const Base::Vector3d localUnit) const gNewX = gOldX; } - return { gp_Pnt(0.0, 0.0, 0.0), gp_Dir(gNewDirection), gp_Dir(gNewX) }; + return {gp_Pnt(0.0, 0.0, 0.0), gp_Dir(gNewDirection), gp_Dir(gNewX)}; } Base::Vector3d DrawViewPart::localVectorToDirection(const Base::Vector3d localUnit) const { -// Base::Console().Message("DVP::localVectorToDirection() - localUnit: %s\n", DrawUtil::formatVector(localUnit).c_str()); + // Base::Console().Message("DVP::localVectorToDirection() - localUnit: %s\n", DrawUtil::formatVector(localUnit).c_str()); gp_Ax2 cs = localVectorToCS(localUnit); return DrawUtil::toVector3d(cs.Direction()); } gp_Ax2 DrawViewPart::getProjectionCS(const Base::Vector3d pt) const { -// Base::Console().Message("DVP::getProjectionCS() - %s - %s\n", getNameInDocument(), Label.getValue()); + // Base::Console().Message("DVP::getProjectionCS() - %s - %s\n", getNameInDocument(), Label.getValue()); Base::Vector3d direction = Direction.getValue(); - gp_Dir gDir(direction.x, - direction.y, - direction.z); + gp_Dir gDir(direction.x, direction.y, direction.z); Base::Vector3d xDir = getXDirection(); - gp_Dir gXDir(xDir.x, - xDir.y, - xDir.z); - gp_Pnt gOrg(pt.x, - pt.y, - pt.z); - gp_Ax2 viewAxis(gOrg, - gDir); + gp_Dir gXDir(xDir.x, xDir.y, xDir.z); + gp_Pnt gOrg(pt.x, pt.y, pt.z); + gp_Ax2 viewAxis(gOrg, gDir); try { - viewAxis = gp_Ax2(gOrg, - gDir, - gXDir); + viewAxis = gp_Ax2(gOrg, gDir, gXDir); } catch (...) { Base::Console().Warning("DVP - %s - failed to create projection CS\n", getNameInDocument()); @@ -1082,22 +1079,18 @@ gp_Ax2 DrawViewPart::getProjectionCS(const Base::Vector3d pt) const return viewAxis; } -gp_Ax2 DrawViewPart::getViewAxis(const Base::Vector3d& pt, - const Base::Vector3d& direction, - const bool flip) const +gp_Ax2 DrawViewPart::getViewAxis(const Base::Vector3d& pt, const Base::Vector3d& direction, + const bool flip) const { - (void) direction; - (void) flip; + (void)direction; + (void)flip; Base::Console().Message("DVP::getViewAxis - deprecated. Use getProjectionCS.\n"); return getProjectionCS(pt); } //TODO: make saveShape a property -Base::Vector3d DrawViewPart::getOriginalCentroid() const -{ - return m_saveCentroid; -} +Base::Vector3d DrawViewPart::getOriginalCentroid() const { return m_saveCentroid; } Base::Vector3d DrawViewPart::getCurrentCentroid() const { @@ -1111,7 +1104,7 @@ std::vector DrawViewPart::getSectionRefs() const { std::vector result; std::vector inObjs = getInList(); - for (auto& o:inObjs) { + for (auto& o : inObjs) { if (o->getTypeId().isDerivedFrom(DrawViewSection::getClassTypeId())) { result.push_back(static_cast(o)); } @@ -1123,7 +1116,7 @@ std::vector DrawViewPart::getDetailRefs() const { std::vector result; std::vector inObjs = getInList(); - for (auto& o:inObjs) { + for (auto& o : inObjs) { if (o->getTypeId().isDerivedFrom(DrawViewDetail::getClassTypeId())) { if (!o->isRemoving()) { result.push_back(static_cast(o)); @@ -1140,15 +1133,21 @@ const BaseGeomPtrVector DrawViewPart::getVisibleFaceEdges() const bool DrawViewPart::handleFaces() { - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/General"); return hGrp->GetBool("HandleFaces", 1l); } bool DrawViewPart::newFaceFinder(void) { - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/General"); bool result = hGrp->GetBool("NewFaceFinder", 0l); return result; } @@ -1167,7 +1166,7 @@ void DrawViewPart::unsetupObject() for (; it != hatches.end(); it++) { std::string viewName = (*it)->getNameInDocument(); Base::Interpreter().runStringArg("App.getDocument(\"%s\").removeObject(\"%s\")", - docName.c_str(), viewName.c_str()); + docName.c_str(), viewName.c_str()); } // Remove the View's GeomHatches from document @@ -1176,7 +1175,7 @@ void DrawViewPart::unsetupObject() for (; it2 != gHatches.end(); it2++) { std::string viewName = (*it2)->getNameInDocument(); Base::Interpreter().runStringArg("App.getDocument(\"%s\").removeObject(\"%s\")", - docName.c_str(), viewName.c_str()); + docName.c_str(), viewName.c_str()); } // Remove Dimensions which reference this DVP @@ -1190,7 +1189,7 @@ void DrawViewPart::unsetupObject() const char* name = (*it3)->getNameInDocument(); if (name) { Base::Interpreter().runStringArg("App.getDocument(\"%s\").removeObject(\"%s\")", - docName.c_str(), name); + docName.c_str(), name); } } } @@ -1206,7 +1205,7 @@ void DrawViewPart::unsetupObject() const char* name = (*it3)->getNameInDocument(); if (name) { Base::Interpreter().runStringArg("App.getDocument(\"%s\").removeObject(\"%s\")", - docName.c_str(), name); + docName.c_str(), name); } } } @@ -1217,8 +1216,8 @@ bool DrawViewPart::isIso() const { bool result = false; Base::Vector3d dir = Direction.getValue(); - if ( DrawUtil::fpCompare(fabs(dir.x), fabs(dir.y)) && - DrawUtil::fpCompare(fabs(dir.x), fabs(dir.z)) ) { + if (DrawUtil::fpCompare(fabs(dir.x), fabs(dir.y)) + && DrawUtil::fpCompare(fabs(dir.x), fabs(dir.z))) { result = true; } return result; @@ -1226,16 +1225,14 @@ bool DrawViewPart::isIso() const bool DrawViewPart::checkXDirection() const { -// Base::Console().Message("DVP::checkXDirection()\n"); + // Base::Console().Message("DVP::checkXDirection()\n"); Base::Vector3d xDir = XDirection.getValue(); - if (DrawUtil::fpCompare(xDir.Length(), 0.0)) { + if (DrawUtil::fpCompare(xDir.Length(), 0.0)) { Base::Vector3d dir = Direction.getValue(); Base::Vector3d origin(0.0, 0.0, 0.0); - Base::Vector3d xDir = getLegacyX(origin, - dir); + Base::Vector3d xDir = getLegacyX(origin, dir); Base::Console().Log("DVP - %s - XDirection property not set. Trying %s\n", - getNameInDocument(), - DrawUtil::formatVector(xDir).c_str()); + getNameInDocument(), DrawUtil::formatVector(xDir).c_str()); return false; } return true; @@ -1244,45 +1241,42 @@ bool DrawViewPart::checkXDirection() const // Base::Vector3d DrawViewPart::getXDirection() const { -// Base::Console().Message("DVP::getXDirection() - %s\n", Label.getValue()); - Base::Vector3d result(1.0, 0.0, 0.0); //default X + // Base::Console().Message("DVP::getXDirection() - %s\n", Label.getValue()); + Base::Vector3d result(1.0, 0.0, 0.0);//default X App::Property* prop = getPropertyByName("XDirection"); - if (prop) { //have an XDirection property + if (prop) {//have an XDirection property Base::Vector3d propVal = XDirection.getValue(); - if (DrawUtil::fpCompare(propVal.Length(), 0.0)) { //but it has no value - Base::Vector3d dir = Direction.getValue(); //make a sensible default + if (DrawUtil::fpCompare(propVal.Length(), 0.0)) {//but it has no value + Base::Vector3d dir = Direction.getValue(); //make a sensible default Base::Vector3d org(0.0, 0.0, 0.0); - result = getLegacyX(org, - dir); - } else { - result = propVal; //normal case. XDirection is set. + result = getLegacyX(org, dir); + } + else { + result = propVal;//normal case. XDirection is set. } - } else { //no Property. can this happen? - Base::Vector3d dir = Direction.getValue(); //make a sensible default - Base::Vector3d org(0.0, 0.0, 0.0); - result = getLegacyX(org, - dir); + } + else { //no Property. can this happen? + Base::Vector3d dir = Direction.getValue();//make a sensible default + Base::Vector3d org(0.0, 0.0, 0.0); + result = getLegacyX(org, dir); } return result; } -Base::Vector3d DrawViewPart::getLegacyX(const Base::Vector3d& pt, - const Base::Vector3d& axis, - const bool flip) const +Base::Vector3d DrawViewPart::getLegacyX(const Base::Vector3d& pt, const Base::Vector3d& axis, + const bool flip) const { -// Base::Console().Message("DVP::getLegacyX() - %s\n", Label.getValue()); + // Base::Console().Message("DVP::getLegacyX() - %s\n", Label.getValue()); gp_Ax2 viewAxis = TechDraw::legacyViewAxis1(pt, axis, flip); gp_Dir gXDir = viewAxis.XDirection(); - Base::Vector3d result(gXDir.X(), - gXDir.Y(), - gXDir.Z()); + Base::Vector3d result(gXDir.X(), gXDir.Y(), gXDir.Z()); return result; } void DrawViewPart::updateReferenceVert(std::string tag, Base::Vector3d loc2d) { - for (auto& v: m_referenceVerts) { + for (auto& v : m_referenceVerts) { if (v->getTagAsString() == tag) { v->pnt = loc2d; break; @@ -1292,7 +1286,7 @@ void DrawViewPart::updateReferenceVert(std::string tag, Base::Vector3d loc2d) void DrawViewPart::addReferencesToGeom() { -// Base::Console().Message("DVP::addReferencesToGeom() - %s\n", getNameInDocument()); + // Base::Console().Message("DVP::addReferencesToGeom() - %s\n", getNameInDocument()); std::vector gVerts = getVertexGeometry(); gVerts.insert(gVerts.end(), m_referenceVerts.begin(), m_referenceVerts.end()); getGeometryObject()->setVertexGeometry(gVerts); @@ -1302,11 +1296,11 @@ void DrawViewPart::addReferencesToGeom() //ex. LandmarkDimension as a reference std::string DrawViewPart::addReferenceVertex(Base::Vector3d v) { -// Base::Console().Message("DVP::addReferenceVertex(%s) - %s\n", -// DrawUtil::formatVector(v).c_str(), getNameInDocument()); + // Base::Console().Message("DVP::addReferenceVertex(%s) - %s\n", + // DrawUtil::formatVector(v).c_str(), getNameInDocument()); std::string refTag; -// Base::Vector3d scaledV = v * getScale(); -// TechDraw::Vertex* ref = new TechDraw::Vertex(scaledV); + // Base::Vector3d scaledV = v * getScale(); + // TechDraw::Vertex* ref = new TechDraw::Vertex(scaledV); Base::Vector3d scaledV = v; TechDraw::VertexPtr ref(std::make_shared(scaledV)); ref->reference = true; @@ -1318,11 +1312,12 @@ std::string DrawViewPart::addReferenceVertex(Base::Vector3d v) void DrawViewPart::removeReferenceVertex(std::string tag) { std::vector newRefVerts; - for (auto& v: m_referenceVerts) { + for (auto& v : m_referenceVerts) { if (v->getTagAsString() != tag) { newRefVerts.push_back(v); - } else { -// delete v; //??? who deletes v? + } + else { + // delete v; //??? who deletes v? } } m_referenceVerts = newRefVerts; @@ -1331,11 +1326,11 @@ void DrawViewPart::removeReferenceVertex(std::string tag) void DrawViewPart::removeAllReferencesFromGeom() { -// Base::Console().Message("DVP::removeAllReferencesFromGeom()\n"); + // Base::Console().Message("DVP::removeAllReferencesFromGeom()\n"); if (!m_referenceVerts.empty()) { std::vector gVerts = getVertexGeometry(); std::vector newVerts; - for (auto& gv: gVerts) { + for (auto& gv : gVerts) { if (!gv->reference) { newVerts.push_back(gv); } @@ -1346,7 +1341,7 @@ void DrawViewPart::removeAllReferencesFromGeom() void DrawViewPart::resetReferenceVerts() { -// Base::Console().Message("DVP::resetReferenceVerts() %s\n", getNameInDocument()); + // Base::Console().Message("DVP::resetReferenceVerts() %s\n", getNameInDocument()); removeAllReferencesFromGeom(); addReferencesToGeom(); } @@ -1364,25 +1359,23 @@ void DrawViewPart::clearCosmeticVertexes() //add the cosmetic verts to geometry vertex list void DrawViewPart::addCosmeticVertexesToGeom() { -// Base::Console().Message("DVP::addCosmeticVertexesToGeom()\n"); + // Base::Console().Message("DVP::addCosmeticVertexesToGeom()\n"); const std::vector cVerts = CosmeticVertexes.getValues(); - for (auto& cv: cVerts) { - int iGV = geometryObject->addCosmeticVertex(cv->scaled(getScale()), - cv->getTagAsString()); + for (auto& cv : cVerts) { + int iGV = geometryObject->addCosmeticVertex(cv->scaled(getScale()), cv->getTagAsString()); cv->linkGeom = iGV; } } int DrawViewPart::add1CVToGV(std::string tag) { -// Base::Console().Message("DVP::add1CVToGV(%s)\n", tag.c_str()); + // Base::Console().Message("DVP::add1CVToGV(%s)\n", tag.c_str()); TechDraw::CosmeticVertex* cv = getCosmeticVertex(tag); if (!cv) { Base::Console().Message("DVP::add1CVToGV - cv %s not found\n", tag.c_str()); return 0; } - int iGV = geometryObject->addCosmeticVertex(cv->scaled(getScale()), - cv->getTagAsString()); + int iGV = geometryObject->addCosmeticVertex(cv->scaled(getScale()), cv->getTagAsString()); cv->linkGeom = iGV; return iGV; } @@ -1390,12 +1383,12 @@ int DrawViewPart::add1CVToGV(std::string tag) //update Vertex geometry with current CV's void DrawViewPart::refreshCVGeoms() { -// Base::Console().Message("DVP::refreshCVGeoms()\n"); + // Base::Console().Message("DVP::refreshCVGeoms()\n"); std::vector gVerts = getVertexGeometry(); std::vector newGVerts; - for (auto& gv :gVerts) { - if (gv->cosmeticTag.empty()) { //keep only non-cv vertices + for (auto& gv : gVerts) { + if (gv->cosmeticTag.empty()) {//keep only non-cv vertices newGVerts.push_back(gv); } } @@ -1406,14 +1399,14 @@ void DrawViewPart::refreshCVGeoms() //what is the CV's position in the big geometry q int DrawViewPart::getCVIndex(std::string tag) { -// Base::Console().Message("DVP::getCVIndex(%s)\n", tag.c_str()); + // Base::Console().Message("DVP::getCVIndex(%s)\n", tag.c_str()); int result = -1; std::vector gVerts = getVertexGeometry(); std::vector cVerts = CosmeticVertexes.getValues(); int i = 0; bool found = false; - for (auto& gv :gVerts) { + for (auto& gv : gVerts) { if (gv->cosmeticTag == tag) { result = i; found = true; @@ -1421,12 +1414,12 @@ int DrawViewPart::getCVIndex(std::string tag) } i++; } - if (!found) { //not in vertexGeoms + if (!found) {//not in vertexGeoms int base = gVerts.size(); int i = 0; - for (auto& cv: cVerts) { -// Base::Console().Message("DVP::getCVIndex - cv tag: %s\n", -// cv->getTagAsString().c_str()); + for (auto& cv : cVerts) { + // Base::Console().Message("DVP::getCVIndex - cv tag: %s\n", + // cv->getTagAsString().c_str()); if (cv->getTagAsString() == tag) { result = base + i; break; @@ -1434,7 +1427,7 @@ int DrawViewPart::getCVIndex(std::string tag) i++; } } -// Base::Console().Message("DVP::getCVIndex - returns: %d\n", result); + // Base::Console().Message("DVP::getCVIndex - returns: %d\n", result); return result; } @@ -1451,29 +1444,27 @@ void DrawViewPart::clearCosmeticEdges() //add the cosmetic edges to geometry edge list void DrawViewPart::addCosmeticEdgesToGeom() { -// Base::Console().Message("CEx::addCosmeticEdgesToGeom()\n"); + // Base::Console().Message("CEx::addCosmeticEdgesToGeom()\n"); const std::vector cEdges = CosmeticEdges.getValues(); - for (auto& ce: cEdges) { + for (auto& ce : cEdges) { TechDraw::BaseGeomPtr scaledGeom = ce->scaledGeometry(getScale()); if (!scaledGeom) continue; -// int iGE = - geometryObject->addCosmeticEdge(scaledGeom, - ce->getTagAsString()); + // int iGE = + geometryObject->addCosmeticEdge(scaledGeom, ce->getTagAsString()); } } int DrawViewPart::add1CEToGE(std::string tag) { -// Base::Console().Message("CEx::add1CEToGE(%s) 2\n", tag.c_str()); + // Base::Console().Message("CEx::add1CEToGE(%s) 2\n", tag.c_str()); TechDraw::CosmeticEdge* ce = getCosmeticEdge(tag); if (!ce) { Base::Console().Message("CEx::add1CEToGE 2 - ce %s not found\n", tag.c_str()); return -1; } TechDraw::BaseGeomPtr scaledGeom = ce->scaledGeometry(getScale()); - int iGE = geometryObject->addCosmeticEdge(scaledGeom, - tag); + int iGE = geometryObject->addCosmeticEdge(scaledGeom, tag); return iGE; } @@ -1481,11 +1472,11 @@ int DrawViewPart::add1CEToGE(std::string tag) //update Edge geometry with current CE's void DrawViewPart::refreshCEGeoms() { -// Base::Console().Message("DVP::refreshCEGeoms()\n"); + // Base::Console().Message("DVP::refreshCEGeoms()\n"); std::vector gEdges = getEdgeGeometry(); std::vector oldGEdges; - for (auto& ge :gEdges) { - if (ge->source() != SourceType::COSEDGE) { + for (auto& ge : gEdges) { + if (ge->source() != SourceType::COSEDGE) { oldGEdges.push_back(ge); } } @@ -1503,15 +1494,14 @@ void DrawViewPart::clearCenterLines() int DrawViewPart::add1CLToGE(std::string tag) { -// Base::Console().Message("CEx::add1CLToGE(%s) 2\n", tag.c_str()); + // Base::Console().Message("CEx::add1CLToGE(%s) 2\n", tag.c_str()); TechDraw::CenterLine* cl = getCenterLine(tag); if (!cl) { Base::Console().Message("CEx::add1CLToGE 2 - cl %s not found\n", tag.c_str()); return -1; } TechDraw::BaseGeomPtr scaledGeom = cl->scaledGeometry(this); - int iGE = geometryObject->addCenterLine(scaledGeom, - tag); + int iGE = geometryObject->addCenterLine(scaledGeom, tag); return iGE; } @@ -1519,11 +1509,11 @@ int DrawViewPart::add1CLToGE(std::string tag) //update Edge geometry with current CL's void DrawViewPart::refreshCLGeoms() { -// Base::Console().Message("DVP::refreshCLGeoms()\n"); + // Base::Console().Message("DVP::refreshCLGeoms()\n"); std::vector gEdges = getEdgeGeometry(); std::vector newGEdges; - for (auto& ge :gEdges) { - if (ge->source() != SourceType::CENTERLINE) { + for (auto& ge : gEdges) { + if (ge->source() != SourceType::CENTERLINE) { newGEdges.push_back(ge); } } @@ -1534,16 +1524,16 @@ void DrawViewPart::refreshCLGeoms() //add the center lines to geometry Edges list void DrawViewPart::addCenterLinesToGeom() { -// Base::Console().Message("DVP::addCenterLinesToGeom()\n"); + // Base::Console().Message("DVP::addCenterLinesToGeom()\n"); const std::vector lines = CenterLines.getValues(); - for (auto& cl: lines) { + for (auto& cl : lines) { TechDraw::BaseGeomPtr scaledGeom = cl->scaledGeometry(this); if (!scaledGeom) { Base::Console().Error("DVP::addCenterLinesToGeom - scaledGeometry is null\n"); continue; } -// int idx = - (void) geometryObject->addCenterLine(scaledGeom, cl->getTagAsString()); + // int idx = + (void)geometryObject->addCenterLine(scaledGeom, cl->getTagAsString()); } } @@ -1554,7 +1544,7 @@ void DrawViewPart::clearGeomFormats() std::vector noFormats; std::vector fmts = GeomFormats.getValues(); GeomFormats.setValues(noFormats); - for (auto& f: fmts) { + for (auto& f : fmts) { delete f; } } @@ -1568,9 +1558,8 @@ void DrawViewPart::dumpVerts(std::string text) return; } std::vector gVerts = getVertexGeometry(); - Base::Console().Message("%s - dumping %d vertGeoms\n", - text.c_str(), gVerts.size()); - for (auto& gv: gVerts) { + Base::Console().Message("%s - dumping %d vertGeoms\n", text.c_str(), gVerts.size()); + for (auto& gv : gVerts) { gv->dump(); } } @@ -1578,9 +1567,8 @@ void DrawViewPart::dumpVerts(std::string text) void DrawViewPart::dumpCosVerts(std::string text) { std::vector cVerts = CosmeticVertexes.getValues(); - Base::Console().Message("%s - dumping %d CosmeticVertexes\n", - text.c_str(), cVerts.size()); - for (auto& cv: cVerts) { + Base::Console().Message("%s - dumping %d CosmeticVertexes\n", text.c_str(), cVerts.size()); + for (auto& cv : cVerts) { cv->dump("a CV"); } } @@ -1588,14 +1576,13 @@ void DrawViewPart::dumpCosVerts(std::string text) void DrawViewPart::dumpCosEdges(std::string text) { std::vector cEdges = CosmeticEdges.getValues(); - Base::Console().Message("%s - dumping %d CosmeticEdge\n", - text.c_str(), cEdges.size()); - for (auto& ce: cEdges) { + Base::Console().Message("%s - dumping %d CosmeticEdge\n", text.c_str(), cEdges.size()); + for (auto& ce : cEdges) { ce->dump("a CE"); } } -PyObject *DrawViewPart::getPyObject() +PyObject* DrawViewPart::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -1604,94 +1591,124 @@ PyObject *DrawViewPart::getPyObject() return Py::new_reference_to(PythonObject); } -void DrawViewPart::handleChangedPropertyName(Base::XMLReader &reader, const char* TypeName, const char* PropName) +void DrawViewPart::handleChangedPropertyName(Base::XMLReader& reader, const char* TypeName, + const char* PropName) { -// extHandleChangedPropertyName(reader, TypeName, PropName); // CosmeticExtension + // extHandleChangedPropertyName(reader, TypeName, PropName); // CosmeticExtension DrawView::handleChangedPropertyName(reader, TypeName, PropName); } bool DrawViewPart::prefHardViz() { - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/HLR"); bool result = hGrp->GetBool("HardViz", true); return result; } bool DrawViewPart::prefSeamViz() { - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/HLR"); bool result = hGrp->GetBool("SeamViz", true); return result; } bool DrawViewPart::prefSmoothViz() { - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/HLR"); bool result = hGrp->GetBool("SmoothViz", true); return result; } bool DrawViewPart::prefIsoViz() { - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/HLR"); bool result = hGrp->GetBool("IsoViz", false); return result; } bool DrawViewPart::prefHardHid() { - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); - bool result = hGrp->GetBool("HardHid", false); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/HLR"); + bool result = hGrp->GetBool("HardHid", false); return result; } bool DrawViewPart::prefSeamHid() { - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/HLR"); bool result = hGrp->GetBool("SeamHid", false); return result; } bool DrawViewPart::prefSmoothHid() { - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/HLR"); bool result = hGrp->GetBool("SmoothHid", false); return result; } bool DrawViewPart::prefIsoHid() { - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/HLR"); bool result = hGrp->GetBool("IsoHid", false); return result; } int DrawViewPart::prefIsoCount() { - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/HLR"); int result = hGrp->GetBool("IsoCount", 0); return result; } // Python Drawing feature --------------------------------------------------------- -namespace App { +namespace App +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewPartPython, TechDraw::DrawViewPart) -template<> const char* TechDraw::DrawViewPartPython::getViewProviderName() const { +template<> const char* TechDraw::DrawViewPartPython::getViewProviderName() const +{ return "TechDrawGui::ViewProviderViewPart"; } /// @endcond // explicit template instantiation template class TechDrawExport FeaturePythonT; -} +}// namespace App diff --git a/src/Mod/TechDraw/App/DrawViewPart.h b/src/Mod/TechDraw/App/DrawViewPart.h index c8536c411414..a520fc506c78 100644 --- a/src/Mod/TechDraw/App/DrawViewPart.h +++ b/src/Mod/TechDraw/App/DrawViewPart.h @@ -37,8 +37,8 @@ #include #include -#include "DrawView.h" #include "CosmeticExtension.h" +#include "DrawView.h" class gp_Pnt; @@ -58,9 +58,10 @@ using GeometryObjectPtr = std::shared_ptr; class Vertex; class BaseGeom; class Face; -} +}// namespace TechDraw -namespace TechDraw { +namespace TechDraw +{ class DrawHatch; class DrawGeomHatch; class DrawViewDimension; @@ -72,14 +73,14 @@ class CosmeticVertex; class CosmeticEdge; class CenterLine; class GeomFormat; -} +}// namespace TechDraw namespace TechDraw { class DrawViewSection; -class TechDrawExport DrawViewPart : public DrawView, public CosmeticExtension +class TechDrawExport DrawViewPart: public DrawView, public CosmeticExtension { PROPERTY_HEADER_WITH_EXTENSIONS(TechDraw::DrawViewPart); @@ -87,32 +88,31 @@ class TechDrawExport DrawViewPart : public DrawView, public CosmeticExtension DrawViewPart(); ~DrawViewPart() override; - App::PropertyLinkList Source; - App::PropertyXLinkList XSource; - App::PropertyVector Direction; //TODO: Rename to YAxisDirection or whatever this actually is (ProjectionDirection) - App::PropertyVector XDirection; - App::PropertyBool Perspective; - App::PropertyDistance Focus; - - App::PropertyBool CoarseView; - App::PropertyBool SeamVisible; - App::PropertyBool SmoothVisible; + App::PropertyLinkList Source; + App::PropertyXLinkList XSource; + App::PropertyVector + Direction;//TODO: Rename to YAxisDirection or whatever this actually is (ProjectionDirection) + App::PropertyVector XDirection; + App::PropertyBool Perspective; + App::PropertyDistance Focus; + + App::PropertyBool CoarseView; + App::PropertyBool SeamVisible; + App::PropertyBool SmoothVisible; //App::PropertyBool OutlinesVisible; - App::PropertyBool IsoVisible; + App::PropertyBool IsoVisible; - App::PropertyBool HardHidden; - App::PropertyBool SmoothHidden; - App::PropertyBool SeamHidden; + App::PropertyBool HardHidden; + App::PropertyBool SmoothHidden; + App::PropertyBool SeamHidden; //App::PropertyBool OutlinesHidden; - App::PropertyBool IsoHidden; - App::PropertyInteger IsoCount; + App::PropertyBool IsoHidden; + App::PropertyInteger IsoCount; short mustExecute() const override; - App::DocumentObjectExecReturn *execute() override; - const char* getViewProviderName() const override { - return "TechDrawGui::ViewProviderViewPart"; - } - PyObject *getPyObject() override; + App::DocumentObjectExecReturn* execute() override; + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderViewPart"; } + PyObject* getPyObject() override; std::vector getHatches() const; std::vector getGeomHatches() const; @@ -127,34 +127,35 @@ class TechDrawExport DrawViewPart : public DrawView, public CosmeticExtension bool hasGeometry() const; TechDraw::GeometryObjectPtr getGeometryObject() const { return geometryObject; } - TechDraw::BaseGeomPtr getGeomByIndex(int idx) const; //get existing geom for edge idx in projection - TechDraw::VertexPtr getProjVertexByIndex(int idx) const; //get existing geom for vertex idx in projection + TechDraw::BaseGeomPtr + getGeomByIndex(int idx) const;//get existing geom for edge idx in projection + TechDraw::VertexPtr + getProjVertexByIndex(int idx) const;//get existing geom for vertex idx in projection TechDraw::VertexPtr getProjVertexByCosTag(std::string cosTag); - std::vector getFaceEdgesByIndex(int idx) const; //get edges for face idx in projection + std::vector + getFaceEdgesByIndex(int idx) const;//get edges for face idx in projection virtual Base::BoundBox3d getBoundingBox() const; double getBoxX() const; double getBoxY() const; QRectF getRect() const override; - virtual std::vector getSectionRefs() const; //are there ViewSections based on this ViewPart? + virtual std::vector + getSectionRefs() const;//are there ViewSections based on this ViewPart? virtual std::vector getDetailRefs() const; - virtual Base::Vector3d projectPoint(const Base::Vector3d& pt, - bool invert = true) const; + virtual Base::Vector3d projectPoint(const Base::Vector3d& pt, bool invert = true) const; virtual BaseGeomPtr projectEdge(const TopoDS_Edge& e) const; virtual BaseGeomPtrVector projectWire(const TopoDS_Wire& inWire) const; - virtual gp_Ax2 getViewAxis(const Base::Vector3d& pt, - const Base::Vector3d& direction, - const bool flip=true) const; + virtual gp_Ax2 getViewAxis(const Base::Vector3d& pt, const Base::Vector3d& direction, + const bool flip = true) const; virtual gp_Ax2 getProjectionCS(Base::Vector3d pt = Base::Vector3d(0.0, 0.0, 0.0)) const; - virtual Base::Vector3d getXDirection() const; //don't use XDirection.getValue() + virtual Base::Vector3d getXDirection() const;//don't use XDirection.getValue() virtual Base::Vector3d getOriginalCentroid() const; virtual Base::Vector3d getCurrentCentroid() const; - virtual Base::Vector3d getLegacyX(const Base::Vector3d& pt, - const Base::Vector3d& axis, - const bool flip = true) const; + virtual Base::Vector3d getLegacyX(const Base::Vector3d& pt, const Base::Vector3d& axis, + const bool flip = true) const; gp_Ax2 localVectorToCS(const Base::Vector3d localUnit) const; Base::Vector3d localVectorToDirection(const Base::Vector3d localUnit) const; @@ -168,6 +169,7 @@ class TechDrawExport DrawViewPart : public DrawView, public CosmeticExtension virtual TopoDS_Shape getSourceShape() const; virtual TopoDS_Shape getSourceShapeFused() const; virtual std::vector getSourceShape2d() const; + virtual TopoDS_Shape getShapeForDetail() const; TopoDS_Shape getShape() const; double getSizeAlongVector(Base::Vector3d alignmentVector); @@ -209,7 +211,7 @@ class TechDrawExport DrawViewPart : public DrawView, public CosmeticExtension std::vector getAllSources() const; bool waitingForFaces() const { return m_waitingForFaces; } - void waitingForFaces(bool s) { m_waitingForFaces = s;} + void waitingForFaces(bool s) { m_waitingForFaces = s; } bool waitingForHlr() const { return m_waitingForHlr; } void waitingForHlr(bool s) { m_waitingForHlr = s; } virtual bool waitingForResult() const; @@ -224,14 +226,15 @@ public Q_SLOTS: bool checkXDirection() const; TechDraw::GeometryObjectPtr geometryObject; - TechDraw::GeometryObjectPtr m_tempGeometryObject; //holds the new GO until hlr is completed + TechDraw::GeometryObjectPtr m_tempGeometryObject;//holds the new GO until hlr is completed Base::BoundBox3d bbox; void onChanged(const App::Property* prop) override; void unsetupObject() override; - virtual TechDraw::GeometryObjectPtr buildGeometryObject(TopoDS_Shape& shape, const gp_Ax2& viewAxis); - virtual TechDraw::GeometryObjectPtr makeGeometryForShape(TopoDS_Shape& shape); //const?? + virtual TechDraw::GeometryObjectPtr buildGeometryObject(TopoDS_Shape& shape, + const gp_Ax2& viewAxis); + virtual TechDraw::GeometryObjectPtr makeGeometryForShape(TopoDS_Shape& shape);//const?? void partExec(TopoDS_Shape& shape); virtual void addShapes2d(void); @@ -242,10 +245,11 @@ public Q_SLOTS: bool m_handleFaces; - TopoDS_Shape m_saveShape; //TODO: make this a Property. Part::TopoShapeProperty?? - Base::Vector3d m_saveCentroid; //centroid before centering shape in origin + TopoDS_Shape m_saveShape; //TODO: make this a Property. Part::TopoShapeProperty?? + Base::Vector3d m_saveCentroid;//centroid before centering shape in origin - void handleChangedPropertyName(Base::XMLReader &reader, const char* TypeName, const char* PropName) override; + void handleChangedPropertyName(Base::XMLReader& reader, const char* TypeName, + const char* PropName) override; bool prefHardViz(); bool prefSeamViz(); @@ -255,7 +259,7 @@ public Q_SLOTS: bool prefSeamHid(); bool prefSmoothHid(); bool prefIsoHid(); - int prefIsoCount(); + int prefIsoCount(); std::vector m_referenceVerts; @@ -270,11 +274,10 @@ public Q_SLOTS: QMetaObject::Connection connectFaceWatcher; QFutureWatcher m_faceWatcher; QFuture m_faceFuture; - }; using DrawViewPartPython = App::FeaturePythonT; -} //namespace TechDraw +}//namespace TechDraw -#endif // #ifndef DrawViewPart_h_ +#endif// #ifndef DrawViewPart_h_ diff --git a/src/Mod/TechDraw/App/DrawViewSection.cpp b/src/Mod/TechDraw/App/DrawViewSection.cpp index b69c3a01a492..6107e2eb9c17 100644 --- a/src/Mod/TechDraw/App/DrawViewSection.cpp +++ b/src/Mod/TechDraw/App/DrawViewSection.cpp @@ -46,31 +46,31 @@ #include "PreCompiled.h" #ifndef _PreComp_ -#include -#include -#include -#include -#include -#include #include #include +#include #include #include #include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include #include #include -#include -#include -#include -#include -#include -#include -#include +#include #endif #include @@ -84,9 +84,9 @@ #include "DrawGeomHatch.h" #include "DrawHatch.h" +#include "DrawProjGroupItem.h" #include "DrawUtil.h" #include "EdgeWalker.h" -#include "DrawProjGroupItem.h" #include "GeometryObject.h" #include "DrawViewSection.h" @@ -113,23 +113,12 @@ ChangePoint::ChangePoint(gp_Pnt location, gp_Dir preDirection, gp_Dir postDirect m_postDirection.setY(postDirection.Y()); } -void ChangePoint::scale(double scaleFactor) -{ - m_location = m_location * scaleFactor; -} +void ChangePoint::scale(double scaleFactor) { m_location = m_location * scaleFactor; } -const char* DrawViewSection::SectionDirEnums[]= {"Right", - "Left", - "Up", - "Down", - "Aligned", - nullptr}; +const char* DrawViewSection::SectionDirEnums[] = {"Right", "Left", "Up", + "Down", "Aligned", nullptr}; -const char* DrawViewSection::CutSurfaceEnums[]= {"Hide", - "Color", - "SvgHatch", - "PatHatch", - nullptr}; +const char* DrawViewSection::CutSurfaceEnums[] = {"Hide", "Color", "SvgHatch", "PatHatch", nullptr}; //=========================================================================== // DrawViewSection @@ -137,45 +126,53 @@ const char* DrawViewSection::CutSurfaceEnums[]= {"Hide", PROPERTY_SOURCE(TechDraw::DrawViewSection, TechDraw::DrawViewPart) -DrawViewSection::DrawViewSection() : - m_waitingForCut(false), - m_shapeSize(0.0) +DrawViewSection::DrawViewSection() : m_waitingForCut(false), m_shapeSize(0.0) { - static const char *sgroup = "Section"; - static const char *fgroup = "Cut Surface Format"; - static const char *ggroup = "Cut Operation"; + static const char* sgroup = "Section"; + static const char* fgroup = "Cut Surface Format"; + static const char* ggroup = "Cut Operation"; //general section properties - ADD_PROPERTY_TYPE(SectionSymbol ,(""), sgroup, App::Prop_None, "The identifier for this section"); - ADD_PROPERTY_TYPE(BaseView ,(nullptr), sgroup, App::Prop_None, "2D View source for this Section"); + ADD_PROPERTY_TYPE(SectionSymbol, (""), sgroup, App::Prop_Output, + "The identifier for this section"); + ADD_PROPERTY_TYPE(BaseView, (nullptr), sgroup, App::Prop_None, + "2D View source for this Section"); BaseView.setScope(App::LinkScope::Global); - ADD_PROPERTY_TYPE(SectionNormal ,(0, 0,1.0) ,sgroup, App::Prop_None, - "Section Plane normal direction"); //direction of extrusion of cutting prism - ADD_PROPERTY_TYPE(SectionOrigin ,(0, 0,0) ,sgroup, App::Prop_None, "Section Plane Origin"); + ADD_PROPERTY_TYPE(SectionNormal, (0, 0, 1.0), sgroup, App::Prop_None, + "Section Plane normal direction");//direction of extrusion of cutting prism + ADD_PROPERTY_TYPE(SectionOrigin, (0, 0, 0), sgroup, App::Prop_None, "Section Plane Origin"); //TODO: SectionDirection is a legacy from when SectionViews were only available along //cardinal directions. It should be made obsolete and replaced with Aligned sections and //local unit vectors. SectionDirection.setEnums(SectionDirEnums); - ADD_PROPERTY_TYPE(SectionDirection, ((long)0), sgroup, App::Prop_None, "Orientation of this Section in the Base View"); + ADD_PROPERTY_TYPE(SectionDirection, ((long)0), sgroup, App::Prop_None, + "Orientation of this Section in the Base View"); //properties related to the cut operation - ADD_PROPERTY_TYPE(FuseBeforeCut ,(false), ggroup, App::Prop_None, "Merge Source(s) into a single shape before cutting"); - ADD_PROPERTY_TYPE(TrimAfterCut ,(false), ggroup, App::Prop_None, "Trim the resulting shape after the section cut"); + ADD_PROPERTY_TYPE(FuseBeforeCut, (false), ggroup, App::Prop_None, + "Merge Source(s) into a single shape before cutting"); + ADD_PROPERTY_TYPE(TrimAfterCut, (false), ggroup, App::Prop_None, + "Trim the resulting shape after the section cut"); //properties related to the display of the cut surface CutSurfaceDisplay.setEnums(CutSurfaceEnums); - ADD_PROPERTY_TYPE(CutSurfaceDisplay, (prefCutSurface()), fgroup, App::Prop_None, "Appearance of Cut Surface"); - ADD_PROPERTY_TYPE(FileHatchPattern ,(DrawHatch::prefSvgHatch()), fgroup, App::Prop_None, "The hatch pattern file for the cut surface"); - ADD_PROPERTY_TYPE(FileGeomPattern ,(DrawGeomHatch::prefGeomHatchFile()), fgroup, App::Prop_None, "The PAT pattern file for geometric hatching"); - - ADD_PROPERTY_TYPE(SvgIncluded ,(""), fgroup, App::Prop_None, - "Embedded Svg hatch file. System use only."); // n/a to end users - ADD_PROPERTY_TYPE(PatIncluded ,(""), fgroup, App::Prop_None, - "Embedded Pat pattern file. System use only."); // n/a to end users - ADD_PROPERTY_TYPE(NameGeomPattern ,(DrawGeomHatch::prefGeomHatchName()), fgroup, App::Prop_None, "The pattern name for geometric hatching"); + ADD_PROPERTY_TYPE(CutSurfaceDisplay, (prefCutSurface()), fgroup, App::Prop_None, + "Appearance of Cut Surface"); + ADD_PROPERTY_TYPE(FileHatchPattern, (DrawHatch::prefSvgHatch()), fgroup, App::Prop_None, + "The hatch pattern file for the cut surface"); + ADD_PROPERTY_TYPE(FileGeomPattern, (DrawGeomHatch::prefGeomHatchFile()), fgroup, App::Prop_None, + "The PAT pattern file for geometric hatching"); + + ADD_PROPERTY_TYPE(SvgIncluded, (""), fgroup, App::Prop_None, + "Embedded Svg hatch file. System use only.");// n/a to end users + ADD_PROPERTY_TYPE(PatIncluded, (""), fgroup, App::Prop_None, + "Embedded Pat pattern file. System use only.");// n/a to end users + ADD_PROPERTY_TYPE(NameGeomPattern, (DrawGeomHatch::prefGeomHatchName()), fgroup, App::Prop_None, + "The pattern name for geometric hatching"); ADD_PROPERTY_TYPE(HatchScale, (1.0), fgroup, App::Prop_None, "Hatch pattern size adjustment"); - ADD_PROPERTY_TYPE(HatchRotation, (0.0), fgroup, App::Prop_None, "Rotation of hatch pattern in degrees anti-clockwise"); + ADD_PROPERTY_TYPE(HatchRotation, (0.0), fgroup, App::Prop_None, + "Rotation of hatch pattern in degrees anti-clockwise"); ADD_PROPERTY_TYPE(HatchOffset, (0.0, 0.0, 0.0), fgroup, App::Prop_None, "Hatch pattern offset"); getParameters(); @@ -206,12 +203,8 @@ short DrawViewSection::mustExecute() const return TechDraw::DrawView::mustExecute(); } - if (Scale.isTouched() || - Direction.isTouched() || - BaseView.isTouched() || - SectionNormal.isTouched() || - SectionOrigin.isTouched() || - Rotation.isTouched() ) { + if (Scale.isTouched() || Direction.isTouched() || BaseView.isTouched() + || SectionNormal.isTouched() || SectionOrigin.isTouched() || Rotation.isTouched()) { return 1; } @@ -234,23 +227,36 @@ void DrawViewSection::onChanged(const App::Property* prop) if (prop == &SectionNormal) { Direction.setValue(SectionNormal.getValue()); - } else if (prop == &SectionSymbol) { - std::string lblText = "Section " + - std::string(SectionSymbol.getValue()) + - " - " + - std::string(SectionSymbol.getValue()); - Label.setValue(lblText); - } else if (prop == &CutSurfaceDisplay) { + return; + } + else if (prop == &SectionSymbol) { + if (getBaseDVP()) { + getBaseDVP()->requestPaint(); + } + return; + } + else if (prop == &CutSurfaceDisplay) { if (CutSurfaceDisplay.isValue("PatHatch")) { makeLineSets(); } - } else if (prop == &FileHatchPattern) { + requestPaint(); + return; + } + else if (prop == &FileHatchPattern) { replaceSvgIncluded(FileHatchPattern.getValue()); - } else if (prop == &FileGeomPattern) { + requestPaint(); + return; + } + else if (prop == &FileGeomPattern) { replacePatIncluded(FileGeomPattern.getValue()); makeLineSets(); - } else if (prop == &NameGeomPattern ) { + requestPaint(); + return; + } + else if (prop == &NameGeomPattern) { makeLineSets(); + requestPaint(); + return; } DrawView::onChanged(prop); @@ -258,14 +264,14 @@ void DrawViewSection::onChanged(const App::Property* prop) TopoDS_Shape DrawViewSection::getShapeToCut() { -// Base::Console().Message("DVS::getShapeToCut()\n"); + // Base::Console().Message("DVS::getShapeToCut()\n"); App::DocumentObject* base = BaseView.getValue(); TechDraw::DrawViewPart* dvp = nullptr; - if (!base || - !base->getTypeId().isDerivedFrom(TechDraw::DrawViewPart::getClassTypeId())) { + if (!base || !base->getTypeId().isDerivedFrom(TechDraw::DrawViewPart::getClassTypeId())) { //this can probably only happen with scripting return TopoDS_Shape(); - } else { + } + else { dvp = static_cast(base); } TopoDS_Shape shapeToCut = dvp->getSourceShape(); @@ -275,9 +281,14 @@ TopoDS_Shape DrawViewSection::getShapeToCut() return shapeToCut; } -App::DocumentObjectExecReturn *DrawViewSection::execute() +TopoDS_Shape DrawViewSection::getShapeForDetail() const +{ + return TechDraw::rotateShape(getCutShape(), getProjectionCS(), Rotation.getValue()); +} + +App::DocumentObjectExecReturn* DrawViewSection::execute() { -// Base::Console().Message("DVS::execute() - %s\n", getNameInDocument()); + // Base::Console().Message("DVS::execute() - %s\n", getNameInDocument()); if (!keepUpdated()) { return App::DocumentObject::StdReturn; } @@ -286,20 +297,37 @@ App::DocumentObjectExecReturn *DrawViewSection::execute() return new App::DocumentObjectExecReturn("BaseView object not found"); } + if (waitingForCut() || waitingForHlr()) { + return DrawView::execute(); + } + TopoDS_Shape baseShape = getShapeToCut(); if (baseShape.IsNull()) { return DrawView::execute(); } - m_saveShape = baseShape; //save shape for 2nd pass + //is SectionOrigin valid? + Bnd_Box centerBox; + BRepBndLib::AddOptimal(baseShape, centerBox); + centerBox.SetGap(0.0); + Base::Vector3d orgPnt = SectionOrigin.getValue(); + + if (!isReallyInBox(gp_Pnt(orgPnt.x, orgPnt.y, orgPnt.z), centerBox)) { + Base::Console().Warning("DVS: SectionOrigin doesn't intersect part in %s\n", + getNameInDocument()); + } + + //save important info for later use + m_shapeSize = sqrt(centerBox.SquareExtent()); + m_saveShape = baseShape; bool haveX = checkXDirection(); if (!haveX) { //block touch/onChanged stuff Base::Vector3d newX = getXDirection(); XDirection.setValue(newX); - XDirection.purgeTouched(); //don't trigger updates! + XDirection.purgeTouched();//don't trigger updates! //unblock } @@ -312,8 +340,7 @@ App::DocumentObjectExecReturn *DrawViewSection::execute() bool DrawViewSection::isBaseValid() const { App::DocumentObject* base = BaseView.getValue(); - if (base && - base->getTypeId().isDerivedFrom(TechDraw::DrawViewPart::getClassTypeId())) { + if (base && base->getTypeId().isDerivedFrom(TechDraw::DrawViewPart::getClassTypeId())) { return true; } return false; @@ -321,11 +348,10 @@ bool DrawViewSection::isBaseValid() const void DrawViewSection::sectionExec(TopoDS_Shape& baseShape) { -// Base::Console().Message("DVS::sectionExec() - %s baseShape.IsNull: %d\n", -// getNameInDocument(), baseShape.IsNull()); + // Base::Console().Message("DVS::sectionExec() - %s baseShape.IsNull: %d\n", + // getNameInDocument(), baseShape.IsNull()); - if (waitingForHlr() || - waitingForCut()) { + if (waitingForHlr() || waitingForCut()) { return; } @@ -334,12 +360,15 @@ void DrawViewSection::sectionExec(TopoDS_Shape& baseShape) return; } + m_cuttingTool = makeCuttingTool(m_shapeSize); + try { //note that &m_cutWatcher in the third parameter is not strictly required, but using the //4 parameter signature instead of the 3 parameter signature prevents clazy warning: //https://github.com/KDE/clazy/blob/1.11/docs/checks/README-connect-3arg-lambda.md - connectCutWatcher = QObject::connect(&m_cutWatcher, &QFutureWatcherBase::finished, - &m_cutWatcher, [this] { this->onSectionCutFinished(); }); + connectCutWatcher = + QObject::connect(&m_cutWatcher, &QFutureWatcherBase::finished, &m_cutWatcher, + [this] { this->onSectionCutFinished(); }); m_cutFuture = QtConcurrent::run(this, &DrawViewSection::makeSectionCut, baseShape); m_cutWatcher.setFuture(m_cutFuture); waitingForCut(true); @@ -350,41 +379,27 @@ void DrawViewSection::sectionExec(TopoDS_Shape& baseShape) } } -void DrawViewSection::makeSectionCut(TopoDS_Shape &baseShape) +void DrawViewSection::makeSectionCut(TopoDS_Shape& baseShape) { -// Base::Console().Message("DVS::makeSectionCut() - %s - baseShape.IsNull: %d\n", -// getNameInDocument(), baseShape.IsNull()); + // Base::Console().Message("DVS::makeSectionCut() - %s - baseShape.IsNull: %d\n", + // getNameInDocument(), baseShape.IsNull()); showProgressMessage(getNameInDocument(), "is making section cut"); -// cut base shape with tool - //is SectionOrigin valid? - Bnd_Box centerBox; - BRepBndLib::AddOptimal(baseShape, centerBox); - centerBox.SetGap(0.0); - Base::Vector3d orgPnt = SectionOrigin.getValue(); - - if(!isReallyInBox(gp_Pnt(orgPnt.x, orgPnt.y, orgPnt.z), centerBox)) { - Base::Console().Warning("DVS: SectionOrigin doesn't intersect part in %s\n", getNameInDocument()); - } - m_shapeSize = sqrt(centerBox.SquareExtent()); - // We need to copy the shape to not modify the BRepstructure BRepBuilderAPI_Copy BuilderCopy(baseShape); TopoDS_Shape myShape = BuilderCopy.Shape(); - m_saveShape = myShape; //save shape for 2nd pass + m_saveShape = myShape;//save shape for 2nd pass if (debugSection()) { - BRepTools::Write(myShape, "DVSCopy.brep"); //debug + BRepTools::Write(myShape, "DVSCopy.brep");//debug } - m_cuttingTool = makeCuttingTool(m_shapeSize); - if (debugSection()) { - BRepTools::Write(m_cuttingTool, "DVSTool.brep"); //debug + BRepTools::Write(m_cuttingTool, "DVSTool.brep");//debug } -// perform cut + // perform cut BRep_Builder builder; TopoDS_Compound cutPieces; builder.MakeCompound(cutPieces); @@ -402,7 +417,7 @@ void DrawViewSection::makeSectionCut(TopoDS_Shape &baseShape) // cutPieces contains result of cutting each subshape in baseShape with tool m_cutPieces = cutPieces; if (debugSection()) { - BRepTools::Write(cutPieces, "DVSCutPieces1.brep"); //debug + BRepTools::Write(cutPieces, "DVSCutPieces1.brep");//debug } //second cut if requested. Sometimes the first cut includes extra uncut pieces. @@ -411,17 +426,18 @@ void DrawViewSection::makeSectionCut(TopoDS_Shape &baseShape) if (mkCut2.IsDone()) { m_cutPieces = mkCut2.Shape(); if (debugSection()) { - BRepTools::Write(m_cutPieces, "DVSCutPieces2.brep"); //debug + BRepTools::Write(m_cutPieces, "DVSCutPieces2.brep");//debug } } } -// check for error in cut + // check for error in cut Bnd_Box testBox; BRepBndLib::AddOptimal(m_cutPieces, testBox); testBox.SetGap(0.0); - if (testBox.IsVoid()) { //prism & input don't intersect. rawShape is garbage, don't bother. - Base::Console().Warning("DVS::makeSectionCut - prism & input don't intersect - %s\n", Label.getValue()); + if (testBox.IsVoid()) {//prism & input don't intersect. rawShape is garbage, don't bother. + Base::Console().Warning("DVS::makeSectionCut - prism & input don't intersect - %s\n", + Label.getValue()); return; } @@ -429,43 +445,35 @@ void DrawViewSection::makeSectionCut(TopoDS_Shape &baseShape) } //position, scale and rotate shape for buildGeometryObject -TopoDS_Shape DrawViewSection::prepareShape(const TopoDS_Shape& rawShape, - double shapeSize) +TopoDS_Shape DrawViewSection::prepareShape(const TopoDS_Shape& rawShape, double shapeSize) { -// Base::Console().Message("DVS::prepareShape - %s - rawShape.IsNull: %d shapeSize: %.3f\n", -// getNameInDocument(), rawShape.IsNull(), shapeSize); - (void) shapeSize; //shapeSize is not used in this base class, but is interesting for - //derived classes + // Base::Console().Message("DVS::prepareShape - %s - rawShape.IsNull: %d shapeSize: %.3f\n", + // getNameInDocument(), rawShape.IsNull(), shapeSize); + (void)shapeSize;//shapeSize is not used in this base class, but is interesting for + //derived classes // build display geometry as in DVP, with minor mods TopoDS_Shape preparedShape; try { Base::Vector3d origin(0.0, 0.0, 0.0); m_projectionCS = getProjectionCS(origin); gp_Pnt inputCenter; - inputCenter = TechDraw::findCentroid(rawShape, - m_projectionCS); - Base::Vector3d centroid(inputCenter.X(), - inputCenter.Y(), - inputCenter.Z()); - - preparedShape = TechDraw::moveShape(rawShape, - centroid * -1.0); + inputCenter = TechDraw::findCentroid(rawShape, m_projectionCS); + Base::Vector3d centroid(inputCenter.X(), inputCenter.Y(), inputCenter.Z()); + + preparedShape = TechDraw::moveShape(rawShape, centroid * -1.0); m_cutShape = preparedShape; m_saveCentroid = centroid; - preparedShape = TechDraw::scaleShape(preparedShape, - getScale()); + preparedShape = TechDraw::scaleShape(preparedShape, getScale()); if (!DrawUtil::fpCompare(Rotation.getValue(), 0.0)) { - preparedShape = TechDraw::rotateShape(preparedShape, - m_projectionCS, - Rotation.getValue()); + preparedShape = + TechDraw::rotateShape(preparedShape, m_projectionCS, Rotation.getValue()); } if (debugSection()) { - BRepTools::Write(m_cutShape, "DVSCutShape.brep"); //debug -// DrawUtil::dumpCS("DVS::makeSectionCut - CS to GO", viewAxis); + BRepTools::Write(m_cutShape, "DVSCutShape.brep");//debug + // DrawUtil::dumpCS("DVS::makeSectionCut - CS to GO", viewAxis); } - } catch (Standard_Failure& e1) { Base::Console().Warning("DVS::prepareShape - failed to build shape %s - %s **\n", @@ -476,17 +484,17 @@ TopoDS_Shape DrawViewSection::prepareShape(const TopoDS_Shape& rawShape, TopoDS_Shape DrawViewSection::makeCuttingTool(double shapeSize) { -// Base::Console().Message("DVS::makeCuttingTool(%.3f) - %s\n", shapeSize, getNameInDocument()); + // Base::Console().Message("DVS::makeCuttingTool(%.3f) - %s\n", shapeSize, getNameInDocument()); // Make the extrusion face gp_Pln pln = getSectionPlane(); gp_Dir gpNormal = pln.Axis().Direction(); BRepBuilderAPI_MakeFace mkFace(pln, -shapeSize, shapeSize, -shapeSize, shapeSize); TopoDS_Face aProjFace = mkFace.Face(); - if(aProjFace.IsNull()) { + if (aProjFace.IsNull()) { return TopoDS_Shape(); } - if (debugSection()){ - BRepTools::Write(aProjFace, "DVSSectionFace.brep"); //debug + if (debugSection()) { + BRepTools::Write(aProjFace, "DVSSectionFace.brep");//debug } gp_Vec extrudeDir = shapeSize * gp_Vec(gpNormal); return BRepPrimAPI_MakePrism(aProjFace, extrudeDir, false, true).Shape(); @@ -494,14 +502,14 @@ TopoDS_Shape DrawViewSection::makeCuttingTool(double shapeSize) void DrawViewSection::onSectionCutFinished() { -// Base::Console().Message("DVS::onSectionCutFinished() - %s\n", getNameInDocument()); + // Base::Console().Message("DVS::onSectionCutFinished() - %s\n", getNameInDocument()); QObject::disconnect(connectCutWatcher); showProgressMessage(getNameInDocument(), "has finished making section cut"); m_preparedShape = prepareShape(getShapeToPrepare(), m_shapeSize); if (debugSection()) { - BRepTools::Write(m_preparedShape, "DVSPreparedShape.brep"); //debug + BRepTools::Write(m_preparedShape, "DVSPreparedShape.brep");//debug } postSectionCutTasks(); @@ -513,7 +521,7 @@ void DrawViewSection::onSectionCutFinished() //activities that depend on updated geometry object void DrawViewSection::postHlrTasks(void) { -// Base::Console().Message("DVS::postHlrTasks() - %s\n", getNameInDocument()); + // Base::Console().Message("DVS::postHlrTasks() - %s\n", getNameInDocument()); DrawViewPart::postHlrTasks(); @@ -536,37 +544,34 @@ void DrawViewSection::postHlrTasks(void) return; } - TopoDS_Shape centeredFaces = TechDraw::moveShape(faceIntersections, - m_saveCentroid * -1.0); + TopoDS_Shape centeredFaces = TechDraw::moveShape(faceIntersections, m_saveCentroid * -1.0); - TopoDS_Shape scaledSection = TechDraw::scaleShape(centeredFaces, - getScale()); + TopoDS_Shape scaledSection = TechDraw::scaleShape(centeredFaces, getScale()); if (!DrawUtil::fpCompare(Rotation.getValue(), 0.0)) { - scaledSection = TechDraw::rotateShape(scaledSection, - getProjectionCS(), - Rotation.getValue()); + scaledSection = + TechDraw::rotateShape(scaledSection, getProjectionCS(), Rotation.getValue()); } m_sectionTopoDSFaces = alignSectionFaces(faceIntersections); if (debugSection()) { - BRepTools::Write(m_sectionTopoDSFaces, "DVSTopoSectionFaces.brep"); //debug + BRepTools::Write(m_sectionTopoDSFaces, "DVSTopoSectionFaces.brep");//debug } m_tdSectionFaces = makeTDSectionFaces(m_sectionTopoDSFaces); TechDraw::DrawViewPart* dvp = dynamic_cast(BaseView.getValue()); if (dvp) { - dvp->requestPaint(); //to refresh section line + dvp->requestPaint();//to refresh section line } - requestPaint(); //this will be a duplicate paint if we are making a standalone ComplexSection + requestPaint();//this will be a duplicate paint if we are making a standalone ComplexSection } //activities that depend on a valid section cut void DrawViewSection::postSectionCutTasks() { -// Base::Console().Message("DVS::postSectionCutTasks()\n"); + // Base::Console().Message("DVS::postSectionCutTasks()\n"); std::vector children = getInList(); - for (auto& c: children) { + for (auto& c : children) { if (c->getTypeId().isDerivedFrom(DrawViewPart::getClassTypeId())) { //details or sections of this need cut shape c->recomputeFeature(); @@ -576,8 +581,7 @@ void DrawViewSection::postSectionCutTasks() bool DrawViewSection::waitingForResult() const { - if (DrawViewPart::waitingForResult() || - waitingForCut()) { + if (DrawViewPart::waitingForResult() || waitingForCut()) { return true; } return false; @@ -597,17 +601,18 @@ gp_Pln DrawViewSection::getSectionPlane() const //! case is a compound of individual cuts) with the "effective" (flattened) section plane. TopoDS_Compound DrawViewSection::findSectionPlaneIntersections(const TopoDS_Shape& shape) { -// Base::Console().Message("DVS::findSectionPlaneIntersections() - %s\n", getNameInDocument()); - if(shape.IsNull()){ + // Base::Console().Message("DVS::findSectionPlaneIntersections() - %s\n", getNameInDocument()); + if (shape.IsNull()) { // this shouldn't happen -// Base::Console().Warning("DrawViewSection::findSectionPlaneInter - %s - input shape is Null\n", getNameInDocument()); + // Base::Console().Warning("DrawViewSection::findSectionPlaneInter - %s - input shape is Null\n", getNameInDocument()); return TopoDS_Compound(); } gp_Pln plnSection = getSectionPlane(); if (debugSection()) { - BRepBuilderAPI_MakeFace mkFace(plnSection, -m_shapeSize, m_shapeSize, -m_shapeSize, m_shapeSize); - BRepTools::Write(mkFace.Face(), "DVSSectionPlane.brep"); //debug + BRepBuilderAPI_MakeFace mkFace(plnSection, -m_shapeSize, m_shapeSize, -m_shapeSize, + m_shapeSize); + BRepTools::Write(mkFace.Face(), "DVSSectionPlane.brep");//debug BRepTools::Write(shape, "DVSShapeToIntersect.brep)"); } BRep_Builder builder; @@ -615,13 +620,13 @@ TopoDS_Compound DrawViewSection::findSectionPlaneIntersections(const TopoDS_Shap builder.MakeCompound(result); TopExp_Explorer expFaces(shape, TopAbs_FACE); - for ( ; expFaces.More(); expFaces.Next()) { + for (; expFaces.More(); expFaces.Next()) { const TopoDS_Face& face = TopoDS::Face(expFaces.Current()); BRepAdaptor_Surface adapt(face); - if (adapt.GetType() == GeomAbs_Plane){ + if (adapt.GetType() == GeomAbs_Plane) { gp_Pln plnFace = adapt.Plane(); - if(plnSection.Contains(plnFace.Location(), Precision::Confusion()) && - plnFace.Axis().IsParallel(plnSection.Axis(), Precision::Angular())) { + if (plnSection.Contains(plnFace.Location(), Precision::Confusion()) + && plnFace.Axis().IsParallel(plnSection.Axis(), Precision::Angular())) { builder.Add(result, face); } } @@ -632,17 +637,15 @@ TopoDS_Compound DrawViewSection::findSectionPlaneIntersections(const TopoDS_Shap //move section faces to line up with cut shape TopoDS_Compound DrawViewSection::alignSectionFaces(TopoDS_Shape faceIntersections) { -// Base::Console().Message("DVS::alignSectionFaces()\n"); + // Base::Console().Message("DVS::alignSectionFaces()\n"); TopoDS_Compound sectionFaces; - TopoDS_Shape centeredShape = TechDraw::moveShape(faceIntersections, - getOriginalCentroid() * -1.0); + TopoDS_Shape centeredShape = + TechDraw::moveShape(faceIntersections, getOriginalCentroid() * -1.0); - TopoDS_Shape scaledSection = TechDraw::scaleShape(centeredShape, - getScale()); + TopoDS_Shape scaledSection = TechDraw::scaleShape(centeredShape, getScale()); if (!DrawUtil::fpCompare(Rotation.getValue(), 0.0)) { - scaledSection = TechDraw::rotateShape(scaledSection, - getProjectionCS(), - Rotation.getValue()); + scaledSection = + TechDraw::rotateShape(scaledSection, getProjectionCS(), Rotation.getValue()); } return mapToPage(scaledSection); @@ -654,7 +657,7 @@ TopoDS_Compound DrawViewSection::mapToPage(TopoDS_Shape& shapeToAlign) // needs to be aligned to paper plane (origin, stdZ); //project the faces in the shapeToAlign, build new faces from the resulting wires and //combine everything into a compound of faces -// Base::Console().Message("DVS::mapToPage() - shapeToAlign.null: %d\n", shapeToAlign.IsNull()); + // Base::Console().Message("DVS::mapToPage() - shapeToAlign.null: %d\n", shapeToAlign.IsNull()); BRep_Builder builder; TopoDS_Compound result; builder.MakeCompound(result); @@ -664,13 +667,14 @@ TopoDS_Compound DrawViewSection::mapToPage(TopoDS_Shape& shapeToAlign) const TopoDS_Face& face = TopoDS::Face(expFace.Current()); std::vector faceWires; TopExp_Explorer expWires(face, TopAbs_WIRE); - for ( ; expWires.More(); expWires.Next()) { + for (; expWires.More(); expWires.Next()) { const TopoDS_Wire& wire = TopoDS::Wire(expWires.Current()); - TopoDS_Shape projectedShape = GeometryObject::projectSimpleShape(wire, getProjectionCS()); + TopoDS_Shape projectedShape = + GeometryObject::projectSimpleShape(wire, getProjectionCS()); std::vector wireEdges; //projectedShape is just a bunch of edges. we have to rebuild the wire. TopExp_Explorer expEdges(projectedShape, TopAbs_EDGE); - for ( ; expEdges.More(); expEdges.Next()) { + for (; expEdges.More(); expEdges.Next()) { const TopoDS_Edge& edge = TopoDS::Edge(expEdges.Current()); wireEdges.push_back(edge); } @@ -689,7 +693,7 @@ TopoDS_Compound DrawViewSection::mapToPage(TopoDS_Shape& shapeToAlign) if (debugSection()) { std::stringstream ss; ss << "DVSFaceFromWires" << iFace << ".brep"; - BRepTools::Write(mkFace.Face(), ss.str().c_str()); //debug + BRepTools::Write(mkFace.Face(), ss.str().c_str());//debug } } @@ -699,18 +703,18 @@ TopoDS_Compound DrawViewSection::mapToPage(TopoDS_Shape& shapeToAlign) //turn OCC section faces into TD geometry std::vector DrawViewSection::makeTDSectionFaces(TopoDS_Compound topoDSFaces) { -// Base::Console().Message("DVS::makeTDSectionFaces()\n"); + // Base::Console().Message("DVS::makeTDSectionFaces()\n"); std::vector tdSectionFaces; TopExp_Explorer sectionExpl(topoDSFaces, TopAbs_FACE); for (; sectionExpl.More(); sectionExpl.Next()) { const TopoDS_Face& face = TopoDS::Face(sectionExpl.Current()); TechDraw::FacePtr sectionFace(std::make_shared()); TopExp_Explorer expFace(face, TopAbs_WIRE); - for ( ; expFace.More(); expFace.Next()) { + for (; expFace.More(); expFace.Next()) { TechDraw::Wire* w = new TechDraw::Wire(); const TopoDS_Wire& wire = TopoDS::Wire(expFace.Current()); TopExp_Explorer expWire(wire, TopAbs_EDGE); - for ( ; expWire.More(); expWire.Next()) { + for (; expWire.More(); expWire.Next()) { const TopoDS_Edge& edge = TopoDS::Edge(expWire.Current()); TechDraw::BaseGeomPtr e = BaseGeom::baseFactory(edge); if (e) { @@ -730,20 +734,20 @@ std::pair DrawViewSection::sectionLineEnds() { std::pair result; Base::Vector3d stdZ(0.0, 0.0, 1.0); - double baseRotation = getBaseDVP()->Rotation.getValue(); //Qt degrees are clockwise + double baseRotation = getBaseDVP()->Rotation.getValue();//Qt degrees are clockwise Base::Rotation rotator(stdZ, baseRotation * M_PI / 180.0); - Base::Rotation unrotator(stdZ, - baseRotation * M_PI / 180.0); + Base::Rotation unrotator(stdZ, -baseRotation * M_PI / 180.0); - auto sNorm = SectionNormal.getValue(); - auto axis = getBaseDVP()->Direction.getValue(); + auto sNorm = SectionNormal.getValue(); + auto axis = getBaseDVP()->Direction.getValue(); Base::Vector3d stdOrg(0.0, 0.0, 0.0); - Base::Vector3d sectionLineDir = - axis.Cross(sNorm); + Base::Vector3d sectionLineDir = -axis.Cross(sNorm); sectionLineDir.Normalize(); - sectionLineDir = getBaseDVP()->projectPoint(sectionLineDir); //convert to base view CS + sectionLineDir = getBaseDVP()->projectPoint(sectionLineDir);//convert to base view CS sectionLineDir.Normalize(); Base::Vector3d sectionOrg = SectionOrigin.getValue() - getBaseDVP()->getOriginalCentroid(); - sectionOrg = getBaseDVP()->projectPoint(sectionOrg); //convert to base view CS + sectionOrg = getBaseDVP()->projectPoint(sectionOrg);//convert to base view CS double halfSize = getBaseDVP()->getSizeAlongVector(sectionLineDir) / 2.0; result.first = sectionOrg + sectionLineDir * halfSize; result.second = sectionOrg - sectionLineDir * halfSize; @@ -757,7 +761,7 @@ ChangePointVector DrawViewSection::getChangePointsFromSectionLine() // Base::Console().Message("Dvs::getChangePointsFromSectionLine()\n"); ChangePointVector result; std::vector allPoints; - DrawViewPart *baseDvp = dynamic_cast(BaseView.getValue()); + DrawViewPart* baseDvp = dynamic_cast(BaseView.getValue()); if (baseDvp) { std::pair lineEnds = sectionLineEnds(); //make start and end marks @@ -778,7 +782,7 @@ ChangePointVector DrawViewSection::getChangePointsFromSectionLine() //this should really be in BoundBox.h //!check if point is in box or on boundary of box //!compare to isInBox which doesn't allow on boundary -bool DrawViewSection::isReallyInBox (const Base::Vector3d v, const Base::BoundBox3d bb) const +bool DrawViewSection::isReallyInBox(const Base::Vector3d v, const Base::BoundBox3d bb) const { if (v.x <= bb.MinX || v.x >= bb.MaxX) return false; @@ -789,15 +793,15 @@ bool DrawViewSection::isReallyInBox (const Base::Vector3d v, const Base::BoundBo return true; } -bool DrawViewSection::isReallyInBox (const gp_Pnt p, const Bnd_Box& bb) const +bool DrawViewSection::isReallyInBox(const gp_Pnt p, const Bnd_Box& bb) const { return !bb.IsOut(p); } Base::Vector3d DrawViewSection::getXDirection() const { -// Base::Console().Message("DVS::getXDirection() - %s\n", Label.getValue()); - Base::Vector3d result(1.0, 0.0, 0.0); //default X + // Base::Console().Message("DVS::getXDirection() - %s\n", Label.getValue()); + Base::Vector3d result(1.0, 0.0, 0.0);//default X App::Property* prop = getPropertyByName("XDirection"); if (prop) { //we have an XDirection property @@ -806,62 +810,54 @@ Base::Vector3d DrawViewSection::getXDirection() const if (BaseView.getValue()) { gp_Ax2 cs = getCSFromBase(SectionDirection.getValueAsString()); gp_Dir gXDir = cs.XDirection(); - result = Base::Vector3d(gXDir.X(), - gXDir.Y(), - gXDir.Z()); + result = Base::Vector3d(gXDir.X(), gXDir.Y(), gXDir.Z()); } - } else { + } + else { //XDirection is good, so we use it result = XDirection.getValue(); } - } else { + } + else { //no XDirection property. can this happen? gp_Ax2 cs = getCSFromBase(SectionDirection.getValueAsString()); gp_Dir gXDir = cs.XDirection(); - result = Base::Vector3d(gXDir.X(), - gXDir.Y(), - gXDir.Z()); + result = Base::Vector3d(gXDir.X(), gXDir.Y(), gXDir.Z()); } return result; } void DrawViewSection::setCSFromBase(const std::string sectionName) { -// Base::Console().Message("DVS::setCSFromBase(%s)\n", sectionName.c_str()); + // Base::Console().Message("DVS::setCSFromBase(%s)\n", sectionName.c_str()); gp_Dir gDir = getCSFromBase(sectionName).Direction(); - Base::Vector3d vDir(gDir.X(), - gDir.Y(), - gDir.Z()); + Base::Vector3d vDir(gDir.X(), gDir.Y(), gDir.Z()); Direction.setValue(vDir); SectionNormal.setValue(vDir); gp_Dir gxDir = getCSFromBase(sectionName).XDirection(); - Base::Vector3d vXDir(gxDir.X(), - gxDir.Y(), - gxDir.Z()); + Base::Vector3d vXDir(gxDir.X(), gxDir.Y(), gxDir.Z()); XDirection.setValue(vXDir); } //set the section CS based on an XY vector in BaseViews CS void DrawViewSection::setCSFromBase(const Base::Vector3d localUnit) { -// Base::Console().Message("DVS::setCSFromBase(%s)\n", DrawUtil::formatVector(localUnit).c_str()); + // Base::Console().Message("DVS::setCSFromBase(%s)\n", DrawUtil::formatVector(localUnit).c_str()); gp_Ax2 newSectionCS = getBaseDVP()->localVectorToCS(localUnit); - Base::Vector3d vDir(newSectionCS.Direction().X(), - newSectionCS.Direction().Y(), + Base::Vector3d vDir(newSectionCS.Direction().X(), newSectionCS.Direction().Y(), newSectionCS.Direction().Z()); Direction.setValue(vDir); SectionNormal.setValue(vDir); - Base::Vector3d vXDir(newSectionCS.XDirection().X(), - newSectionCS.XDirection().Y(), + Base::Vector3d vXDir(newSectionCS.XDirection().X(), newSectionCS.XDirection().Y(), newSectionCS.XDirection().Z()); - XDirection.setValue(vXDir); //XDir is for projection + XDirection.setValue(vXDir);//XDir is for projection } //reset the section CS based on an XY vector in current section CS void DrawViewSection::setCSFromLocalUnit(const Base::Vector3d localUnit) { -// Base::Console().Message("DVS::setCSFromLocalUnit(%s)\n", DrawUtil::formatVector(localUnit).c_str()); + // Base::Console().Message("DVS::setCSFromLocalUnit(%s)\n", DrawUtil::formatVector(localUnit).c_str()); gp_Dir verticalDir = getSectionCS().YDirection(); gp_Ax1 verticalAxis(DrawUtil::togp_Pnt(SectionOrigin.getValue()), verticalDir); gp_Dir oldNormal = getSectionCS().Direction(); @@ -874,7 +870,7 @@ void DrawViewSection::setCSFromLocalUnit(const Base::Vector3d localUnit) gp_Ax2 DrawViewSection::getCSFromBase(const std::string sectionName) const { -// Base::Console().Message("DVS::getCSFromBase(%s)\n", sectionName.c_str()); + // Base::Console().Message("DVS::getCSFromBase(%s)\n", sectionName.c_str()); Base::Vector3d origin(0.0, 0.0, 0.0); Base::Vector3d sectOrigin = SectionOrigin.getValue(); @@ -886,39 +882,41 @@ gp_Ax2 DrawViewSection::getCSFromBase(const std::string sectionName) const gp_Dir dvpDir = dvpCS.Direction(); gp_Dir dvpUp = dvpCS.YDirection(); gp_Dir dvpRight = dvpCS.XDirection(); - gp_Pnt dvsLoc(sectOrigin.x, - sectOrigin.y, - sectOrigin.z); + gp_Pnt dvsLoc(sectOrigin.x, sectOrigin.y, sectOrigin.z); gp_Dir dvsDir; gp_Dir dvsXDir; - if (sectionName == "Up") { //looking up + if (sectionName == "Up") {//looking up dvsDir = dvpUp.Reversed(); dvsXDir = dvpRight; - } else if (sectionName == "Down") { - dvsDir = dvpUp; + } + else if (sectionName == "Down") { + dvsDir = dvpUp; dvsXDir = dvpRight; - } else if (sectionName == "Left") { - dvsDir = dvpRight; //dvpX - dvsXDir = dvpDir.Reversed(); //-dvpZ - } else if (sectionName == "Right") { + } + else if (sectionName == "Left") { + dvsDir = dvpRight; //dvpX + dvsXDir = dvpDir.Reversed();//-dvpZ + } + else if (sectionName == "Right") { dvsDir = dvpRight.Reversed(); dvsXDir = dvpDir; - } else if (sectionName == "Aligned") { + } + else if (sectionName == "Aligned") { //if aligned, we don't get our direction from the base view Base::Vector3d sectionNormal = SectionNormal.getValue(); dvsDir = gp_Dir(sectionNormal.x, sectionNormal.y, sectionNormal.z); Base::Vector3d sectionXDir = XDirection.getValue(); dvsXDir = gp_Dir(sectionXDir.x, sectionXDir.y, sectionXDir.z); - } else { - Base::Console().Log("Error - DVS::getCSFromBase - bad sectionName: %s\n", sectionName.c_str()); + } + else { + Base::Console().Log("Error - DVS::getCSFromBase - bad sectionName: %s\n", + sectionName.c_str()); dvsDir = dvpRight; dvsXDir = dvpDir; } - gp_Ax2 CS(dvsLoc, - dvsDir, - dvsXDir); + gp_Ax2 CS(dvsLoc, dvsDir, dvsXDir); if (debugSection()) { DrawUtil::dumpCS("DVS::getCSFromBase - sectionCS out", CS); @@ -930,28 +928,20 @@ gp_Ax2 DrawViewSection::getCSFromBase(const std::string sectionName) const //returns current section cs gp_Ax2 DrawViewSection::getSectionCS() const { -// Base::Console().Message("DVS::getSectionCS()\n"); + // Base::Console().Message("DVS::getSectionCS()\n"); Base::Vector3d vNormal = SectionNormal.getValue(); - gp_Dir gNormal(vNormal.x, - vNormal.y, - vNormal.z); - Base::Vector3d vXDir = getXDirection(); - gp_Dir gXDir(vXDir.x, - vXDir.y, - vXDir.z); + gp_Dir gNormal(vNormal.x, vNormal.y, vNormal.z); + Base::Vector3d vXDir = getXDirection(); + gp_Dir gXDir(vXDir.x, vXDir.y, vXDir.z); Base::Vector3d vOrigin = SectionOrigin.getValue(); - gp_Pnt gOrigin(vOrigin.x, - vOrigin.y, - vOrigin.z); - gp_Ax2 sectionCS(gOrigin, - gNormal); + gp_Pnt gOrigin(vOrigin.x, vOrigin.y, vOrigin.z); + gp_Ax2 sectionCS(gOrigin, gNormal); try { - sectionCS = gp_Ax2(gOrigin, - gNormal, - gXDir); + sectionCS = gp_Ax2(gOrigin, gNormal, gXDir); } catch (...) { - Base::Console().Log("DVS::getSectionCS - %s - failed to create section CS\n", getNameInDocument()); + Base::Console().Log("DVS::getSectionCS - %s - failed to create section CS\n", + getNameInDocument()); } return sectionCS; } @@ -959,31 +949,24 @@ gp_Ax2 DrawViewSection::getSectionCS() const gp_Ax2 DrawViewSection::getProjectionCS(const Base::Vector3d pt) const { Base::Vector3d vNormal = SectionNormal.getValue(); - gp_Dir gNormal(vNormal.x, - vNormal.y, - vNormal.z); - Base::Vector3d vXDir = getXDirection(); - gp_Dir gXDir(vXDir.x, - vXDir.y, - vXDir.z); + gp_Dir gNormal(vNormal.x, vNormal.y, vNormal.z); + Base::Vector3d vXDir = getXDirection(); + gp_Dir gXDir(vXDir.x, vXDir.y, vXDir.z); if (DrawUtil::fpCompare(fabs(gNormal.Dot(gXDir)), 1.0)) { //can not build a gp_Ax2 from these values - throw Base::RuntimeError("DVS::getProjectionCS - SectionNormal and XDirection are parallel"); + throw Base::RuntimeError( + "DVS::getProjectionCS - SectionNormal and XDirection are parallel"); } - gp_Pnt gOrigin(pt.x, - pt.y, - pt.z); - return { gOrigin, gNormal, gXDir }; + gp_Pnt gOrigin(pt.x, pt.y, pt.z); + return {gOrigin, gNormal, gXDir}; } std::vector DrawViewSection::getDrawableLines(int i) { -// Base::Console().Message("DVS::getDrawableLines(%d) - lineSets: %d\n", i, m_lineSets.size()); + // Base::Console().Message("DVS::getDrawableLines(%d) - lineSets: %d\n", i, m_lineSets.size()); std::vector result; - result = DrawGeomHatch::getTrimmedLinesSection(this, m_lineSets, - getSectionTopoDSFace(i), - HatchScale.getValue(), - HatchRotation.getValue(), + result = DrawGeomHatch::getTrimmedLinesSection(this, m_lineSets, getSectionTopoDSFace(i), + HatchScale.getValue(), HatchRotation.getValue(), HatchOffset.getValue()); return result; } @@ -994,7 +977,7 @@ TopoDS_Face DrawViewSection::getSectionTopoDSFace(int i) TopExp_Explorer expl(m_sectionTopoDSFaces, TopAbs_FACE); int count = 1; for (; expl.More(); expl.Next(), count++) { - if (count == i+1) { + if (count == i + 1) { result = TopoDS::Face(expl.Current()); } } @@ -1056,7 +1039,7 @@ void DrawViewSection::setupObject() //create geometric hatch lines void DrawViewSection::makeLineSets(void) { -// Base::Console().Message("DVS::makeLineSets()\n"); + // Base::Console().Message("DVS::makeLineSets()\n"); if (PatIncluded.isEmpty()) { return; } @@ -1065,14 +1048,13 @@ void DrawViewSection::makeLineSets(void) Base::FileInfo fi(fileSpec); std::string ext = fi.extension(); if (!fi.isReadable()) { - Base::Console().Message("%s can not read hatch file: %s\n", getNameInDocument(), fileSpec.c_str()); + Base::Console().Message("%s can not read hatch file: %s\n", getNameInDocument(), + fileSpec.c_str()); return; } - if ( (ext == "pat") || - (ext == "PAT") ) { - if ((!fileSpec.empty()) && - (!NameGeomPattern.isEmpty())) { + if ((ext == "pat") || (ext == "PAT")) { + if ((!fileSpec.empty()) && (!NameGeomPattern.isEmpty())) { m_lineSets.clear(); m_lineSets = DrawGeomHatch::makeLineSets(fileSpec, NameGeomPattern.getValue()); } @@ -1081,7 +1063,7 @@ void DrawViewSection::makeLineSets(void) void DrawViewSection::replaceSvgIncluded(std::string newSvgFile) { -// Base::Console().Message("DVS::replaceSvgIncluded(%s)\n", newSvgFile.c_str()); + // Base::Console().Message("DVS::replaceSvgIncluded(%s)\n", newSvgFile.c_str()); if (newSvgFile.empty()) { return; } @@ -1089,14 +1071,15 @@ void DrawViewSection::replaceSvgIncluded(std::string newSvgFile) Base::FileInfo tfi(newSvgFile); if (tfi.isReadable()) { SvgIncluded.setValue(newSvgFile.c_str()); - } else { + } + else { throw Base::RuntimeError("Could not read the new Svg file"); } } void DrawViewSection::replacePatIncluded(std::string newPatFile) { -// Base::Console().Message("DVS::replacePatIncluded(%s)\n", newPatFile.c_str()); + // Base::Console().Message("DVS::replacePatIncluded(%s)\n", newPatFile.c_str()); if (newPatFile.empty()) { return; } @@ -1104,7 +1087,8 @@ void DrawViewSection::replacePatIncluded(std::string newPatFile) Base::FileInfo tfi(newPatFile); if (tfi.isReadable()) { PatIncluded.setValue(newPatFile.c_str()); - } else { + } + else { throw Base::RuntimeError("Could not read the new Pat file"); } } @@ -1113,9 +1097,12 @@ void DrawViewSection::replacePatIncluded(std::string newPatFile) void DrawViewSection::getParameters() { -// Base::Console().Message("DVS::getParameters()\n"); - Base::ReferencehGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); + // Base::Console().Message("DVS::getParameters()\n"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/General"); bool fuseFirst = hGrp->GetBool("SectionFuseFirst", false); FuseBeforeCut.setValue(fuseFirst); @@ -1123,42 +1110,50 @@ void DrawViewSection::getParameters() bool DrawViewSection::debugSection(void) const { - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/debug"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/debug"); return hGrp->GetBool("debugSection", false); } int DrawViewSection::prefCutSurface(void) const { -// Base::Console().Message("DVS::prefCutSurface()\n"); - Base::ReferencehGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); - - return hGrp->GetInt("CutSurfaceDisplay", 2); //default to SvgHatch + // Base::Console().Message("DVS::prefCutSurface()\n"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/Decorations"); + + return hGrp->GetInt("CutSurfaceDisplay", 2);//default to SvgHatch } bool DrawViewSection::showSectionEdges(void) { - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/General"); return (hGrp->GetBool("ShowSectionEdges", true)); } -bool DrawViewSection::trimAfterCut() const -{ - return TrimAfterCut.getValue(); -} +bool DrawViewSection::trimAfterCut() const { return TrimAfterCut.getValue(); } // Python Drawing feature --------------------------------------------------------- -namespace App { +namespace App +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewSectionPython, TechDraw::DrawViewSection) -template<> const char* TechDraw::DrawViewSectionPython::getViewProviderName() const { +template<> const char* TechDraw::DrawViewSectionPython::getViewProviderName() const +{ return "TechDrawGui::ViewProviderDrawingView"; } /// @endcond // explicit template instantiation template class TechDrawExport FeaturePythonT; -} +}// namespace App diff --git a/src/Mod/TechDraw/App/DrawViewSection.h b/src/Mod/TechDraw/App/DrawViewSection.h index 14d4545fb780..3ee9d4cbc65d 100644 --- a/src/Mod/TechDraw/App/DrawViewSection.h +++ b/src/Mod/TechDraw/App/DrawViewSection.h @@ -25,9 +25,9 @@ #ifndef DrawViewSection_h_ #define DrawViewSection_h_ -#include #include #include +#include #include #include @@ -80,7 +80,7 @@ class ChangePoint using ChangePointVector = std::vector; -class TechDrawExport DrawViewSection : public DrawViewPart +class TechDrawExport DrawViewSection: public DrawViewPart { PROPERTY_HEADER_WITH_OVERRIDE(Part::DrawViewSection); @@ -88,39 +88,40 @@ class TechDrawExport DrawViewSection : public DrawViewPart DrawViewSection(); ~DrawViewSection() override; - App::PropertyLink BaseView; + App::PropertyLink BaseView; App::PropertyVector SectionNormal; App::PropertyVector SectionOrigin; App::PropertyString SectionSymbol; - App::PropertyEnumeration SectionDirection; //to be made obsolete eventually - App::PropertyEnumeration CutSurfaceDisplay; //new v019 - App::PropertyFile FileHatchPattern; - App::PropertyFile FileGeomPattern; //new v019 + App::PropertyEnumeration SectionDirection; //to be made obsolete eventually + App::PropertyEnumeration CutSurfaceDisplay;//new v019 + App::PropertyFile FileHatchPattern; + App::PropertyFile FileGeomPattern;//new v019 App::PropertyFileIncluded SvgIncluded; App::PropertyFileIncluded PatIncluded; App::PropertyString NameGeomPattern; - App::PropertyFloat HatchScale; - App::PropertyFloat HatchRotation; + App::PropertyFloat HatchScale; + App::PropertyFloat HatchRotation; App::PropertyVector HatchOffset; - App::PropertyBool FuseBeforeCut; - App::PropertyBool TrimAfterCut; //new v021 + App::PropertyBool FuseBeforeCut; + App::PropertyBool TrimAfterCut;//new v021 - bool isReallyInBox (const Base::Vector3d v, const Base::BoundBox3d bb) const; - bool isReallyInBox (const gp_Pnt p, const Bnd_Box& bb) const; + bool isReallyInBox(const Base::Vector3d v, const Base::BoundBox3d bb) const; + bool isReallyInBox(const gp_Pnt p, const Bnd_Box& bb) const; - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; void onChanged(const App::Property* prop) override; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "TechDrawGui::ViewProviderViewSection"; } void unsetupObject() override; short mustExecute() const override; void sectionExec(TopoDS_Shape& s); - virtual void makeSectionCut(TopoDS_Shape &baseShape); + virtual void makeSectionCut(TopoDS_Shape& baseShape); void postHlrTasks(void) override; virtual void postSectionCutTasks(); void waitingForCut(bool s) { m_waitingForCut = s; } @@ -130,8 +131,7 @@ class TechDrawExport DrawViewSection : public DrawViewPart virtual TopoDS_Shape makeCuttingTool(double shapeSize); virtual TopoDS_Shape getShapeToCut(); virtual bool isBaseValid() const; - virtual TopoDS_Shape prepareShape(const TopoDS_Shape& rawShape, - double shapeSize); + virtual TopoDS_Shape prepareShape(const TopoDS_Shape& rawShape, double shapeSize); virtual TopoDS_Shape getShapeToPrepare() const { return m_cutPieces; } //CS related methods @@ -141,25 +141,27 @@ class TechDrawExport DrawViewSection : public DrawViewPart void setCSFromLocalUnit(const Base::Vector3d localUnit); virtual gp_Ax2 getCSFromBase(const std::string sectionName) const; gp_Ax2 getSectionCS() const; - Base::Vector3d getXDirection() const override; //don't use XDirection.getValue() + Base::Vector3d getXDirection() const override;//don't use XDirection.getValue() TechDraw::DrawViewPart* getBaseDVP() const; TechDraw::DrawProjGroupItem* getBaseDPGI() const; //section face related methods - TopoDS_Compound getSectionTFaces() { return m_sectionTopoDSFaces;} - std::vector getTDFaceGeometry() {return m_tdSectionFaces;} + TopoDS_Compound getSectionTFaces() { return m_sectionTopoDSFaces; } + std::vector getTDFaceGeometry() { return m_tdSectionFaces; } TopoDS_Face getSectionTopoDSFace(int i); virtual TopoDS_Compound alignSectionFaces(TopoDS_Shape faceIntersections); TopoDS_Compound mapToPage(TopoDS_Shape& shapeToAlign); virtual std::vector makeTDSectionFaces(TopoDS_Compound topoDSFaces); virtual TopoDS_Shape getShapeToIntersect() { return m_cutPieces; } - void makeLineSets(void) ; + void makeLineSets(void); std::vector getDrawableLines(int i = 0); std::vector getDecodedSpecsFromFile(std::string fileSpec, std::string myPattern); - TopoDS_Shape getCutShape() {return m_cutShape;} + TopoDS_Shape getCutShape() const { return m_cutShape; } + + TopoDS_Shape getShapeForDetail() const override; static const char* SectionDirEnums[]; static const char* CutSurfaceEnums[]; @@ -170,10 +172,10 @@ class TechDrawExport DrawViewSection : public DrawViewPart bool showSectionEdges(void); public Q_SLOTS: - void onSectionCutFinished(void); + virtual void onSectionCutFinished(void); protected: - TopoDS_Compound m_sectionTopoDSFaces; //needed for hatching + TopoDS_Compound m_sectionTopoDSFaces;//needed for hatching std::vector m_lineSets; std::vector m_tdSectionFaces; @@ -192,9 +194,9 @@ public Q_SLOTS: void replaceSvgIncluded(std::string newSvgFile); void replacePatIncluded(std::string newPatFile); - TopoDS_Shape m_cutPieces; //the shape after cutting, but before centering & scaling + TopoDS_Shape m_cutPieces;//the shape after cutting, but before centering & scaling gp_Ax2 m_projectionCS; - TopoDS_Shape m_preparedShape; //the shape after cutting, centering, scaling etc + TopoDS_Shape m_preparedShape;//the shape after cutting, centering, scaling etc QMetaObject::Connection connectCutWatcher; QFutureWatcher m_cutWatcher; @@ -206,6 +208,6 @@ public Q_SLOTS: using DrawViewSectionPython = App::FeaturePythonT; -} //namespace TechDraw +}//namespace TechDraw #endif diff --git a/src/Mod/TechDraw/App/GeometryObject.cpp b/src/Mod/TechDraw/App/GeometryObject.cpp index 08535e40d208..e35055dc7984 100644 --- a/src/Mod/TechDraw/App/GeometryObject.cpp +++ b/src/Mod/TechDraw/App/GeometryObject.cpp @@ -23,43 +23,41 @@ #include "PreCompiled.h" #ifndef _PreComp_ -#include #include #include #include #include #include #include -#include -#include -#include -#include #include #include +#include #include -#include #include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include #include +#include #include #include -#include #include #include -#include #include +#include +#include #include #include -#include #include #include -#endif // #ifndef _PreComp_ +#include +#include +#include +#include +#include +#include +#include +#endif// #ifndef _PreComp_ #include #include @@ -67,11 +65,11 @@ #include #include -#include "GeometryObject.h" #include "Cosmetic.h" #include "DrawUtil.h" -#include "DrawViewPart.h" #include "DrawViewDetail.h" +#include "DrawViewPart.h" +#include "GeometryObject.h" using namespace TechDraw; @@ -84,29 +82,22 @@ struct EdgePoints { TopoDS_Edge edge; }; -GeometryObject::GeometryObject(const string& parent, TechDraw::DrawView* parentObj) : - m_parentName(parent), - m_parent(parentObj), - m_isoCount(0), - m_isPersp(false), - m_focus(100.0), - m_usePolygonHLR(false) +GeometryObject::GeometryObject(const string& parent, TechDraw::DrawView* parentObj) + : m_parentName(parent), m_parent(parentObj), m_isoCount(0), m_isPersp(false), m_focus(100.0), + m_usePolygonHLR(false) -{ -} +{} -GeometryObject::~GeometryObject() -{ - clear(); -} +GeometryObject::~GeometryObject() { clear(); } -const BaseGeomPtrVector GeometryObject::getVisibleFaceEdges(const bool smooth, const bool seam) const +const BaseGeomPtrVector GeometryObject::getVisibleFaceEdges(const bool smooth, + const bool seam) const { BaseGeomPtrVector result; bool smoothOK = smooth; bool seamOK = seam; - for (auto& e:edgeGeom) { + for (auto& e : edgeGeom) { if (e->hlrVisible) { switch (e->classOfEdge) { case ecHARD: @@ -123,26 +114,24 @@ const BaseGeomPtrVector GeometryObject::getVisibleFaceEdges(const bool smooth, c result.push_back(e); } break; - default: - ; + default:; } } } //debug //make compound of edges and save as brep file -// BRep_Builder builder; -// TopoDS_Compound comp; -// builder.MakeCompound(comp); -// for (auto& r: result) { -// builder.Add(comp, r->occEdge); -// } -// BRepTools::Write(comp, "GOVizFaceEdges.brep"); //debug + // BRep_Builder builder; + // TopoDS_Compound comp; + // builder.MakeCompound(comp); + // for (auto& r: result) { + // builder.Add(comp, r->occEdge); + // } + // BRepTools::Write(comp, "GOVizFaceEdges.brep"); //debug return result; } - void GeometryObject::clear() { //shared pointers will delete v/e/f when reference counts go to zero. @@ -152,22 +141,22 @@ void GeometryObject::clear() edgeGeom.clear(); } -void GeometryObject::projectShape(const TopoDS_Shape& inShape, - const gp_Ax2& viewAxis) +void GeometryObject::projectShape(const TopoDS_Shape& inShape, const gp_Ax2& viewAxis) { clear(); Handle(HLRBRep_Algo) brep_hlr; try { brep_hlr = new HLRBRep_Algo(); -// brep_hlr->Debug(true); + // brep_hlr->Debug(true); brep_hlr->Add(inShape, m_isoCount); if (m_isPersp) { double fLength = std::max(Precision::Confusion(), m_focus); - HLRAlgo_Projector projector( viewAxis, fLength ); + HLRAlgo_Projector projector(viewAxis, fLength); brep_hlr->Projector(projector); - } else { - HLRAlgo_Projector projector( viewAxis ); + } + else { + HLRAlgo_Projector projector(viewAxis); brep_hlr->Projector(projector); } brep_hlr->Update(); @@ -177,7 +166,7 @@ void GeometryObject::projectShape(const TopoDS_Shape& inShape, Base::Console().Error("GO::projectShape - OCC error - %s - while projecting shape\n", e.GetMessageString()); throw Base::RuntimeError("GeometryObject::projectShape - OCC error"); - } + } catch (...) { throw Base::RuntimeError("GeometryObject::projectShape - unknown error"); } @@ -186,51 +175,51 @@ void GeometryObject::projectShape(const TopoDS_Shape& inShape, HLRBRep_HLRToShape hlrToShape(brep_hlr); if (!hlrToShape.VCompound().IsNull()) { - visHard = hlrToShape.VCompound(); + visHard = hlrToShape.VCompound(); BRepLib::BuildCurves3d(visHard); visHard = invertGeometry(visHard); -// BRepTools::Write(visHard, "GOvisHard.brep"); //debug + // BRepTools::Write(visHard, "GOvisHard.brep"); //debug } if (!hlrToShape.Rg1LineVCompound().IsNull()) { - visSmooth = hlrToShape.Rg1LineVCompound(); + visSmooth = hlrToShape.Rg1LineVCompound(); BRepLib::BuildCurves3d(visSmooth); visSmooth = invertGeometry(visSmooth); } if (!hlrToShape.RgNLineVCompound().IsNull()) { - visSeam = hlrToShape.RgNLineVCompound(); + visSeam = hlrToShape.RgNLineVCompound(); BRepLib::BuildCurves3d(visSeam); visSeam = invertGeometry(visSeam); } if (!hlrToShape.OutLineVCompound().IsNull()) { -// BRepTools::Write(hlrToShape.OutLineVCompound(), "GOOutLineVCompound.brep"); //debug - visOutline = hlrToShape.OutLineVCompound(); + // BRepTools::Write(hlrToShape.OutLineVCompound(), "GOOutLineVCompound.brep"); //debug + visOutline = hlrToShape.OutLineVCompound(); BRepLib::BuildCurves3d(visOutline); visOutline = invertGeometry(visOutline); } if (!hlrToShape.IsoLineVCompound().IsNull()) { - visIso = hlrToShape.IsoLineVCompound(); + visIso = hlrToShape.IsoLineVCompound(); BRepLib::BuildCurves3d(visIso); visIso = invertGeometry(visIso); } if (!hlrToShape.HCompound().IsNull()) { - hidHard = hlrToShape.HCompound(); + hidHard = hlrToShape.HCompound(); BRepLib::BuildCurves3d(hidHard); hidHard = invertGeometry(hidHard); } if (!hlrToShape.Rg1LineHCompound().IsNull()) { - hidSmooth = hlrToShape.Rg1LineHCompound(); + hidSmooth = hlrToShape.Rg1LineHCompound(); BRepLib::BuildCurves3d(hidSmooth); hidSmooth = invertGeometry(hidSmooth); } if (!hlrToShape.RgNLineHCompound().IsNull()) { - hidSeam = hlrToShape.RgNLineHCompound(); + hidSeam = hlrToShape.RgNLineHCompound(); BRepLib::BuildCurves3d(hidSeam); hidSeam = invertGeometry(hidSeam); } @@ -242,16 +231,18 @@ void GeometryObject::projectShape(const TopoDS_Shape& inShape, } if (!hlrToShape.IsoLineHCompound().IsNull()) { - hidIso = hlrToShape.IsoLineHCompound(); + hidIso = hlrToShape.IsoLineHCompound(); BRepLib::BuildCurves3d(hidIso); hidIso = invertGeometry(hidIso); } } catch (const Standard_Failure&) { - throw Base::RuntimeError("GeometryObject::projectShape - OCC error occurred while extracting edges"); + throw Base::RuntimeError( + "GeometryObject::projectShape - OCC error occurred while extracting edges"); } catch (...) { - throw Base::RuntimeError("GeometryObject::projectShape - unknown error occurred while extracting edges"); + throw Base::RuntimeError( + "GeometryObject::projectShape - unknown error occurred while extracting edges"); } makeTDGeometry(); @@ -260,47 +251,37 @@ void GeometryObject::projectShape(const TopoDS_Shape& inShape, //convert the hlr output into TD Geometry void GeometryObject::makeTDGeometry() { - extractGeometry(TechDraw::ecHARD, //always show the hard&outline visible lines - true); - extractGeometry(TechDraw::ecOUTLINE, - true); + extractGeometry(TechDraw::ecHARD,//always show the hard&outline visible lines + true); + extractGeometry(TechDraw::ecOUTLINE, true); const DrawViewPart* dvp = static_cast(m_parent); if (!dvp) { - return; //some routines do not have a dvp (ex shape outline) + return;//some routines do not have a dvp (ex shape outline) } if (dvp->SmoothVisible.getValue()) { - extractGeometry(TechDraw::ecSMOOTH, - true); + extractGeometry(TechDraw::ecSMOOTH, true); } if (dvp->SeamVisible.getValue()) { - extractGeometry(TechDraw::ecSEAM, - true); + extractGeometry(TechDraw::ecSEAM, true); } if ((dvp->IsoVisible.getValue()) && (dvp->IsoCount.getValue() > 0)) { - extractGeometry(TechDraw::ecUVISO, - true); + extractGeometry(TechDraw::ecUVISO, true); } if (dvp->HardHidden.getValue()) { - extractGeometry(TechDraw::ecHARD, - false); - extractGeometry(TechDraw::ecOUTLINE, - false); + extractGeometry(TechDraw::ecHARD, false); + extractGeometry(TechDraw::ecOUTLINE, false); } if (dvp->SmoothHidden.getValue()) { - extractGeometry(TechDraw::ecSMOOTH, - false); + extractGeometry(TechDraw::ecSMOOTH, false); } if (dvp->SeamHidden.getValue()) { - extractGeometry(TechDraw::ecSEAM, - false); + extractGeometry(TechDraw::ecSEAM, false); } if (dvp->IsoHidden.getValue() && (dvp->IsoCount.getValue() > 0)) { - extractGeometry(TechDraw::ecUVISO, - false); + extractGeometry(TechDraw::ecUVISO, false); } - } //mirror a shape thru XZ plane for Qt's inverted Y coordinate @@ -315,8 +296,7 @@ TopoDS_Shape GeometryObject::invertGeometry(const TopoDS_Shape s) gp_Trsf mirrorY; gp_Pnt org(0.0, 0.0, 0.0); gp_Dir Y(0.0, 1.0, 0.0); - gp_Ax2 mirrorPlane(org, - Y); + gp_Ax2 mirrorPlane(org, Y); mirrorY.SetMirror(mirrorPlane); BRepBuilderAPI_Transform mkTrf(s, mirrorY, true); result = mkTrf.Shape(); @@ -324,8 +304,7 @@ TopoDS_Shape GeometryObject::invertGeometry(const TopoDS_Shape s) } //!set up a hidden line remover and project a shape with it -void GeometryObject::projectShapeWithPolygonAlgo(const TopoDS_Shape& input, - const gp_Ax2 &viewAxis) +void GeometryObject::projectShapeWithPolygonAlgo(const TopoDS_Shape& input, const gp_Ax2& viewAxis) { // Clear previous Geometry clear(); @@ -335,11 +314,11 @@ void GeometryObject::projectShapeWithPolygonAlgo(const TopoDS_Shape& input, //to be reverted. TopoDS_Shape inCopy; if (!m_isPersp) { - gp_Pnt gCenter = findCentroid(input, - viewAxis); + gp_Pnt gCenter = findCentroid(input, viewAxis); Base::Vector3d motion(-gCenter.X(), -gCenter.Y(), -gCenter.Z()); inCopy = moveShape(input, motion); - } else { + } + else { BRepBuilderAPI_Copy BuilderCopy(input); inCopy = BuilderCopy.Shape(); } @@ -351,7 +330,7 @@ void GeometryObject::projectShapeWithPolygonAlgo(const TopoDS_Shape& input, for (int i = 1; faces.More(); faces.Next(), i++) { const TopoDS_Face& f = TopoDS::Face(faces.Current()); if (!f.IsNull()) { - BRepMesh_IncrementalMesh(f, 0.10); //Poly Algo requires a mesh! + BRepMesh_IncrementalMesh(f, 0.10);//Poly Algo requires a mesh! } } brep_hlrPoly = new HLRBRep_PolyAlgo(); @@ -362,15 +341,16 @@ void GeometryObject::projectShapeWithPolygonAlgo(const TopoDS_Shape& input, HLRAlgo_Projector projector(viewAxis, fLength); brep_hlrPoly->Projector(projector); } - else { // non perspective + else {// non perspective HLRAlgo_Projector projector(viewAxis); brep_hlrPoly->Projector(projector); } brep_hlrPoly->Update(); } catch (const Standard_Failure& e) { - Base::Console().Error("GO::projectShapeWithPolygonAlgo - OCC error - %s - while projecting shape\n", - e.GetMessageString()); + Base::Console().Error( + "GO::projectShapeWithPolygonAlgo - OCC error - %s - while projecting shape\n", + e.GetMessageString()); throw Base::RuntimeError("GeometryObject::projectShapeWithPolygonAlgo - OCC error"); } catch (...) { @@ -381,33 +361,33 @@ void GeometryObject::projectShapeWithPolygonAlgo(const TopoDS_Shape& input, HLRBRep_PolyHLRToShape polyhlrToShape; polyhlrToShape.Update(brep_hlrPoly); - visHard = polyhlrToShape.VCompound(); + visHard = polyhlrToShape.VCompound(); BRepLib::BuildCurves3d(visHard); visHard = invertGeometry(visHard); -// BRepTools::Write(visHard, "GOvisHardi.brep"); //debug + // BRepTools::Write(visHard, "GOvisHardi.brep"); //debug - visSmooth = polyhlrToShape.Rg1LineVCompound(); + visSmooth = polyhlrToShape.Rg1LineVCompound(); BRepLib::BuildCurves3d(visSmooth); visSmooth = invertGeometry(visSmooth); - visSeam = polyhlrToShape.RgNLineVCompound(); + visSeam = polyhlrToShape.RgNLineVCompound(); BRepLib::BuildCurves3d(visSeam); visSeam = invertGeometry(visSeam); - visOutline = polyhlrToShape.OutLineVCompound(); + visOutline = polyhlrToShape.OutLineVCompound(); BRepLib::BuildCurves3d(visOutline); visOutline = invertGeometry(visOutline); - hidHard = polyhlrToShape.HCompound(); + hidHard = polyhlrToShape.HCompound(); BRepLib::BuildCurves3d(hidHard); hidHard = invertGeometry(hidHard); -// BRepTools::Write(hidHard, "GOhidHardi.brep"); //debug + // BRepTools::Write(hidHard, "GOhidHardi.brep"); //debug - hidSmooth = polyhlrToShape.Rg1LineHCompound(); + hidSmooth = polyhlrToShape.Rg1LineHCompound(); BRepLib::BuildCurves3d(hidSmooth); hidSmooth = invertGeometry(hidSmooth); - hidSeam = polyhlrToShape.RgNLineHCompound(); + hidSeam = polyhlrToShape.RgNLineHCompound(); BRepLib::BuildCurves3d(hidSeam); hidSeam = invertGeometry(hidSeam); @@ -416,12 +396,15 @@ void GeometryObject::projectShapeWithPolygonAlgo(const TopoDS_Shape& input, hidOutline = invertGeometry(hidOutline); } catch (const Standard_Failure& e) { - Base::Console().Error("GO::projectShapeWithPolygonAlgo - OCC error - %s - while extracting edges\n", - e.GetMessageString()); - throw Base::RuntimeError("GeometryObject::projectShapeWithPolygonAlgo - OCC error occurred while extracting edges"); + Base::Console().Error( + "GO::projectShapeWithPolygonAlgo - OCC error - %s - while extracting edges\n", + e.GetMessageString()); + throw Base::RuntimeError("GeometryObject::projectShapeWithPolygonAlgo - OCC error occurred " + "while extracting edges"); } catch (...) { - throw Base::RuntimeError("GeometryObject::projectShapeWithPolygonAlgo - unknown error occurred while extracting edges"); + throw Base::RuntimeError("GeometryObject::projectShapeWithPolygonAlgo - unknown error " + "occurred while extracting edges"); } makeTDGeometry(); @@ -431,17 +414,16 @@ void GeometryObject::projectShapeWithPolygonAlgo(const TopoDS_Shape& input, //of the main hlr routine. Only the visible hard edges are returned, so this method //is only suitable for simple shapes that have no hidden edges, like faces or wires. //TODO: allow use of perspective projector -TopoDS_Shape GeometryObject::projectSimpleShape(const TopoDS_Shape &shape, - const gp_Ax2 &CS) +TopoDS_Shape GeometryObject::projectSimpleShape(const TopoDS_Shape& shape, const gp_Ax2& CS) { -// Base::Console().Message("GO::()\n"); - if(shape.IsNull()) { + // Base::Console().Message("GO::()\n"); + if (shape.IsNull()) { throw Base::ValueError("GO::projectSimpleShape - input shape is NULL"); } - HLRBRep_Algo *brep_hlr = new HLRBRep_Algo(); + HLRBRep_Algo* brep_hlr = new HLRBRep_Algo(); brep_hlr->Add(shape); - HLRAlgo_Projector projector( CS ); + HLRAlgo_Projector projector(CS); brep_hlr->Projector(projector); brep_hlr->Update(); brep_hlr->Hide(); @@ -456,8 +438,7 @@ TopoDS_Shape GeometryObject::projectSimpleShape(const TopoDS_Shape &shape, //project the edges of a shape onto the XY plane of projCS. This does not give //the same result as the hlr projections -TopoDS_Shape GeometryObject::simpleProjection(const TopoDS_Shape& shape, - const gp_Ax2& projCS) +TopoDS_Shape GeometryObject::simpleProjection(const TopoDS_Shape& shape, const gp_Ax2& projCS) { gp_Pln plane(projCS); TopoDS_Face paper = BRepBuilderAPI_MakeFace(plane); @@ -467,17 +448,16 @@ TopoDS_Shape GeometryObject::simpleProjection(const TopoDS_Shape& shape, return projector.Projection(); } -TopoDS_Shape GeometryObject::projectFace(const TopoDS_Shape &face, - const gp_Ax2 &CS) +TopoDS_Shape GeometryObject::projectFace(const TopoDS_Shape& face, const gp_Ax2& CS) { -// Base::Console().Message("GO::projectFace()\n"); - if(face.IsNull()) { + // Base::Console().Message("GO::projectFace()\n"); + if (face.IsNull()) { throw Base::ValueError("GO::projectFace - input Face is NULL"); } - HLRBRep_Algo *brep_hlr = new HLRBRep_Algo(); + HLRBRep_Algo* brep_hlr = new HLRBRep_Algo(); brep_hlr->Add(face); - HLRAlgo_Projector projector( CS ); + HLRAlgo_Projector projector(CS); brep_hlr->Projector(projector); brep_hlr->Update(); brep_hlr->Hide(); @@ -493,7 +473,7 @@ TopoDS_Shape GeometryObject::projectFace(const TopoDS_Shape &face, //!add edges meeting filter criteria for category, visibility void GeometryObject::extractGeometry(edgeClass category, bool hlrVisible) { -// Base::Console().Message("GO::extractGeometry(%d, %d)\n", category, hlrVisible); + // Base::Console().Message("GO::extractGeometry(%d, %d)\n", category, hlrVisible); TopoDS_Shape filtEdges; if (hlrVisible) { switch (category) { @@ -513,10 +493,13 @@ void GeometryObject::extractGeometry(edgeClass category, bool hlrVisible) filtEdges = visIso; break; default: - Base::Console().Warning("GeometryObject::ExtractGeometry - unsupported hlrVisible edgeClass: %d\n", category); + Base::Console().Warning( + "GeometryObject::ExtractGeometry - unsupported hlrVisible edgeClass: %d\n", + category); return; } - } else { + } + else { switch (category) { case ecHARD: filtEdges = hidHard; @@ -534,7 +517,9 @@ void GeometryObject::extractGeometry(edgeClass category, bool hlrVisible) filtEdges = hidIso; break; default: - Base::Console().Warning("GeometryObject::ExtractGeometry - unsupported hidden edgeClass: %d\n", category); + Base::Console().Warning( + "GeometryObject::ExtractGeometry - unsupported hidden edgeClass: %d\n", + category); return; } } @@ -543,18 +528,19 @@ void GeometryObject::extractGeometry(edgeClass category, bool hlrVisible) } //! update edgeGeom and vertexGeom from Compound of edges -void GeometryObject::addGeomFromCompound(TopoDS_Shape edgeCompound, edgeClass category, bool hlrVisible) +void GeometryObject::addGeomFromCompound(TopoDS_Shape edgeCompound, edgeClass category, + bool hlrVisible) { -// Base::Console().Message("GO::addGeomFromCompound(%d, %d)\n", category, hlrVisible); - if(edgeCompound.IsNull()) { + // Base::Console().Message("GO::addGeomFromCompound(%d, %d)\n", category, hlrVisible); + if (edgeCompound.IsNull()) { Base::Console().Log("TechDraw::GeometryObject::addGeomFromCompound edgeCompound is NULL\n"); - return; // There is no OpenCascade Geometry to be calculated + return;// There is no OpenCascade Geometry to be calculated } BaseGeomPtr base; TopExp_Explorer edges(edgeCompound, TopAbs_EDGE); int i = 1; - for ( ; edges.More(); edges.Next(), i++) { + for (; edges.More(); edges.Next(), i++) { const TopoDS_Edge& edge = TopoDS::Edge(edges.Current()); if (edge.IsNull()) { Base::Console().Log("GO::addGeomFromCompound - edge: %d is NULL\n", i); @@ -564,20 +550,21 @@ void GeometryObject::addGeomFromCompound(TopoDS_Shape edgeCompound, edgeClass ca Base::Console().Log("GO::addGeomFromCompound - edge: %d is zeroEdge\n", i); continue; } - if (DU::isCrazy(edge)) { + if (DU::isCrazy(edge)) { Base::Console().Log("GO::addGeomFromCompound - edge: %d is crazy\n", i); continue; } base = BaseGeom::baseFactory(edge); if (!base) { - Base::Console().Log("Error - GO::addGeomFromCompound - baseFactory failed for edge: %d\n", i); + Base::Console().Log( + "Error - GO::addGeomFromCompound - baseFactory failed for edge: %d\n", i); continue; -// throw Base::ValueError("GeometryObject::addGeomFromCompound - baseFactory failed"); + // throw Base::ValueError("GeometryObject::addGeomFromCompound - baseFactory failed"); } - base->source(0); //object geometry - base->sourceIndex(i-1); + base->source(0);//object geometry + base->sourceIndex(i - 1); base->classOfEdge = category; base->hlrVisible = hlrVisible; edgeGeom.push_back(base); @@ -605,47 +592,43 @@ void GeometryObject::addGeomFromCompound(TopoDS_Shape edgeCompound, edgeClass ca if ((*itVertex)->isEqual(*v2, Precision::Confusion())) { v2Add = false; } - if (circle ) { + if (circle) { if ((*itVertex)->isEqual(*c1, Precision::Confusion())) { c1Add = false; } } - } if (v1Add) { vertexGeom.push_back(v1); v1->hlrVisible = true; - } else { - // delete v1; + } + else { + // delete v1; } if (v2Add) { vertexGeom.push_back(v2); v2->hlrVisible = true; - } else { - // delete v2; + } + else { + // delete v2; } if (circle) { if (c1Add) { vertexGeom.push_back(c1); c1->hlrVisible = true; - } else { - // delete c1; + } + else { + // delete c1; } } } - } //end TopExp + }//end TopExp } -void GeometryObject::addVertex(TechDraw::VertexPtr v) -{ - vertexGeom.push_back(v); -} +void GeometryObject::addVertex(TechDraw::VertexPtr v) { vertexGeom.push_back(v); } -void GeometryObject::addEdge(TechDraw::BaseGeomPtr bg) -{ - edgeGeom.push_back(bg); -} +void GeometryObject::addEdge(TechDraw::BaseGeomPtr bg) { edgeGeom.push_back(bg); } //********** Cosmetic Vertex *************************************************** @@ -654,12 +637,12 @@ void GeometryObject::addEdge(TechDraw::BaseGeomPtr bg) // insertGeomForCV(cv) int GeometryObject::addCosmeticVertex(CosmeticVertex* cv) { -// Base::Console().Message("GO::addCosmeticVertex(%X)\n", cv); + // Base::Console().Message("GO::addCosmeticVertex(%X)\n", cv); double scale = m_parent->getScale(); Base::Vector3d pos = cv->scaled(scale); TechDraw::VertexPtr v(std::make_shared(pos.x, pos.y)); v->cosmetic = true; - v->cosmeticLink = -1; //obs?? + v->cosmeticLink = -1;//obs?? v->cosmeticTag = cv->getTagAsString(); v->hlrVisible = true; int idx = vertexGeom.size(); @@ -674,7 +657,7 @@ int GeometryObject::addCosmeticVertex(Base::Vector3d pos) Base::Console().Message("GO::addCosmeticVertex() 1 - deprec?\n"); TechDraw::VertexPtr v(std::make_shared(pos.x, pos.y)); v->cosmetic = true; - v->cosmeticTag = "tbi"; //not connected to CV + v->cosmeticTag = "tbi";//not connected to CV v->hlrVisible = true; int idx = vertexGeom.size(); vertexGeom.push_back(v); @@ -683,10 +666,10 @@ int GeometryObject::addCosmeticVertex(Base::Vector3d pos) int GeometryObject::addCosmeticVertex(Base::Vector3d pos, std::string tagString) { -// Base::Console().Message("GO::addCosmeticVertex() 2\n"); + // Base::Console().Message("GO::addCosmeticVertex() 2\n"); TechDraw::VertexPtr v(std::make_shared(pos.x, pos.y)); v->cosmetic = true; - v->cosmeticTag = tagString; //connected to CV + v->cosmeticTag = tagString;//connected to CV v->hlrVisible = true; int idx = vertexGeom.size(); vertexGeom.push_back(v); @@ -700,7 +683,7 @@ int GeometryObject::addCosmeticVertex(Base::Vector3d pos, std::string tagString) // insertGeomForCE(ce) int GeometryObject::addCosmeticEdge(CosmeticEdge* ce) { -// Base::Console().Message("GO::addCosmeticEdge(%X) 0\n", ce); + // Base::Console().Message("GO::addCosmeticEdge(%X) 0\n", ce); double scale = m_parent->getScale(); TechDraw::BaseGeomPtr e = ce->scaledGeometry(scale); e->cosmetic = true; @@ -713,16 +696,15 @@ int GeometryObject::addCosmeticEdge(CosmeticEdge* ce) //adds a new GeomEdge to list for ce[link] //this should be made obsolete and the variant with tag used instead -int GeometryObject::addCosmeticEdge(Base::Vector3d start, - Base::Vector3d end) +int GeometryObject::addCosmeticEdge(Base::Vector3d start, Base::Vector3d end) { -// Base::Console().Message("GO::addCosmeticEdge() 1 - deprec?\n"); + // Base::Console().Message("GO::addCosmeticEdge() 1 - deprec?\n"); gp_Pnt gp1(start.x, start.y, start.z); gp_Pnt gp2(end.x, end.y, end.z); TopoDS_Edge occEdge = BRepBuilderAPI_MakeEdge(gp1, gp2); TechDraw::BaseGeomPtr e = BaseGeom::baseFactory(occEdge); e->cosmetic = true; -// e->cosmeticLink = link; + // e->cosmeticLink = link; e->setCosmeticTag("tbi"); e->hlrVisible = true; int idx = edgeGeom.size(); @@ -730,31 +712,28 @@ int GeometryObject::addCosmeticEdge(Base::Vector3d start, return idx; } -int GeometryObject::addCosmeticEdge(Base::Vector3d start, - Base::Vector3d end, - std::string tagString) +int GeometryObject::addCosmeticEdge(Base::Vector3d start, Base::Vector3d end, std::string tagString) { -// Base::Console().Message("GO::addCosmeticEdge() 2\n"); + // Base::Console().Message("GO::addCosmeticEdge() 2\n"); gp_Pnt gp1(start.x, start.y, start.z); gp_Pnt gp2(end.x, end.y, end.z); TopoDS_Edge occEdge = BRepBuilderAPI_MakeEdge(gp1, gp2); TechDraw::BaseGeomPtr base = BaseGeom::baseFactory(occEdge); base->cosmetic = true; base->setCosmeticTag(tagString); - base->source(1); //1-CosmeticEdge, 2-CenterLine + base->source(1);//1-CosmeticEdge, 2-CenterLine base->hlrVisible = true; int idx = edgeGeom.size(); edgeGeom.push_back(base); return idx; } -int GeometryObject::addCosmeticEdge(TechDraw::BaseGeomPtr base, - std::string tagString) +int GeometryObject::addCosmeticEdge(TechDraw::BaseGeomPtr base, std::string tagString) { -// Base::Console().Message("GO::addCosmeticEdge(%X, %s) 3\n", base, tagString.c_str()); + // Base::Console().Message("GO::addCosmeticEdge(%X, %s) 3\n", base, tagString.c_str()); base->cosmetic = true; base->hlrVisible = true; - base->source(1); //1-CosmeticEdge, 2-CenterLine + base->source(1);//1-CosmeticEdge, 2-CenterLine base->setCosmeticTag(tagString); base->sourceIndex(-1); int idx = edgeGeom.size(); @@ -762,15 +741,14 @@ int GeometryObject::addCosmeticEdge(TechDraw::BaseGeomPtr base, return idx; } -int GeometryObject::addCenterLine(TechDraw::BaseGeomPtr base, - std::string tag) +int GeometryObject::addCenterLine(TechDraw::BaseGeomPtr base, std::string tag) // int s, int si) { -// Base::Console().Message("GO::addCenterLine()\n"); + // Base::Console().Message("GO::addCenterLine()\n"); base->cosmetic = true; base->setCosmeticTag(tag); base->source(2); -// base->sourceIndex(si); //index into source; + // base->sourceIndex(si); //index into source; int idx = edgeGeom.size(); edgeGeom.push_back(base); return idx; @@ -778,16 +756,10 @@ int GeometryObject::addCenterLine(TechDraw::BaseGeomPtr base, //! empty Face geometry -void GeometryObject::clearFaceGeom() -{ - faceGeom.clear(); -} +void GeometryObject::clearFaceGeom() { faceGeom.clear(); } //! add a Face to Face Geometry -void GeometryObject::addFaceGeom(FacePtr f) -{ - faceGeom.push_back(f); -} +void GeometryObject::addFaceGeom(FacePtr f) { faceGeom.push_back(f); } TechDraw::DrawViewDetail* GeometryObject::isParentDetail() { @@ -802,8 +774,7 @@ TechDraw::DrawViewDetail* GeometryObject::isParentDetail() } -bool GeometryObject::isWithinArc(double theta, double first, - double last, bool cw) const +bool GeometryObject::isWithinArc(double theta, double first, double last, bool cw) const { if (fabs(last - first) >= 2 * M_PI) { return true; @@ -828,13 +799,16 @@ bool GeometryObject::isWithinArc(double theta, double first, if (cw) { if (first > last) { return theta <= first && theta >= last; - } else { + } + else { return theta <= first || theta >= last; } - } else { + } + else { if (first > last) { return theta >= first || theta <= last; - } else { + } + else { return theta >= first && theta <= last; } } @@ -843,20 +817,20 @@ bool GeometryObject::isWithinArc(double theta, double first, //note bbx is scaled Base::BoundBox3d GeometryObject::calcBoundingBox() const { -// Base::Console().Message("GO::calcBoundingBox() - edges: %d\n", edgeGeom.size()); + // Base::Console().Message("GO::calcBoundingBox() - edges: %d\n", edgeGeom.size()); Bnd_Box testBox; testBox.SetGap(0.0); if (!edgeGeom.empty()) { - for (BaseGeomPtrVector::const_iterator it( edgeGeom.begin() ); - it != edgeGeom.end(); ++it) { - BRepBndLib::AddOptimal((*it)->occEdge, testBox); + for (BaseGeomPtrVector::const_iterator it(edgeGeom.begin()); it != edgeGeom.end(); ++it) { + BRepBndLib::AddOptimal((*it)->occEdge, testBox); } } double xMin = 0, xMax = 0, yMin = 0, yMax = 0, zMin = 0, zMax = 0; if (testBox.IsVoid()) { Base::Console().Log("INFO - GO::calcBoundingBox - testBox is void\n"); - } else { + } + else { testBox.Get(xMin, yMin, zMin, xMax, yMax, zMax); } Base::BoundBox3d bbox(xMin, yMin, zMin, xMax, yMax, zMax); @@ -865,14 +839,15 @@ Base::BoundBox3d GeometryObject::calcBoundingBox() const void GeometryObject::pruneVertexGeom(Base::Vector3d center, double radius) { - const std::vector& oldVerts = getVertexGeometry(); + const std::vector& oldVerts = getVertexGeometry(); std::vector newVerts; - for (auto& v: oldVerts) { + for (auto& v : oldVerts) { Base::Vector3d v3 = v->point(); double length = (v3 - center).Length(); if (length < Precision::Confusion()) { continue; - } else if (length < radius) { + } + else if (length < radius) { newVerts.push_back(v); } } @@ -899,12 +874,11 @@ bool GeometryObject::findVertex(Base::Vector3d v) //! used for individual views, but not secondary views in projection groups //! flip determines Y mirror or not. // getViewAxis 1 -gp_Ax2 TechDraw::getViewAxis(const Base::Vector3d origin, - const Base::Vector3d& direction, - const bool flip) +gp_Ax2 TechDraw::getViewAxis(const Base::Vector3d origin, const Base::Vector3d& direction, + const bool flip) { -// Base::Console().Message("GO::getViewAxis() - 1 - use only with getLegacyX\n"); - (void) flip; + // Base::Console().Message("GO::getViewAxis() - 1 - use only with getLegacyX\n"); + (void)flip; gp_Ax2 viewAxis; gp_Pnt inputCenter(origin.x, origin.y, origin.z); Base::Vector3d stdZ(0.0, 0.0, 1.0); @@ -912,47 +886,42 @@ gp_Ax2 TechDraw::getViewAxis(const Base::Vector3d origin, Base::Vector3d cross = direction; if (DU::checkParallel(direction, stdZ)) { cross = Base::Vector3d(1.0, 0.0, 0.0); - } else { + } + else { cross.Normalize(); cross = cross.Cross(stdZ); } if (cross.IsEqual(stdOrg, FLT_EPSILON)) { - viewAxis = gp_Ax2(inputCenter, - gp_Dir(direction.x, direction.y, direction.z)); + viewAxis = gp_Ax2(inputCenter, gp_Dir(direction.x, direction.y, direction.z)); return viewAxis; } - viewAxis = gp_Ax2(inputCenter, - gp_Dir(direction.x, direction.y, direction.z), + viewAxis = gp_Ax2(inputCenter, gp_Dir(direction.x, direction.y, direction.z), gp_Dir(cross.x, cross.y, cross.z)); return viewAxis; } //! gets a coordinate system specified by Z and X directions //getViewAxis 2 -gp_Ax2 TechDraw::getViewAxis(const Base::Vector3d origin, - const Base::Vector3d& direction, - const Base::Vector3d& xAxis, - const bool flip) +gp_Ax2 TechDraw::getViewAxis(const Base::Vector3d origin, const Base::Vector3d& direction, + const Base::Vector3d& xAxis, const bool flip) { -// Base::Console().Message("GO::getViewAxis() - 2\n"); - (void) flip; + // Base::Console().Message("GO::getViewAxis() - 2\n"); + (void)flip; gp_Pnt inputCenter(origin.x, origin.y, origin.z); gp_Ax2 viewAxis; - viewAxis = gp_Ax2(inputCenter, - gp_Dir(direction.x, direction.y, direction.z), + viewAxis = gp_Ax2(inputCenter, gp_Dir(direction.x, direction.y, direction.z), gp_Dir(xAxis.x, xAxis.y, xAxis.z)); return viewAxis; } // was getViewAxis 1 // getViewAxis as used before XDirection property adopted -gp_Ax2 TechDraw::legacyViewAxis1(const Base::Vector3d origin, - const Base::Vector3d& direction, - const bool flip) +gp_Ax2 TechDraw::legacyViewAxis1(const Base::Vector3d origin, const Base::Vector3d& direction, + const bool flip) { -// Base::Console().Message("GO::legacyViewAxis1()\n"); + // Base::Console().Message("GO::legacyViewAxis1()\n"); gp_Ax2 viewAxis; gp_Pnt inputCenter(origin.x, origin.y, origin.z); Base::Vector3d stdZ(0.0, 0.0, 1.0); @@ -962,29 +931,28 @@ gp_Ax2 TechDraw::legacyViewAxis1(const Base::Vector3d origin, flipDirection = Base::Vector3d(direction.x, direction.y, direction.z); } Base::Vector3d cross = flipDirection; -// //special case + // //special case if (DU::checkParallel(flipDirection, stdZ)) { cross = Base::Vector3d(1.0, 0.0, 0.0); - } else { + } + else { cross.Normalize(); cross = cross.Cross(stdZ); } if (cross.IsEqual(stdOrg, FLT_EPSILON)) { - viewAxis = gp_Ax2(inputCenter, - gp_Dir(flipDirection.x, flipDirection.y, flipDirection.z)); + viewAxis = gp_Ax2(inputCenter, gp_Dir(flipDirection.x, flipDirection.y, flipDirection.z)); return viewAxis; } - viewAxis = gp_Ax2(inputCenter, - gp_Dir(flipDirection.x, flipDirection.y, flipDirection.z), + viewAxis = gp_Ax2(inputCenter, gp_Dir(flipDirection.x, flipDirection.y, flipDirection.z), gp_Dir(cross.x, cross.y, cross.z)); //this bit is to handle the old mirror Y logic, but it messes up //some old files. gp_Trsf mirrorXForm; gp_Ax2 mirrorCS(inputCenter, gp_Dir(0, -1, 0)); - mirrorXForm.SetMirror( mirrorCS ); + mirrorXForm.SetMirror(mirrorCS); viewAxis = viewAxis.Transformed(mirrorXForm); return viewAxis; @@ -1000,28 +968,24 @@ gp_Pnt TechDraw::findCentroid(const TopoDS_Shape& shape) Standard_Real xMin, yMin, zMin, xMax, yMax, zMax; tBounds.Get(xMin, yMin, zMin, xMax, yMax, zMax); - Standard_Real x = (xMin + xMax) / 2.0, - y = (yMin + yMax) / 2.0, - z = (zMin + zMax) / 2.0; + Standard_Real x = (xMin + xMax) / 2.0, y = (yMin + yMax) / 2.0, z = (zMin + zMax) / 2.0; return gp_Pnt(x, y, z); } //! Returns the centroid of shape, as viewed according to direction -gp_Pnt TechDraw::findCentroid(const TopoDS_Shape &shape, - const Base::Vector3d &direction) +gp_Pnt TechDraw::findCentroid(const TopoDS_Shape& shape, const Base::Vector3d& direction) { -// Base::Console().Message("GO::findCentroid() - 1\n"); + // Base::Console().Message("GO::findCentroid() - 1\n"); Base::Vector3d origin(0.0, 0.0, 0.0); gp_Ax2 viewAxis = getViewAxis(origin, direction); return findCentroid(shape, viewAxis); } //! Returns the centroid of shape, as viewed according to direction -gp_Pnt TechDraw::findCentroid(const TopoDS_Shape &shape, - const gp_Ax2 &viewAxis) +gp_Pnt TechDraw::findCentroid(const TopoDS_Shape& shape, const gp_Ax2& viewAxis) { -// Base::Console().Message("GO::findCentroid() - 2\n"); + // Base::Console().Message("GO::findCentroid() - 2\n"); gp_Trsf tempTransform; tempTransform.SetTransformation(viewAxis); @@ -1034,9 +998,7 @@ gp_Pnt TechDraw::findCentroid(const TopoDS_Shape &shape, Standard_Real xMin, yMin, zMin, xMax, yMax, zMax; tBounds.Get(xMin, yMin, zMin, xMax, yMax, zMax); - Standard_Real x = (xMin + xMax) / 2.0, - y = (yMin + yMax) / 2.0, - z = (zMin + zMax) / 2.0; + Standard_Real x = (xMin + xMax) / 2.0, y = (yMin + yMax) / 2.0, z = (zMin + zMax) / 2.0; // Get centroid back into object space tempTransform.Inverted().Transforms(x, y, z); @@ -1044,37 +1006,56 @@ gp_Pnt TechDraw::findCentroid(const TopoDS_Shape &shape, return gp_Pnt(x, y, z); } -Base::Vector3d TechDraw::findCentroidVec(const TopoDS_Shape &shape, - const Base::Vector3d &direction) +Base::Vector3d TechDraw::findCentroidVec(const TopoDS_Shape& shape, const Base::Vector3d& direction) { -// Base::Console().Message("GO::findCentroidVec() - 1\n"); + // Base::Console().Message("GO::findCentroidVec() - 1\n"); gp_Pnt p = TechDraw::findCentroid(shape, direction); Base::Vector3d result(p.X(), p.Y(), p.Z()); return result; } -Base::Vector3d TechDraw::findCentroidVec(const TopoDS_Shape &shape, - const gp_Ax2 &cs) +Base::Vector3d TechDraw::findCentroidVec(const TopoDS_Shape& shape, const gp_Ax2& cs) { -// Base::Console().Message("GO::findCentroidVec() - 2\n"); + // Base::Console().Message("GO::findCentroidVec() - 2\n"); gp_Pnt p = TechDraw::findCentroid(shape, cs); Base::Vector3d result(p.X(), p.Y(), p.Z()); return result; } +//! Returns the XY plane center of shape with respect to coordSys +gp_Pnt TechDraw::findCentroidXY(const TopoDS_Shape& shape, const gp_Ax2& coordSys) +{ + // Base::Console().Message("GO::findCentroid() - 2\n"); + + gp_Trsf tempTransform; + tempTransform.SetTransformation(coordSys); + BRepBuilderAPI_Transform builder(shape, tempTransform); + + Bnd_Box tBounds; + tBounds.SetGap(0.0); + BRepBndLib::AddOptimal(builder.Shape(), tBounds, true, false); + + Standard_Real xMin, yMin, zMin, xMax, yMax, zMax; + tBounds.Get(xMin, yMin, zMin, xMax, yMax, zMax); + + Standard_Real x = (xMin + xMax) / 2.0, y = (yMin + yMax) / 2.0, z = 0.0; + + // Get "centroid" back into object space + tempTransform.Inverted().Transforms(x, y, z); + + return gp_Pnt(x, y, z); +} //!scales & mirrors a shape about a center -TopoDS_Shape TechDraw::mirrorShapeVec(const TopoDS_Shape &input, - const Base::Vector3d& inputCenter, - double scale) +TopoDS_Shape TechDraw::mirrorShapeVec(const TopoDS_Shape& input, const Base::Vector3d& inputCenter, + double scale) { gp_Pnt gInput(inputCenter.x, inputCenter.y, inputCenter.z); return TechDraw::mirrorShape(input, gInput, scale); } -TopoDS_Shape TechDraw::mirrorShape(const TopoDS_Shape &input, - const gp_Pnt& inputCenter, - double scale) +TopoDS_Shape TechDraw::mirrorShape(const TopoDS_Shape& input, const gp_Pnt& inputCenter, + double scale) { TopoDS_Shape transShape; if (input.IsNull()) { @@ -1087,11 +1068,12 @@ TopoDS_Shape TechDraw::mirrorShape(const TopoDS_Shape &input, //BRepBuilderAPI_Transform will loop forever if asked to use 0.0 as scale if (scale <= 0.0) { tempTransform.SetScale(inputCenter, 1.0); - } else { + } + else { tempTransform.SetScale(inputCenter, scale); } gp_Trsf mirrorTransform; - mirrorTransform.SetMirror( gp_Ax2(inputCenter, gp_Dir(0, -1, 0)) ); + mirrorTransform.SetMirror(gp_Ax2(inputCenter, gp_Dir(0, -1, 0))); tempTransform.Multiply(mirrorTransform); // Apply that transform to the shape. This should preserve the centre. @@ -1106,8 +1088,7 @@ TopoDS_Shape TechDraw::mirrorShape(const TopoDS_Shape &input, } //!rotates a shape about a viewAxis -TopoDS_Shape TechDraw::rotateShape(const TopoDS_Shape &input, - const gp_Ax2 &viewAxis, +TopoDS_Shape TechDraw::rotateShape(const TopoDS_Shape& input, const gp_Ax2& viewAxis, double rotAngle) { TopoDS_Shape transShape; @@ -1116,7 +1097,7 @@ TopoDS_Shape TechDraw::rotateShape(const TopoDS_Shape &input, } gp_Ax1 rotAxis = viewAxis.Axis(); - double rotation = rotAngle * M_PI/180.0; + double rotation = rotAngle * M_PI / 180.0; try { gp_Trsf tempTransform; @@ -1132,13 +1113,12 @@ TopoDS_Shape TechDraw::rotateShape(const TopoDS_Shape &input, } //!scales a shape about origin -TopoDS_Shape TechDraw::scaleShape(const TopoDS_Shape &input, - double scale) +TopoDS_Shape TechDraw::scaleShape(const TopoDS_Shape& input, double scale) { TopoDS_Shape transShape; try { gp_Trsf scaleTransform; - scaleTransform.SetScale(gp_Pnt(0, 0,0), scale); + scaleTransform.SetScale(gp_Pnt(0, 0, 0), scale); BRepBuilderAPI_Transform mkTrf(input, scaleTransform); transShape = mkTrf.Shape(); @@ -1151,8 +1131,7 @@ TopoDS_Shape TechDraw::scaleShape(const TopoDS_Shape &input, } //!moves a shape -TopoDS_Shape TechDraw::moveShape(const TopoDS_Shape &input, - const Base::Vector3d& motion) +TopoDS_Shape TechDraw::moveShape(const TopoDS_Shape& input, const Base::Vector3d& motion) { TopoDS_Shape transShape; try { @@ -1171,15 +1150,10 @@ TopoDS_Shape TechDraw::moveShape(const TopoDS_Shape &input, //!moves a shape with restricts on directions -TopoDS_Shape TechDraw::moveShapeRestricted(const TopoDS_Shape &input, - const Base::Vector3d& motion, - bool allowX, - bool allowY, - bool allowZ) +TopoDS_Shape TechDraw::moveShapeRestricted(const TopoDS_Shape& input, const Base::Vector3d& motion, + bool allowX, bool allowY, bool allowZ) { - gp_Vec gMotion(allowX ? motion.x : 0.0, - allowY ? motion.y : 0.0, - allowZ ? motion.z : 0.0); + gp_Vec gMotion(allowX ? motion.x : 0.0, allowY ? motion.y : 0.0, allowZ ? motion.z : 0.0); TopoDS_Shape transShape; try { gp_Trsf xlate; @@ -1196,13 +1170,10 @@ TopoDS_Shape TechDraw::moveShapeRestricted(const TopoDS_Shape &input, } //!moves a shape with restricts on directions -TopoDS_Shape TechDraw::moveShapeRestricted(const TopoDS_Shape &input, - const Base::Vector3d& motion, +TopoDS_Shape TechDraw::moveShapeRestricted(const TopoDS_Shape& input, const Base::Vector3d& motion, const Base::Vector3d& mask) { - gp_Vec gMotion(mask.x ? motion.x : 0.0, - mask.y ? motion.y : 0.0, - mask.z ? motion.z : 0.0); + gp_Vec gMotion(mask.x ? motion.x : 0.0, mask.y ? motion.y : 0.0, mask.z ? motion.z : 0.0); TopoDS_Shape transShape; try { @@ -1219,11 +1190,15 @@ TopoDS_Shape TechDraw::moveShapeRestricted(const TopoDS_Shape &input, return transShape; } -TopoDS_Shape TechDraw::moveShapeRestricted(const TopoDS_Shape &input, - const gp_Vec& motion, +TopoDS_Shape TechDraw::moveShapeRestricted(const TopoDS_Shape& input, const gp_Vec& motion, const gp_Vec& mask) { - return moveShapeRestricted(input, - DU::toVector3d(motion), - DU::toVector3d(mask)); + return moveShapeRestricted(input, DU::toVector3d(motion), DU::toVector3d(mask)); +} + +TopoDS_Shape TechDraw::centerShapeXY(const TopoDS_Shape& inShape, const gp_Ax2& coordSys) +{ + gp_Pnt inputCenter = findCentroidXY(inShape, coordSys); + Base::Vector3d centroid = DrawUtil::toVector3d(inputCenter); + return TechDraw::moveShape(inShape, centroid * -1.0); } diff --git a/src/Mod/TechDraw/App/GeometryObject.h b/src/Mod/TechDraw/App/GeometryObject.h index 78d6c695948f..60920f3af4f2 100644 --- a/src/Mod/TechDraw/App/GeometryObject.h +++ b/src/Mod/TechDraw/App/GeometryObject.h @@ -29,9 +29,9 @@ #include #include +#include #include #include -#include #include #include @@ -46,7 +46,7 @@ class DrawViewDetail; class DrawView; class CosmeticVertex; class CosmeticEdge; -} +}// namespace TechDraw namespace TechDraw { @@ -57,54 +57,43 @@ class Vertex; //! scales & mirrors a shape about a center -TopoDS_Shape TechDrawExport mirrorShapeVec(const TopoDS_Shape &input, - const Base::Vector3d& inputCenter = Base::Vector3d(0.0, 0.0, 0.0), - double scale = 1.0); +TopoDS_Shape TechDrawExport mirrorShapeVec( + const TopoDS_Shape& input, const Base::Vector3d& inputCenter = Base::Vector3d(0.0, 0.0, 0.0), + double scale = 1.0); -TopoDS_Shape TechDrawExport mirrorShape(const TopoDS_Shape &input, - const gp_Pnt& inputCenter = gp_Pnt(0.0, 0.0, 0.0), - double scale = 1.0); +TopoDS_Shape TechDrawExport mirrorShape(const TopoDS_Shape& input, + const gp_Pnt& inputCenter = gp_Pnt(0.0, 0.0, 0.0), + double scale = 1.0); -TopoDS_Shape TechDrawExport scaleShape(const TopoDS_Shape &input, - double scale); -TopoDS_Shape TechDrawExport rotateShape(const TopoDS_Shape &input, - const gp_Ax2& viewAxis, +TopoDS_Shape TechDrawExport scaleShape(const TopoDS_Shape& input, double scale); +TopoDS_Shape TechDrawExport rotateShape(const TopoDS_Shape& input, const gp_Ax2& viewAxis, double rotAngle); -TopoDS_Shape TechDrawExport moveShape(const TopoDS_Shape &input, - const Base::Vector3d& motion); -TopoDS_Shape TechDrawExport moveShapeRestricted(const TopoDS_Shape &input, - const Base::Vector3d& motion, - bool allowX = true, - bool allowY = true, - bool allowZ = true); -TopoDS_Shape TechDrawExport moveShapeRestricted(const TopoDS_Shape &input, +TopoDS_Shape TechDrawExport moveShape(const TopoDS_Shape& input, const Base::Vector3d& motion); +TopoDS_Shape TechDrawExport moveShapeRestricted(const TopoDS_Shape& input, + const Base::Vector3d& motion, bool allowX = true, + bool allowY = true, bool allowZ = true); +TopoDS_Shape TechDrawExport moveShapeRestricted(const TopoDS_Shape& input, const Base::Vector3d& motion, const Base::Vector3d& mask); -TopoDS_Shape TechDrawExport moveShapeRestricted(const TopoDS_Shape &input, - const gp_Vec& motion, +TopoDS_Shape TechDrawExport moveShapeRestricted(const TopoDS_Shape& input, const gp_Vec& motion, const gp_Vec& mask); +TopoDS_Shape TechDrawExport centerShapeXY(const TopoDS_Shape& inShape, const gp_Ax2& coordSys); //! Returns the centroid of shape, as viewed according to direction gp_Pnt TechDrawExport findCentroid(const TopoDS_Shape& shape); -gp_Pnt TechDrawExport findCentroid(const TopoDS_Shape &shape, - const Base::Vector3d &direction); -gp_Pnt TechDrawExport findCentroid(const TopoDS_Shape &shape, - const gp_Ax2 &viewAxis); -Base::Vector3d TechDrawExport findCentroidVec(const TopoDS_Shape &shape, - const Base::Vector3d &direction); -Base::Vector3d TechDrawExport findCentroidVec(const TopoDS_Shape &shape, - const gp_Ax2& cs); - -gp_Ax2 TechDrawExport getViewAxis(const Base::Vector3d origin, - const Base::Vector3d& direction, - const bool flip=true); -gp_Ax2 TechDrawExport getViewAxis(const Base::Vector3d origin, - const Base::Vector3d& direction, - const Base::Vector3d& xAxis, - const bool flip=true); -gp_Ax2 TechDrawExport legacyViewAxis1(const Base::Vector3d origin, - const Base::Vector3d& direction, - const bool flip=true); +gp_Pnt TechDrawExport findCentroid(const TopoDS_Shape& shape, const Base::Vector3d& direction); +gp_Pnt TechDrawExport findCentroid(const TopoDS_Shape& shape, const gp_Ax2& viewAxis); +Base::Vector3d TechDrawExport findCentroidVec(const TopoDS_Shape& shape, + const Base::Vector3d& direction); +Base::Vector3d TechDrawExport findCentroidVec(const TopoDS_Shape& shape, const gp_Ax2& cs); +gp_Pnt TechDrawExport findCentroidXY(const TopoDS_Shape& shape, const gp_Ax2& coordSys); + +gp_Ax2 TechDrawExport getViewAxis(const Base::Vector3d origin, const Base::Vector3d& direction, + const bool flip = true); +gp_Ax2 TechDrawExport getViewAxis(const Base::Vector3d origin, const Base::Vector3d& direction, + const Base::Vector3d& xAxis, const bool flip = true); +gp_Ax2 TechDrawExport legacyViewAxis1(const Base::Vector3d origin, const Base::Vector3d& direction, + const bool flip = true); class TechDrawExport GeometryObject { @@ -118,30 +107,25 @@ class TechDrawExport GeometryObject //! Returns 2D bounding box Base::BoundBox3d calcBoundingBox() const; - const std::vector & getVertexGeometry() const { return vertexGeom; } - const BaseGeomPtrVector & getEdgeGeometry() const { return edgeGeom; } + const std::vector& getVertexGeometry() const { return vertexGeom; } + const BaseGeomPtrVector& getEdgeGeometry() const { return edgeGeom; } const BaseGeomPtrVector getVisibleFaceEdges(bool smooth, bool seam) const; - const std::vector & getFaceGeometry() const { return faceGeom; } - - void setVertexGeometry(std::vector newVerts) {vertexGeom = newVerts; } - void setEdgeGeometry(BaseGeomPtrVector newGeoms) {edgeGeom = newGeoms; } - - void projectShape(const TopoDS_Shape &input, - const gp_Ax2 &viewAxis); - void projectShapeWithPolygonAlgo(const TopoDS_Shape &input, - const gp_Ax2 &viewAxis); - static TopoDS_Shape projectSimpleShape(const TopoDS_Shape &shape, - const gp_Ax2 &CS); - static TopoDS_Shape simpleProjection(const TopoDS_Shape& shape, - const gp_Ax2& projCS); - static TopoDS_Shape projectFace(const TopoDS_Shape &face, - const gp_Ax2 &CS); + const std::vector& getFaceGeometry() const { return faceGeom; } + + void setVertexGeometry(std::vector newVerts) { vertexGeom = newVerts; } + void setEdgeGeometry(BaseGeomPtrVector newGeoms) { edgeGeom = newGeoms; } + + void projectShape(const TopoDS_Shape& input, const gp_Ax2& viewAxis); + void projectShapeWithPolygonAlgo(const TopoDS_Shape& input, const gp_Ax2& viewAxis); + static TopoDS_Shape projectSimpleShape(const TopoDS_Shape& shape, const gp_Ax2& CS); + static TopoDS_Shape simpleProjection(const TopoDS_Shape& shape, const gp_Ax2& projCS); + static TopoDS_Shape projectFace(const TopoDS_Shape& face, const gp_Ax2& CS); void makeTDGeometry(); void extractGeometry(edgeClass category, bool visible); void addFaceGeom(FacePtr f); void clearFaceGeom(); void setIsoCount(int i) { m_isoCount = i; } - void setParentName(std::string n); //for debug messages + void setParentName(std::string n);//for debug messages void isPerspective(bool b) { m_isPersp = b; } bool isPerspective() { return m_isPersp; } void usePolygonHLR(bool b) { m_usePolygonHLR = b; } @@ -153,16 +137,16 @@ class TechDrawExport GeometryObject //dupl mirrorShape??? static TopoDS_Shape invertGeometry(const TopoDS_Shape s); - TopoDS_Shape getVisHard() { return visHard; } + TopoDS_Shape getVisHard() { return visHard; } TopoDS_Shape getVisOutline() { return visOutline; } - TopoDS_Shape getVisSmooth() { return visSmooth; } - TopoDS_Shape getVisSeam() { return visSeam; } - TopoDS_Shape getVisIso() { return visIso; } - TopoDS_Shape getHidHard() { return hidHard; } + TopoDS_Shape getVisSmooth() { return visSmooth; } + TopoDS_Shape getVisSeam() { return visSeam; } + TopoDS_Shape getVisIso() { return visIso; } + TopoDS_Shape getHidHard() { return hidHard; } TopoDS_Shape getHidOutline() { return hidOutline; } - TopoDS_Shape getHidSmooth() { return hidSmooth; } - TopoDS_Shape getHidSeam() { return hidSeam; } - TopoDS_Shape getHidIso() { return hidIso; } + TopoDS_Shape getHidSmooth() { return hidSmooth; } + TopoDS_Shape getHidSeam() { return hidSeam; } + TopoDS_Shape getHidIso() { return hidIso; } void addVertex(TechDraw::VertexPtr v); void addEdge(TechDraw::BaseGeomPtr bg); @@ -170,20 +154,14 @@ class TechDrawExport GeometryObject int addCosmeticVertex(CosmeticVertex* cv); int addCosmeticVertex(Base::Vector3d pos); - int addCosmeticVertex(Base::Vector3d pos, - std::string tagString); + int addCosmeticVertex(Base::Vector3d pos, std::string tagString); int addCosmeticEdge(CosmeticEdge* ce); - int addCosmeticEdge(Base::Vector3d start, - Base::Vector3d end); - int addCosmeticEdge(Base::Vector3d start, - Base::Vector3d end, - std::string tagString); - int addCosmeticEdge(TechDraw::BaseGeomPtr base, - std::string tagString); + int addCosmeticEdge(Base::Vector3d start, Base::Vector3d end); + int addCosmeticEdge(Base::Vector3d start, Base::Vector3d end, std::string tagString); + int addCosmeticEdge(TechDraw::BaseGeomPtr base, std::string tagString); - int addCenterLine(TechDraw::BaseGeomPtr bg, - std::string tag); + int addCenterLine(TechDraw::BaseGeomPtr bg, std::string tag); protected: //HLR output @@ -225,6 +203,6 @@ class TechDrawExport GeometryObject using GeometryObjectPtr = std::shared_ptr; -} //namespace TechDraw +}//namespace TechDraw #endif diff --git a/src/Mod/TechDraw/Gui/QGIViewPart.cpp b/src/Mod/TechDraw/Gui/QGIViewPart.cpp index 01de03ea7ddb..33f0c780bbfb 100644 --- a/src/Mod/TechDraw/Gui/QGIViewPart.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewPart.cpp @@ -22,11 +22,11 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include -# include -# include -#endif // #ifndef _PreComp_ +#include +#include +#endif// #ifndef _PreComp_ #include #include @@ -35,25 +35,25 @@ #include #include #include -#include #include +#include #include #include #include #include #include -#include "QGIViewPart.h" #include "MDIViewPage.h" #include "PreferencesGui.h" -#include "QGICenterLine.h" #include "QGICMark.h" +#include "QGICenterLine.h" #include "QGIEdge.h" #include "QGIFace.h" #include "QGIHighlight.h" #include "QGIMatting.h" #include "QGISectionLine.h" #include "QGIVertex.h" +#include "QGIViewPart.h" #include "Rez.h" #include "ViewProviderGeomHatch.h" #include "ViewProviderHatch.h" @@ -68,13 +68,12 @@ using DU = DrawUtil; #define GEOMETRYEDGE 0 #define COSMETICEDGE 1 -#define CENTERLINE 2 +#define CENTERLINE 2 -const float lineScaleFactor = Rez::guiX(1.); // temp fiddle for devel +const float lineScaleFactor = Rez::guiX(1.);// temp fiddle for devel -QGIViewPart::QGIViewPart() : - m_isExporting(false) +QGIViewPart::QGIViewPart() : m_isExporting(false) { setCacheMode(QGraphicsItem::NoCache); setHandlesChildEvents(false); @@ -87,17 +86,15 @@ QGIViewPart::QGIViewPart() : showSection = false; } -QGIViewPart::~QGIViewPart() -{ - tidy(); -} +QGIViewPart::~QGIViewPart() { tidy(); } -QVariant QGIViewPart::itemChange(GraphicsItemChange change, const QVariant &value) +QVariant QGIViewPart::itemChange(GraphicsItemChange change, const QVariant& value) { if (change == ItemSelectedHasChanged && scene()) { //There's nothing special for QGIVP to do when selection changes! - } else if(change == ItemSceneChange && scene()) { - tidy(); + } + else if (change == ItemSceneChange && scene()) { + tidy(); } return QGIView::itemChange(change, value); } @@ -106,18 +103,18 @@ QVariant QGIViewPart::itemChange(GraphicsItemChange change, const QVariant &valu void QGIViewPart::tidy() { //Delete any leftover items - for(QList::iterator it = deleteItems.begin(); it != deleteItems.end(); ++it) { + for (QList::iterator it = deleteItems.begin(); it != deleteItems.end(); ++it) { delete *it; } deleteItems.clear(); } -void QGIViewPart::setViewPartFeature(TechDraw::DrawViewPart *obj) +void QGIViewPart::setViewPartFeature(TechDraw::DrawViewPart* obj) { if (!obj) return; - setViewFeature(static_cast(obj)); + setViewFeature(static_cast(obj)); } QPainterPath QGIViewPart::drawPainterPath(TechDraw::BaseGeomPtr baseGeom) const @@ -135,52 +132,33 @@ QPainterPath QGIViewPart::geomToPainterPath(BaseGeomPtr baseGeom, double rot) if (!baseGeom) return path; - switch(baseGeom->geomType) { + switch (baseGeom->geomType) { case CIRCLE: { TechDraw::CirclePtr geom = std::static_pointer_cast(baseGeom); double x = geom->center.x - geom->radius; double y = geom->center.y - geom->radius; - path.addEllipse(Rez::guiX(x), - Rez::guiX(y), - Rez::guiX(geom->radius * 2), - Rez::guiX(geom->radius * 2)); //topleft@(x, y) radx, rady - } - break; - case ARCOFCIRCLE: { - TechDraw::AOCPtr geom = std::static_pointer_cast (baseGeom); + path.addEllipse(Rez::guiX(x), Rez::guiX(y), Rez::guiX(geom->radius * 2), + Rez::guiX(geom->radius * 2));//topleft@(x, y) radx, rady + } break; + case ARCOFCIRCLE: { + TechDraw::AOCPtr geom = std::static_pointer_cast(baseGeom); if (baseGeom->reversed) { - path.moveTo(Rez::guiX(geom->endPnt.x), - Rez::guiX(geom->endPnt.y)); - pathArc(path, - Rez::guiX(geom->radius), - Rez::guiX(geom->radius), - 0., - geom->largeArc, - !geom->cw, - Rez::guiX(geom->startPnt.x), - Rez::guiX(geom->startPnt.y), - Rez::guiX(geom->endPnt.x), - Rez::guiX(geom->endPnt.y)); - } else { - path.moveTo(Rez::guiX(geom->startPnt.x), - Rez::guiX(geom->startPnt.y)); - pathArc(path, - Rez::guiX(geom->radius), - Rez::guiX(geom->radius), - 0., - geom->largeArc, - geom->cw, - Rez::guiX(geom->endPnt.x), - Rez::guiX(geom->endPnt.y), - Rez::guiX(geom->startPnt.x), - Rez::guiX(geom->startPnt.y)); + path.moveTo(Rez::guiX(geom->endPnt.x), Rez::guiX(geom->endPnt.y)); + pathArc(path, Rez::guiX(geom->radius), Rez::guiX(geom->radius), 0., geom->largeArc, + !geom->cw, Rez::guiX(geom->startPnt.x), Rez::guiX(geom->startPnt.y), + Rez::guiX(geom->endPnt.x), Rez::guiX(geom->endPnt.y)); } + else { + path.moveTo(Rez::guiX(geom->startPnt.x), Rez::guiX(geom->startPnt.y)); + pathArc(path, Rez::guiX(geom->radius), Rez::guiX(geom->radius), 0., geom->largeArc, + geom->cw, Rez::guiX(geom->endPnt.x), Rez::guiX(geom->endPnt.y), + Rez::guiX(geom->startPnt.x), Rez::guiX(geom->startPnt.y)); } - break; + } break; case TechDraw::ELLIPSE: { - TechDraw::AOEPtr geom = std::static_pointer_cast (baseGeom); + TechDraw::AOEPtr geom = std::static_pointer_cast(baseGeom); // Calculate start and end points as ellipse with theta = 0 and pi double startX = geom->center.x + geom->major * cos(geom->angle), @@ -188,206 +166,189 @@ QPainterPath QGIViewPart::geomToPainterPath(BaseGeomPtr baseGeom, double rot) endX = geom->center.x - geom->major * cos(geom->angle), endY = geom->center.y - geom->major * sin(geom->angle); - pathArc(path, - Rez::guiX(geom->major), - Rez::guiX(geom->minor), - geom->angle, - false, - false, - Rez::guiX(endX), - Rez::guiX(endY), - Rez::guiX(startX), - Rez::guiX(startY)); - - pathArc(path, - Rez::guiX(geom->major), - Rez::guiX(geom->minor), - geom->angle, - false, - false, - Rez::guiX(startX), - Rez::guiX(startY), - Rez::guiX(endX), - Rez::guiX(endY)); - } - break; + pathArc(path, Rez::guiX(geom->major), Rez::guiX(geom->minor), geom->angle, false, false, + Rez::guiX(endX), Rez::guiX(endY), Rez::guiX(startX), Rez::guiX(startY)); + + pathArc(path, Rez::guiX(geom->major), Rez::guiX(geom->minor), geom->angle, false, false, + Rez::guiX(startX), Rez::guiX(startY), Rez::guiX(endX), Rez::guiX(endY)); + } break; case TechDraw::ARCOFELLIPSE: { - TechDraw::AOEPtr geom = std::static_pointer_cast (baseGeom); + TechDraw::AOEPtr geom = std::static_pointer_cast(baseGeom); if (baseGeom->reversed) { - path.moveTo(Rez::guiX(geom->endPnt.x), - Rez::guiX(geom->endPnt.y)); - pathArc(path, - Rez::guiX(geom->major), - Rez::guiX(geom->minor), - geom->angle, - geom->largeArc, - !geom->cw, - Rez::guiX(geom->startPnt.x), - Rez::guiX(geom->startPnt.y), - Rez::guiX(geom->endPnt.x), + path.moveTo(Rez::guiX(geom->endPnt.x), Rez::guiX(geom->endPnt.y)); + pathArc(path, Rez::guiX(geom->major), Rez::guiX(geom->minor), geom->angle, + geom->largeArc, !geom->cw, Rez::guiX(geom->startPnt.x), + Rez::guiX(geom->startPnt.y), Rez::guiX(geom->endPnt.x), Rez::guiX(geom->endPnt.y)); - } else { - path.moveTo(Rez::guiX(geom->startPnt.x), - Rez::guiX(geom->startPnt.y)); - pathArc(path, - Rez::guiX(geom->major), - Rez::guiX(geom->minor), - geom->angle, - geom->largeArc, - geom->cw, - Rez::guiX(geom->endPnt.x), - Rez::guiX(geom->endPnt.y), - Rez::guiX(geom->startPnt.x), - Rez::guiX(geom->startPnt.y)); } + else { + path.moveTo(Rez::guiX(geom->startPnt.x), Rez::guiX(geom->startPnt.y)); + pathArc(path, Rez::guiX(geom->major), Rez::guiX(geom->minor), geom->angle, + geom->largeArc, geom->cw, Rez::guiX(geom->endPnt.x), + Rez::guiX(geom->endPnt.y), Rez::guiX(geom->startPnt.x), + Rez::guiX(geom->startPnt.y)); } - break; + } break; case TechDraw::BEZIER: { - TechDraw::BezierSegmentPtr geom = std::static_pointer_cast(baseGeom); + TechDraw::BezierSegmentPtr geom = + std::static_pointer_cast(baseGeom); if (baseGeom->reversed) { if (!geom->pnts.empty()) { Base::Vector3d rStart = geom->pnts.back(); path.moveTo(Rez::guiX(rStart.x), Rez::guiX(rStart.y)); } - if ( geom->poles == 2 ) { + if (geom->poles == 2) { // Degree 1 bezier = straight line... path.lineTo(Rez::guiX(geom->pnts[0].x), Rez::guiX(geom->pnts[0].y)); - - } else if ( geom->poles == 3 ) { + } + else if (geom->poles == 3) { path.quadTo(Rez::guiX(geom->pnts[1].x), Rez::guiX(geom->pnts[1].y), Rez::guiX(geom->pnts[0].x), Rez::guiX(geom->pnts[0].y)); - } else if ( geom->poles == 4 ) { + } + else if (geom->poles == 4) { path.cubicTo(Rez::guiX(geom->pnts[2].x), Rez::guiX(geom->pnts[2].y), Rez::guiX(geom->pnts[1].x), Rez::guiX(geom->pnts[1].y), Rez::guiX(geom->pnts[0].x), Rez::guiX(geom->pnts[0].y)); - } else { //can only handle lines, quads, cubes + } + else {//can only handle lines, quads, cubes Base::Console().Error("Bad pole count (%d) for BezierSegment\n", geom->poles); auto itBez = geom->pnts.begin() + 1; - for (; itBez != geom->pnts.end();itBez++) { - path.lineTo(Rez::guiX((*itBez).x), Rez::guiX((*itBez).y)); //show something for debugging + for (; itBez != geom->pnts.end(); itBez++) { + path.lineTo(Rez::guiX((*itBez).x), + Rez::guiX((*itBez).y));//show something for debugging } } - } else { + } + else { // Move painter to the beginning path.moveTo(Rez::guiX(geom->pnts[0].x), Rez::guiX(geom->pnts[0].y)); - if ( geom->poles == 2 ) { + if (geom->poles == 2) { // Degree 1 bezier = straight line... path.lineTo(Rez::guiX(geom->pnts[1].x), Rez::guiX(geom->pnts[1].y)); - - } else if ( geom->poles == 3 ) { + } + else if (geom->poles == 3) { path.quadTo(Rez::guiX(geom->pnts[1].x), Rez::guiX(geom->pnts[1].y), Rez::guiX(geom->pnts[2].x), Rez::guiX(geom->pnts[2].y)); - - } else if ( geom->poles == 4 ) { + } + else if (geom->poles == 4) { path.cubicTo(Rez::guiX(geom->pnts[1].x), Rez::guiX(geom->pnts[1].y), Rez::guiX(geom->pnts[2].x), Rez::guiX(geom->pnts[2].y), Rez::guiX(geom->pnts[3].x), Rez::guiX(geom->pnts[3].y)); - } else { //can only handle lines, quads, cubes + } + else {//can only handle lines, quads, cubes Base::Console().Error("Bad pole count (%d) for BezierSegment\n", geom->poles); auto itBez = geom->pnts.begin() + 1; - for (; itBez != geom->pnts.end();itBez++) { - path.lineTo(Rez::guiX((*itBez).x), Rez::guiX((*itBez).y)); //show something for debugging + for (; itBez != geom->pnts.end(); itBez++) { + path.lineTo(Rez::guiX((*itBez).x), + Rez::guiX((*itBez).y));//show something for debugging } } } - } - break; + } break; case TechDraw::BSPLINE: { - TechDraw::BSplinePtr geom = std::static_pointer_cast (baseGeom); + TechDraw::BSplinePtr geom = std::static_pointer_cast(baseGeom); if (baseGeom->reversed) { - // Move painter to the end of our last segment - std::vector::const_reverse_iterator it = geom->segments.rbegin(); + // Move painter to the end of our last segment + std::vector::const_reverse_iterator it = + geom->segments.rbegin(); Base::Vector3d rStart = it->pnts.back(); path.moveTo(Rez::guiX(rStart.x), Rez::guiX(rStart.y)); - for ( ; it != geom->segments.rend(); ++it) { + for (; it != geom->segments.rend(); ++it) { // At this point, the painter is either at the beginning // of the first segment, or end of the last - if ( it->poles == 2 ) { + if (it->poles == 2) { // Degree 1 bezier = straight line... path.lineTo(Rez::guiX(it->pnts[0].x), Rez::guiX(it->pnts[0].y)); - - } else if ( it->poles == 3 ) { + } + else if (it->poles == 3) { path.quadTo(Rez::guiX(it->pnts[1].x), Rez::guiX(it->pnts[1].y), Rez::guiX(it->pnts[0].x), Rez::guiX(it->pnts[0].y)); - } else if ( it->poles == 4 ) { + } + else if (it->poles == 4) { path.cubicTo(Rez::guiX(it->pnts[2].x), Rez::guiX(it->pnts[2].y), Rez::guiX(it->pnts[1].x), Rez::guiX(it->pnts[1].y), Rez::guiX(it->pnts[0].x), Rez::guiX(it->pnts[0].y)); - } else { //can only handle lines, quads, cubes - Base::Console().Error("Bad pole count (%d) for BezierSegment of B-spline geometry\n", - it->poles); - path.lineTo(it->pnts[1].x, it->pnts[1].y); //show something for debugging + } + else {//can only handle lines, quads, cubes + Base::Console().Error( + "Bad pole count (%d) for BezierSegment of B-spline geometry\n", + it->poles); + path.lineTo(it->pnts[1].x, it->pnts[1].y);//show something for debugging } } - } else { + } + else { // Move painter to the beginning of our first segment std::vector::const_iterator it = geom->segments.begin(); path.moveTo(Rez::guiX(it->pnts[0].x), Rez::guiX(it->pnts[0].y)); - for ( ; it != geom->segments.end(); ++it) { + for (; it != geom->segments.end(); ++it) { // At this point, the painter is either at the beginning // of the first segment, or end of the last - if ( it->poles == 2 ) { + if (it->poles == 2) { // Degree 1 bezier = straight line... path.lineTo(Rez::guiX(it->pnts[1].x), Rez::guiX(it->pnts[1].y)); - } else if ( it->poles == 3 ) { + } + else if (it->poles == 3) { path.quadTo(Rez::guiX(it->pnts[1].x), Rez::guiX(it->pnts[1].y), Rez::guiX(it->pnts[2].x), Rez::guiX(it->pnts[2].y)); - } else if ( it->poles == 4 ) { + } + else if (it->poles == 4) { path.cubicTo(Rez::guiX(it->pnts[1].x), Rez::guiX(it->pnts[1].y), Rez::guiX(it->pnts[2].x), Rez::guiX(it->pnts[2].y), Rez::guiX(it->pnts[3].x), Rez::guiX(it->pnts[3].y)); - } else { - Base::Console().Error("Bad pole count (%d) for BezierSegment of B-spline geometry\n", - it->poles); - path.lineTo(it->pnts[1].x, it->pnts[1].y); //show something for debugging + } + else { + Base::Console().Error( + "Bad pole count (%d) for BezierSegment of B-spline geometry\n", + it->poles); + path.lineTo(it->pnts[1].x, it->pnts[1].y);//show something for debugging } } } - } - break; + } break; case TechDraw::GENERIC: { - TechDraw::GenericPtr geom = std::static_pointer_cast (baseGeom); + TechDraw::GenericPtr geom = std::static_pointer_cast(baseGeom); if (baseGeom->reversed) { if (!geom->points.empty()) { Base::Vector3d rStart = geom->points.back(); path.moveTo(Rez::guiX(rStart.x), Rez::guiX(rStart.y)); } std::vector::const_reverse_iterator it = geom->points.rbegin(); - for(++it; it != geom->points.rend(); ++it) { + for (++it; it != geom->points.rend(); ++it) { path.lineTo(Rez::guiX((*it).x), Rez::guiX((*it).y)); } - } else { - path.moveTo(Rez::guiX(geom->points[0].x), Rez::guiX(geom->points[0].y)); + } + else { + path.moveTo(Rez::guiX(geom->points[0].x), Rez::guiX(geom->points[0].y)); std::vector::const_iterator it = geom->points.begin(); - for(++it; it != geom->points.end(); ++it) { + for (++it; it != geom->points.end(); ++it) { path.lineTo(Rez::guiX((*it).x), Rez::guiX((*it).y)); } } - } - break; + } break; default: { - Base::Console().Error("Error - geomToPainterPath - UNKNOWN geomType: %d\n", baseGeom->geomType); - } - break; - } //sb end of switch - -//old rotate path logic. now done on App side. -// if (rot != 0.0) { -// QTransform t; -// t.rotate(-rot); -// path = t.map(path); -// } + Base::Console().Error("Error - geomToPainterPath - UNKNOWN geomType: %d\n", + baseGeom->geomType); + } break; + }//sb end of switch + + //old rotate path logic. now done on App side. + // if (rot != 0.0) { + // QTransform t; + // t.rotate(-rot); + // path = t.map(path); + // } return path; } void QGIViewPart::updateView(bool update) { -// Base::Console().Message("QGIVP::updateView() - %s\n", getViewObject()->getNameInDocument()); - auto viewPart( dynamic_cast(getViewObject()) ); + // Base::Console().Message("QGIVP::updateView() - %s\n", getViewObject()->getNameInDocument()); + auto viewPart(dynamic_cast(getViewObject())); if (!viewPart) return; auto vp = static_cast(getViewProvider(getViewObject())); @@ -399,25 +360,26 @@ void QGIViewPart::updateView(bool update) QGIView::updateView(update); } -void QGIViewPart::draw() { +void QGIViewPart::draw() +{ if (!isVisible()) return; drawViewPart(); drawMatting(); //this is old C/L - drawCenterLines(true); //have to draw centerlines after border to get size correct. - drawAllSectionLines(); //same for section lines + drawCenterLines(true);//have to draw centerlines after border to get size correct. + drawAllSectionLines();//same for section lines } void QGIViewPart::drawViewPart() { - auto viewPart( dynamic_cast(getViewObject()) ); + auto viewPart(dynamic_cast(getViewObject())); if (!viewPart) return; -// Base::Console().Message("QGIVP::DVP() - %s / %s\n", viewPart->getNameInDocument(), viewPart->Label.getValue()); + // Base::Console().Message("QGIVP::DVP() - %s / %s\n", viewPart->getNameInDocument(), viewPart->Label.getValue()); if (!viewPart->hasGeometry()) { - removePrimitives(); //clean the slate + removePrimitives();//clean the slate removeDecorations(); return; } @@ -426,35 +388,35 @@ void QGIViewPart::drawViewPart() if (!vp) return; - float lineWidth = vp->LineWidth.getValue() * lineScaleFactor; //thick - float lineWidthHid = vp->HiddenWidth.getValue() * lineScaleFactor; //thin - float lineWidthIso = vp->IsoWidth.getValue() * lineScaleFactor; //graphic -// float lineWidthExtra = viewPart->ExtraWidth.getValue() * lineScaleFactor; //extra + float lineWidth = vp->LineWidth.getValue() * lineScaleFactor; //thick + float lineWidthHid = vp->HiddenWidth.getValue() * lineScaleFactor;//thin + float lineWidthIso = vp->IsoWidth.getValue() * lineScaleFactor; //graphic + // float lineWidthExtra = viewPart->ExtraWidth.getValue() * lineScaleFactor; //extra bool showAll = vp->ShowAllEdges.getValue(); prepareGeometryChange(); - removePrimitives(); //clean the slate + removePrimitives();//clean the slate removeDecorations(); if (viewPart->handleFaces() && !viewPart->CoarseView.getValue()) { // Draw Faces std::vector hatchObjs = viewPart->getHatches(); std::vector geomObjs = viewPart->getGeomHatches(); - const std::vector &faceGeoms = viewPart->getFaceGeometry(); + const std::vector& faceGeoms = viewPart->getFaceGeometry(); std::vector::const_iterator fit = faceGeoms.begin(); - for(int i = 0 ; fit != faceGeoms.end(); fit++, i++) { + for (int i = 0; fit != faceGeoms.end(); fit++, i++) { QGIFace* newFace = drawFace(*fit, i); newFace->isHatched(false); newFace->setFillMode(QGIFace::PlainFill); TechDraw::DrawHatch* fHatch = faceIsHatched(i, hatchObjs); TechDraw::DrawGeomHatch* fGeom = faceIsGeomHatched(i, geomObjs); if (fGeom) { - const std::vector &sourceNames = fGeom->Source.getSubValues(); + const std::vector& sourceNames = fGeom->Source.getSubValues(); if (!sourceNames.empty()) { std::vector lineSets = fGeom->getTrimmedLines(i); if (!lineSets.empty()) { newFace->clearLineSets(); - for (auto& ls: lineSets) { + for (auto& ls : lineSets) { newFace->addLineSet(ls); } newFace->isHatched(true); @@ -474,21 +436,23 @@ void QGIViewPart::drawViewPart() } } } - } else if (fHatch) { + } + else if (fHatch) { Gui::ViewProvider* gvp = QGIView::getViewProvider(fHatch); ViewProviderHatch* hatchVp = dynamic_cast(gvp); if (fHatch->isSvgHatch()) { if (!fHatch->SvgIncluded.isEmpty()) { if (getExporting()) { newFace->hideSvg(true); - } else { + } + else { newFace->hideSvg(false); } newFace->isHatched(true); newFace->setFillMode(QGIFace::SvgFill); newFace->setHatchFile(fHatch->SvgIncluded.getValue()); -// Gui::ViewProvider* gvp = QGIView::getViewProvider(fHatch); -// ViewProviderHatch* hatchVp = dynamic_cast(gvp); + // Gui::ViewProvider* gvp = QGIView::getViewProvider(fHatch); + // ViewProviderHatch* hatchVp = dynamic_cast(gvp); if (hatchVp) { double hatchScale = hatchVp->HatchScale.getValue(); if (hatchScale > 0.0) { @@ -499,7 +463,8 @@ void QGIViewPart::drawViewPart() newFace->setHatchOffset(hatchVp->HatchOffset.getValue()); } } - } else { //bitmap hatch + } + else {//bitmap hatch newFace->isHatched(true); newFace->setFillMode(QGIFace::BitmapFill); newFace->setHatchFile(fHatch->SvgIncluded.getValue()); @@ -509,7 +474,7 @@ void QGIViewPart::drawViewPart() } } bool drawEdges = prefFaceEdges(); - newFace->setDrawEdges(drawEdges); //pref. for debugging only + newFace->setDrawEdges(drawEdges);//pref. for debugging only newFace->setZValue(ZVALUE::FACE); newFace->setPrettyNormal(); newFace->draw(); @@ -519,30 +484,30 @@ void QGIViewPart::drawViewPart() // Draw Edges QColor edgeColor = PreferencesGui::normalQColor(); - const TechDraw::BaseGeomPtrVector &geoms = viewPart->getEdgeGeometry(); + const TechDraw::BaseGeomPtrVector& geoms = viewPart->getEdgeGeometry(); TechDraw::BaseGeomPtrVector::const_iterator itGeom = geoms.begin(); QGIEdge* item; - for(int i = 0 ; itGeom != geoms.end(); itGeom++, i++) { + for (int i = 0; itGeom != geoms.end(); itGeom++, i++) { bool showEdge = false; if ((*itGeom)->hlrVisible) { - if (((*itGeom)->classOfEdge == ecHARD) || - ((*itGeom)->classOfEdge == ecOUTLINE) || - (((*itGeom)->classOfEdge == ecSMOOTH) && viewPart->SmoothVisible.getValue()) || - (((*itGeom)->classOfEdge == ecSEAM) && viewPart->SeamVisible.getValue()) || - (((*itGeom)->classOfEdge == ecUVISO) && viewPart->IsoVisible.getValue())) { + if (((*itGeom)->classOfEdge == ecHARD) || ((*itGeom)->classOfEdge == ecOUTLINE) + || (((*itGeom)->classOfEdge == ecSMOOTH) && viewPart->SmoothVisible.getValue()) + || (((*itGeom)->classOfEdge == ecSEAM) && viewPart->SeamVisible.getValue()) + || (((*itGeom)->classOfEdge == ecUVISO) && viewPart->IsoVisible.getValue())) { showEdge = true; } - } else { - if ( (((*itGeom)->classOfEdge == ecHARD) && (viewPart->HardHidden.getValue())) || - (((*itGeom)->classOfEdge == ecOUTLINE) && (viewPart->HardHidden.getValue())) || - (((*itGeom)->classOfEdge == ecSMOOTH) && (viewPart->SmoothHidden.getValue())) || - (((*itGeom)->classOfEdge == ecSEAM) && (viewPart->SeamHidden.getValue())) || - (((*itGeom)->classOfEdge == ecUVISO) && (viewPart->IsoHidden.getValue())) ) { + } + else { + if ((((*itGeom)->classOfEdge == ecHARD) && (viewPart->HardHidden.getValue())) + || (((*itGeom)->classOfEdge == ecOUTLINE) && (viewPart->HardHidden.getValue())) + || (((*itGeom)->classOfEdge == ecSMOOTH) && (viewPart->SmoothHidden.getValue())) + || (((*itGeom)->classOfEdge == ecSEAM) && (viewPart->SeamHidden.getValue())) + || (((*itGeom)->classOfEdge == ecUVISO) && (viewPart->IsoHidden.getValue()))) { showEdge = true; } } bool showItem = true; - if (showEdge) { //based on hard/seam/hidden/etc + if (showEdge) {//based on hard/seam/hidden/etc item = new QGIEdge(i); item->setWidth(lineWidth); item->setNormalColor(edgeColor); @@ -552,13 +517,17 @@ void QGIViewPart::drawViewPart() if (source == COSMETICEDGE) { std::string cTag = (*itGeom)->getCosmeticTag(); showItem = formatGeomFromCosmetic(cTag, item); - } else if (source == CENTERLINE) { + } + else if (source == CENTERLINE) { std::string cTag = (*itGeom)->getCosmeticTag(); showItem = formatGeomFromCenterLine(cTag, item); - } else { - Base::Console().Message("QGIVP::drawVP - edge: %d is confused - source: %d\n", i,source); } - } else { + else { + Base::Console().Message("QGIVP::drawVP - edge: %d is confused - source: %d\n", + i, source); + } + } + else { TechDraw::GeomFormat* gf = viewPart->getGeomFormatBySelection(i); if (gf) { item->setNormalColor(gf->m_format.m_color.asValue()); @@ -568,11 +537,11 @@ void QGIViewPart::drawViewPart() } } - addToGroup(item); //item is at scene(0, 0), not group(0, 0) - item->setPos(0.0, 0.0); //now at group(0, 0) + addToGroup(item); //item is at scene(0, 0), not group(0, 0) + item->setPos(0.0, 0.0);//now at group(0, 0) item->setPath(drawPainterPath(*itGeom)); item->setZValue(ZVALUE::EDGE); - if(!(*itGeom)->hlrVisible) { + if (!(*itGeom)->hlrVisible) { item->setWidth(lineWidthHid); item->setHiddenEdge(true); item->setZValue(ZVALUE::HIDEDGE); @@ -581,63 +550,68 @@ void QGIViewPart::drawViewPart() item->setWidth(lineWidthIso); } item->setPrettyNormal(); - if (!showAll) { //view level "show" status - if (!showItem) { //individual edge "show" status + if (!showAll) { //view level "show" status + if (!showItem) {//individual edge "show" status item->hide(); } } //debug a path -// QPainterPath edgePath=drawPainterPath(*itGeom); -// std::stringstream edgeId; -// edgeId << "QGIVP.edgePath" << i; -// dumpPath(edgeId.str().c_str(), edgePath); - } + // QPainterPath edgePath=drawPainterPath(*itGeom); + // std::stringstream edgeId; + // edgeId << "QGIVP.edgePath" << i; + // dumpPath(edgeId.str().c_str(), edgePath); + } } // Draw Vertexs: - Base::Reference hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> - GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/General"); double vertexScaleFactor = hGrp->GetFloat("VertexScale", 3.0); QColor vertexColor = PreferencesGui::vertexQColor(); bool showVertices = true; bool showCenterMarks = true; - if (getFrameState()) { //frames are on + if (getFrameState()) {//frames are on if (viewPart->CoarseView.getValue()) { showVertices = false; } if (!vp->ArcCenterMarks.getValue()) { showCenterMarks = false; } - } else { //frames are off + } + else {//frames are off showVertices = false; - if (!prefPrintCenters()) { //based on preference (!frame && !pref) + if (!prefPrintCenters()) {//based on preference (!frame && !pref) showCenterMarks = false; } - if (!vp->ArcCenterMarks.getValue()) { //based on property (!frame && !prop) + if (!vp->ArcCenterMarks.getValue()) {//based on property (!frame && !prop) showCenterMarks = false; } } - const std::vector &verts = viewPart->getVertexGeometry(); + const std::vector& verts = viewPart->getVertexGeometry(); std::vector::const_iterator vert = verts.begin(); double cAdjust = vp->CenterScale.getValue(); - for(int i = 0 ; vert != verts.end(); ++vert, i++) { + for (int i = 0; vert != verts.end(); ++vert, i++) { if ((*vert)->isCenter) { if (showCenterMarks) { QGICMark* cmItem = new QGICMark(i); addToGroup(cmItem); cmItem->setPos(Rez::guiX((*vert)->x()), Rez::guiX((*vert)->y())); - cmItem->setThick(0.5 * lineWidth); //need minimum? - cmItem->setSize( cAdjust * lineWidth * vertexScaleFactor); + cmItem->setThick(0.5 * lineWidth);//need minimum? + cmItem->setSize(cAdjust * lineWidth * vertexScaleFactor); cmItem->setPrettyNormal(); cmItem->setZValue(ZVALUE::VERTEX); } - } else { //regular Vertex + } + else {//regular Vertex if (showVertices) { - QGIVertex *item = new QGIVertex(i); + QGIVertex* item = new QGIVertex(i); addToGroup(item); item->setPos(Rez::guiX((*vert)->x()), Rez::guiX((*vert)->y())); item->setNormalColor(vertexColor); @@ -651,16 +625,16 @@ void QGIViewPart::drawViewPart() //draw detail highlights auto drefs = viewPart->getDetailRefs(); - for (auto& r:drefs) { + for (auto& r : drefs) { drawHighlight(r, true); } } bool QGIViewPart::formatGeomFromCosmetic(std::string cTag, QGIEdge* item) { -// Base::Console().Message("QGIVP::formatGeomFromCosmetic(%s)\n", cTag.c_str()); + // Base::Console().Message("QGIVP::formatGeomFromCosmetic(%s)\n", cTag.c_str()); bool result = true; - auto partFeat( dynamic_cast(getViewObject()) ); + auto partFeat(dynamic_cast(getViewObject())); TechDraw::CosmeticEdge* ce = partFeat ? partFeat->getCosmeticEdge(cTag) : nullptr; if (ce) { item->setNormalColor(ce->m_format.m_color.asValue()); @@ -674,9 +648,9 @@ bool QGIViewPart::formatGeomFromCosmetic(std::string cTag, QGIEdge* item) bool QGIViewPart::formatGeomFromCenterLine(std::string cTag, QGIEdge* item) { -// Base::Console().Message("QGIVP::formatGeomFromCenterLine(%d)\n", sourceIndex); + // Base::Console().Message("QGIVP::formatGeomFromCenterLine(%d)\n", sourceIndex); bool result = true; - auto partFeat( dynamic_cast(getViewObject()) ); + auto partFeat(dynamic_cast(getViewObject())); TechDraw::CenterLine* cl = partFeat ? partFeat->getCenterLine(cTag) : nullptr; if (cl) { item->setNormalColor(cl->m_format.m_color.asValue()); @@ -689,10 +663,11 @@ bool QGIViewPart::formatGeomFromCenterLine(std::string cTag, QGIEdge* item) QGIFace* QGIViewPart::drawFace(TechDraw::FacePtr f, int idx) { -// Base::Console().Message("QGIVP::drawFace - %d\n", idx); - std::vector fWires = f->wires; + // Base::Console().Message("QGIVP::drawFace - %d\n", idx); + std::vector fWires = f->wires; QPainterPath facePath; - for(std::vector::iterator wire = fWires.begin(); wire != fWires.end(); ++wire) { + for (std::vector::iterator wire = fWires.begin(); wire != fWires.end(); + ++wire) { TechDraw::BaseGeomPtrVector geoms = (*wire)->geoms; if (geoms.empty()) continue; @@ -703,25 +678,26 @@ QGIFace* QGIViewPart::drawFace(TechDraw::FacePtr f, int idx) //wirePath.moveTo(startPoint); QPainterPath firstSeg = drawPainterPath(firstGeom); wirePath.connectPath(firstSeg); - for(TechDraw::BaseGeomPtrVector::iterator edge = ((*wire)->geoms.begin()) + 1; edge != (*wire)->geoms.end(); ++edge) { + for (TechDraw::BaseGeomPtrVector::iterator edge = ((*wire)->geoms.begin()) + 1; + edge != (*wire)->geoms.end(); ++edge) { QPainterPath edgePath = drawPainterPath(*edge); //handle section faces differently if (idx == -1) { - QPointF wEnd = wirePath.currentPosition(); - auto element = edgePath.elementAt(0); - QPointF eStart(element.x, element.y); - QPointF eEnd = edgePath.currentPosition(); - QPointF sVec = wEnd - eStart; - QPointF eVec = wEnd - eEnd; - double sDist2 = sVec.x() * sVec.x() + sVec.y() * sVec.y(); - double eDist2 = eVec.x() * eVec.x() + eVec.y() * eVec.y(); - if (sDist2 > eDist2) { - edgePath = edgePath.toReversed(); - } - } + QPointF wEnd = wirePath.currentPosition(); + auto element = edgePath.elementAt(0); + QPointF eStart(element.x, element.y); + QPointF eEnd = edgePath.currentPosition(); + QPointF sVec = wEnd - eStart; + QPointF eVec = wEnd - eEnd; + double sDist2 = sVec.x() * sVec.x() + sVec.y() * sVec.y(); + double eDist2 = eVec.x() * eVec.x() + eVec.y() * eVec.y(); + if (sDist2 > eDist2) { + edgePath = edgePath.toReversed(); + } + } wirePath.connectPath(edgePath); } -// dumpPath("wirePath:", wirePath); + // dumpPath("wirePath:", wirePath); facePath.addPath(wirePath); } facePath.setFillRule(Qt::OddEvenFill); @@ -747,14 +723,14 @@ void QGIViewPart::removePrimitives() if (mdi) { getMDIViewPage()->blockSceneSelection(true); } - for (auto& c:children) { - QGIPrimPath* prim = dynamic_cast(c); - if (prim) { + for (auto& c : children) { + QGIPrimPath* prim = dynamic_cast(c); + if (prim) { prim->hide(); scene()->removeItem(prim); delete prim; - } - } + } + } if (mdi) { getMDIViewPage()->blockSceneSelection(false); } @@ -764,25 +740,25 @@ void QGIViewPart::removePrimitives() void QGIViewPart::removeDecorations() { QList children = childItems(); - for (auto& c:children) { - QGIDecoration* decor = dynamic_cast(c); - QGIMatting* mat = dynamic_cast(c); - if (decor) { + for (auto& c : children) { + QGIDecoration* decor = dynamic_cast(c); + QGIMatting* mat = dynamic_cast(c); + if (decor) { decor->hide(); scene()->removeItem(decor); delete decor; - } else if (mat) { + } + else if (mat) { mat->hide(); scene()->removeItem(mat); delete mat; - } - - } + } + } } void QGIViewPart::drawAllSectionLines() { - TechDraw::DrawViewPart *viewPart = static_cast(getViewObject()); + TechDraw::DrawViewPart* viewPart = static_cast(getViewObject()); if (!viewPart) return; @@ -791,10 +767,11 @@ void QGIViewPart::drawAllSectionLines() return; if (vp->ShowSectionLine.getValue()) { auto refs = viewPart->getSectionRefs(); - for (auto& r:refs) { + for (auto& r : refs) { if (r->isDerivedFrom(DrawComplexSection::getClassTypeId())) { drawComplexSectionLine(r, true); - } else { + } + else { drawSectionLine(r, true); } } @@ -803,7 +780,7 @@ void QGIViewPart::drawAllSectionLines() void QGIViewPart::drawSectionLine(TechDraw::DrawViewSection* viewSection, bool b) { - TechDraw::DrawViewPart *viewPart = static_cast(getViewObject()); + TechDraw::DrawViewPart* viewPart = static_cast(getViewObject()); if (!viewPart) return; if (!viewSection) @@ -816,7 +793,7 @@ void QGIViewPart::drawSectionLine(TechDraw::DrawViewSection* viewSection, bool b if (!vp) { return; } - float lineWidthThin = vp->HiddenWidth.getValue() * lineScaleFactor; //thin + float lineWidthThin = vp->HiddenWidth.getValue() * lineScaleFactor;//thin if (b) { QGISectionLine* sectionLine = new QGISectionLine(); @@ -835,13 +812,12 @@ void QGIViewPart::drawSectionLine(TechDraw::DrawViewSection* viewSection, bool b double fudge = 2.0 * Preferences::dimFontSizeMM(); Base::Vector3d lineDir = l2 - l1; lineDir.Normalize(); - sectionLine->setEnds(l1 - lineDir * Rez::guiX(fudge), - l2 + lineDir * Rez::guiX(fudge)); + sectionLine->setEnds(l1 - lineDir * Rez::guiX(fudge), l2 + lineDir * Rez::guiX(fudge)); //which way do the arrows point? Base::Vector3d arrowDir = viewSection->SectionNormal.getValue(); - arrowDir = - viewPart->projectPoint(arrowDir); //arrows point reverse of sectionNormal - sectionLine->setDirection(arrowDir.x, - arrowDir.y); //3d direction needs Y inversion + arrowDir = -viewPart->projectPoint(arrowDir); //arrows point reverse of sectionNormal + sectionLine->setDirection(arrowDir.x, -arrowDir.y);//3d direction needs Y inversion if (vp->SectionLineMarks.getValue()) { ChangePointVector points = viewSection->getChangePointsFromSectionLine(); @@ -854,7 +830,8 @@ void QGIViewPart::drawSectionLine(TechDraw::DrawViewSection* viewSection, bool b points.front().setLocation(location0); points.back().setLocation(location1); sectionLine->setChangePoints(points); - } else { + } + else { sectionLine->clearChangePoints(); } @@ -864,7 +841,7 @@ void QGIViewPart::drawSectionLine(TechDraw::DrawViewSection* viewSection, bool b double fontSize = Preferences::dimFontSizeMM(); sectionLine->setFont(getFont(), fontSize); sectionLine->setZValue(ZVALUE::SECTIONLINE); - sectionLine->setRotation(- viewPart->Rotation.getValue()); + sectionLine->setRotation(-viewPart->Rotation.getValue()); sectionLine->draw(); } } @@ -872,7 +849,7 @@ void QGIViewPart::drawSectionLine(TechDraw::DrawViewSection* viewSection, bool b void QGIViewPart::drawComplexSectionLine(TechDraw::DrawViewSection* viewSection, bool b) { Q_UNUSED(b); - TechDraw::DrawViewPart *viewPart = static_cast(getViewObject()); + TechDraw::DrawViewPart* viewPart = static_cast(getViewObject()); if (!viewPart) return; if (!viewSection) @@ -881,7 +858,7 @@ void QGIViewPart::drawComplexSectionLine(TechDraw::DrawViewSection* viewSection, if (!vp) { return; } - float lineWidthThin = vp->HiddenWidth.getValue() * lineScaleFactor; //thin + float lineWidthThin = vp->HiddenWidth.getValue() * lineScaleFactor;//thin auto dcs = static_cast(viewSection); BaseGeomPtrVector edges = dcs->makeSectionLineGeometry(); @@ -899,7 +876,7 @@ void QGIViewPart::drawComplexSectionLine(TechDraw::DrawViewSection* viewSection, } std::pair ends = dcs->sectionLineEnds(); - Base::Vector3d vStart = Rez::guiX(ends.first); //already scaled by dcs + Base::Vector3d vStart = Rez::guiX(ends.first);//already scaled by dcs Base::Vector3d vEnd = Rez::guiX(ends.second); QGISectionLine* sectionLine = new QGISectionLine(); @@ -912,14 +889,17 @@ void QGIViewPart::drawComplexSectionLine(TechDraw::DrawViewSection* viewSection, sectionLine->setEnds(vStart, vEnd); if (vp->SectionLineMarks.getValue()) { sectionLine->setChangePoints(dcs->getChangePointsFromSectionLine()); - } else { + } + else { sectionLine->clearChangePoints(); } if (dcs->ProjectionStrategy.isValue("Offset")) { Base::Vector3d arrowDirOffset = viewSection->SectionNormal.getValue(); - arrowDirOffset = - viewPart->projectPoint(arrowDirOffset); //arrows are opposite section normal - sectionLine->setDirection(arrowDirOffset.x, -arrowDirOffset.y); //invert y for Qt - } else { + arrowDirOffset = + -viewPart->projectPoint(arrowDirOffset);//arrows are opposite section normal + sectionLine->setDirection(arrowDirOffset.x, -arrowDirOffset.y);//invert y for Qt + } + else { std::pair dirsAligned = dcs->sectionArrowDirs(); dirsAligned.first = DrawUtil::invertY(dirsAligned.first); dirsAligned.second = DrawUtil::invertY(dirsAligned.second); @@ -932,14 +912,14 @@ void QGIViewPart::drawComplexSectionLine(TechDraw::DrawViewSection* viewSection, double fontSize = Preferences::dimFontSizeMM(); sectionLine->setFont(getFont(), fontSize); sectionLine->setZValue(ZVALUE::SECTIONLINE); - sectionLine->setRotation(- viewPart->Rotation.getValue()); + sectionLine->setRotation(-viewPart->Rotation.getValue()); sectionLine->draw(); } //TODO: use Cosmetic::CenterLine object for this to make it usable for dims. void QGIViewPart::drawCenterLines(bool b) { - TechDraw::DrawViewPart *viewPart = dynamic_cast(getViewObject()); + TechDraw::DrawViewPart* viewPart = dynamic_cast(getViewObject()); if (!viewPart) return; @@ -955,7 +935,7 @@ void QGIViewPart::drawCenterLines(bool b) double sectionSpan; double sectionFudge = Rez::guiX(10.0); double xVal, yVal; - if (horiz) { + if (horiz) { centerLine = new QGICenterLine(); addToGroup(centerLine); centerLine->setPos(0.0, 0.0); @@ -988,9 +968,8 @@ void QGIViewPart::drawCenterLines(bool b) void QGIViewPart::drawHighlight(TechDraw::DrawViewDetail* viewDetail, bool b) { - TechDraw::DrawViewPart *viewPart = static_cast(getViewObject()); - if (!viewPart || - !viewDetail) { + TechDraw::DrawViewPart* viewPart = static_cast(getViewObject()); + if (!viewPart || !viewDetail) { return; } @@ -999,28 +978,31 @@ void QGIViewPart::drawHighlight(TechDraw::DrawViewDetail* viewDetail, bool b) return; if (b) { -// double fontSize = getPrefFontSize(); + // double fontSize = getPrefFontSize(); double fontSize = Preferences::labelFontSizeMM(); QGIHighlight* highlight = new QGIHighlight(); addToGroup(highlight); - highlight->setPos(0.0, 0.0); //sb setPos(center.x, center.y)? + highlight->setPos(0.0, 0.0);//sb setPos(center.x, center.y)? highlight->setReference(viewDetail->Reference.getValue()); highlight->setStyle((Qt::PenStyle)vp->HighlightLineStyle.getValue()); highlight->setColor(vp->HighlightLineColor.getValue().asValue()); Base::Vector3d center = viewDetail->AnchorPoint.getValue() * viewPart->getScale(); + double rotationRad = viewPart->Rotation.getValue() * M_PI / 180.0; + center.RotateZ(rotationRad); double radius = viewDetail->Radius.getValue() * viewPart->getScale(); - highlight->setBounds(center.x - radius, center.y + radius, center.x + radius, center.y - radius); + highlight->setBounds(center.x - radius, center.y + radius, center.x + radius, + center.y - radius); highlight->setWidth(Rez::guiX(vp->IsoWidth.getValue())); highlight->setFont(getFont(), fontSize); highlight->setZValue(ZVALUE::HIGHLIGHT); + //handle conversion of apparent X,Y to rotated QPointF rotCenter = highlight->mapFromParent(transformOriginPoint()); highlight->setTransformOriginPoint(rotCenter); - double rotation = viewPart->Rotation.getValue() + - vp->HighlightAdjust.getValue(); + double rotation = viewPart->Rotation.getValue() + vp->HighlightAdjust.getValue(); highlight->setRotation(rotation); highlight->draw(); } @@ -1028,11 +1010,12 @@ void QGIViewPart::drawHighlight(TechDraw::DrawViewDetail* viewDetail, bool b) void QGIViewPart::drawMatting() { - auto viewPart( dynamic_cast(getViewObject()) ); + auto viewPart(dynamic_cast(getViewObject())); TechDraw::DrawViewDetail* dvd = nullptr; if (viewPart && viewPart->isDerivedFrom(TechDraw::DrawViewDetail::getClassTypeId())) { dvd = static_cast(viewPart); - } else { + } + else { return; } @@ -1050,10 +1033,9 @@ void QGIViewPart::drawMatting() // pathArc(path, geom->major, geom->minor, geom->angle, geom->largeArc, geom->cw, // geom->endPnt.x, geom->endPnt.y, // geom->startPnt.x, geom->startPnt.y); -void QGIViewPart::pathArc(QPainterPath &path, double rx, double ry, double x_axis_rotation, - bool large_arc_flag, bool sweep_flag, - double x, double y, - double curx, double cury) +void QGIViewPart::pathArc(QPainterPath& path, double rx, double ry, double x_axis_rotation, + bool large_arc_flag, bool sweep_flag, double x, double y, double curx, + double cury) { double sin_th, cos_th; double a00, a01, a10, a11; @@ -1071,7 +1053,7 @@ void QGIViewPart::pathArc(QPainterPath &path, double rx, double ry, double x_axi dx = (curx - x) / 2.0; dy = (cury - y) / 2.0; - dx1 = cos_th * dx + sin_th * dy; + dx1 = cos_th * dx + sin_th * dy; dy1 = -sin_th * dx + cos_th * dy; Pr1 = rx * rx; Pr2 = ry * ry; @@ -1084,10 +1066,10 @@ void QGIViewPart::pathArc(QPainterPath &path, double rx, double ry, double x_axi ry = ry * qSqrt(check); } - a00 = cos_th / rx; - a01 = sin_th / rx; + a00 = cos_th / rx; + a01 = sin_th / rx; a10 = -sin_th / ry; - a11 = cos_th / ry; + a11 = cos_th / ry; x0 = a00 * curx + a01 * cury; y0 = a10 * curx + a11 * cury; x1 = a00 * x + a01 * y; @@ -1125,17 +1107,13 @@ void QGIViewPart::pathArc(QPainterPath &path, double rx, double ry, double x_axi path.moveTo(curx, cury); for (i = 0; i < n_segs; i++) { - pathArcSegment(path, xc, yc, - th0 + i * th_arc / n_segs, - th0 + (i + 1) * th_arc / n_segs, - rx, ry, x_axis_rotation); + pathArcSegment(path, xc, yc, th0 + i * th_arc / n_segs, th0 + (i + 1) * th_arc / n_segs, rx, + ry, x_axis_rotation); } } -void QGIViewPart::pathArcSegment(QPainterPath &path, - double xc, double yc, - double th0, double th1, - double rx, double ry, double xAxisRotation) +void QGIViewPart::pathArcSegment(QPainterPath& path, double xc, double yc, double th0, double th1, + double rx, double ry, double xAxisRotation) { double sinTh, cosTh; double a00, a01, a10, a11; @@ -1146,10 +1124,10 @@ void QGIViewPart::pathArcSegment(QPainterPath &path, sinTh = qSin(xAxisRotation); cosTh = qCos(xAxisRotation); - a00 = cosTh * rx; + a00 = cosTh * rx; a01 = -sinTh * ry; - a10 = sinTh * rx; - a11 = cosTh * ry; + a10 = sinTh * rx; + a11 = cosTh * ry; thHalf = 0.5 * (th1 - th0); t = (8.0 / 3.0) * qSin(thHalf * 0.5) * qSin(thHalf * 0.5) / qSin(thHalf); @@ -1160,15 +1138,14 @@ void QGIViewPart::pathArcSegment(QPainterPath &path, x2 = x3 + t * qSin(th1); y2 = y3 - t * qCos(th1); - path.cubicTo(a00 * x1 + a01 * y1, a10 * x1 + a11 * y1, - a00 * x2 + a01 * y2, a10 * x2 + a11 * y2, + path.cubicTo(a00 * x1 + a01 * y1, a10 * x1 + a11 * y1, a00 * x2 + a01 * y2, a10 * x2 + a11 * y2, a00 * x3 + a01 * y3, a10 * x3 + a11 * y3); } void QGIViewPart::toggleCache(bool state) { - QList items = childItems(); - for(QList::iterator it = items.begin(); it != items.end(); it++) { + QList items = childItems(); + for (QList::iterator it = items.begin(); it != items.end(); it++) { //(*it)->setCacheMode((state)? DeviceCoordinateCache : NoCache); //TODO: fiddle cache settings if req'd for performance Q_UNUSED(state); (*it)->setCacheMode(NoCache); @@ -1178,23 +1155,24 @@ void QGIViewPart::toggleCache(bool state) void QGIViewPart::toggleCosmeticLines(bool state) { - QList items = childItems(); - for(QList::iterator it = items.begin(); it != items.end(); it++) { - QGIEdge *edge = dynamic_cast(*it); - if(edge) { + QList items = childItems(); + for (QList::iterator it = items.begin(); it != items.end(); it++) { + QGIEdge* edge = dynamic_cast(*it); + if (edge) { edge->setCosmetic(state); } } } //get hatchObj for face i if it exists -TechDraw::DrawHatch* QGIViewPart::faceIsHatched(int i, std::vector hatchObjs) const +TechDraw::DrawHatch* QGIViewPart::faceIsHatched(int i, + std::vector hatchObjs) const { TechDraw::DrawHatch* result = nullptr; bool found = false; - for (auto& h:hatchObjs) { - const std::vector &sourceNames = h->Source.getSubValues(); - for (auto& s: sourceNames) { + for (auto& h : hatchObjs) { + const std::vector& sourceNames = h->Source.getSubValues(); + for (auto& s : sourceNames) { int fdx = TechDraw::DrawUtil::getIndexFromName(s); if (fdx == i) { result = h; @@ -1209,13 +1187,14 @@ TechDraw::DrawHatch* QGIViewPart::faceIsHatched(int i, std::vector geomObjs) const +TechDraw::DrawGeomHatch* +QGIViewPart::faceIsGeomHatched(int i, std::vector geomObjs) const { TechDraw::DrawGeomHatch* result = nullptr; bool found = false; - for (auto& h:geomObjs) { - const std::vector &sourceNames = h->Source.getSubValues(); - for (auto& sn: sourceNames) { + for (auto& h : geomObjs) { + const std::vector& sourceNames = h->Source.getSubValues(); + for (auto& sn : sourceNames) { int fdx = TechDraw::DrawUtil::getIndexFromName(sn); if (fdx == i) { result = h; @@ -1233,59 +1212,67 @@ TechDraw::DrawGeomHatch* QGIViewPart::faceIsGeomHatched(int i, std::vector>>%s has %d elements\n", text, path.elementCount()); - char* typeName; - for(int iElem = 0; iElem < path.elementCount(); iElem++) { - elem = path.elementAt(iElem); - if(elem.isMoveTo()) { - typeName = "MoveTo"; - } else if (elem.isLineTo()) { - typeName = "LineTo"; - } else if (elem.isCurveTo()) { - typeName = "CurveTo"; - } else { - typeName = "CurveData"; - } - Base::Console().Message(">>>>> element %d: type:%d/%s pos(%.3f, %.3f) M:%d L:%d C:%d\n", - iElem, elem.type, typeName, elem.x, elem.y, elem.isMoveTo(), elem.isLineTo(), - elem.isCurveTo()); + QPainterPath::Element elem; + Base::Console().Message(">>>%s has %d elements\n", text, path.elementCount()); + char* typeName; + for (int iElem = 0; iElem < path.elementCount(); iElem++) { + elem = path.elementAt(iElem); + if (elem.isMoveTo()) { + typeName = "MoveTo"; + } + else if (elem.isLineTo()) { + typeName = "LineTo"; + } + else if (elem.isCurveTo()) { + typeName = "CurveTo"; } + else { + typeName = "CurveData"; + } + Base::Console().Message(">>>>> element %d: type:%d/%s pos(%.3f, %.3f) M:%d L:%d C:%d\n", + iElem, elem.type, typeName, elem.x, elem.y, elem.isMoveTo(), + elem.isLineTo(), elem.isCurveTo()); + } } QRectF QGIViewPart::boundingRect() const { -// return childrenBoundingRect(); -// return customChildrenBoundingRect(); + // return childrenBoundingRect(); + // return customChildrenBoundingRect(); return QGIView::boundingRect(); } -void QGIViewPart::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) { +void QGIViewPart::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +{ QStyleOptionGraphicsItem myOption(*option); myOption.state &= ~QStyle::State_Selected; -// painter->drawRect(boundingRect()); //good for debugging + // painter->drawRect(boundingRect()); //good for debugging - QGIView::paint (painter, &myOption, widget); + QGIView::paint(painter, &myOption, widget); } //QGIViewPart derived classes do not need a rotate view method as rotation is handled on App side. -void QGIViewPart::rotateView() -{ -} +void QGIViewPart::rotateView() {} bool QGIViewPart::prefFaceEdges() { bool result = false; - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/General"); result = hGrp->GetBool("DrawFaceEdges", 0l); return result; } bool QGIViewPart::prefPrintCenters() { - Base::Reference hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> - GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); - bool printCenters = hGrp->GetBool("PrintCenterMarks", false); //true matches v0.18 behaviour + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/TechDraw/Decorations"); + bool printCenters = hGrp->GetBool("PrintCenterMarks", false);//true matches v0.18 behaviour return printCenters; } diff --git a/src/Mod/TechDraw/Gui/TaskComplexSection.cpp b/src/Mod/TechDraw/Gui/TaskComplexSection.cpp index 54031e0a0db6..ae9a5e83b0ac 100644 --- a/src/Mod/TechDraw/Gui/TaskComplexSection.cpp +++ b/src/Mod/TechDraw/Gui/TaskComplexSection.cpp @@ -22,9 +22,9 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -#endif // #ifndef _PreComp_ +#include +#include +#endif// #ifndef _PreComp_ #include #include @@ -37,26 +37,26 @@ #include #include +#include "Widgets/CompassWidget.h" +#include "Widgets/VectorEditWidget.h" #include #include #include #include #include -#include "Widgets/CompassWidget.h" -#include "Widgets/VectorEditWidget.h" +#include "DrawGuiUtil.h" #include "TaskComplexSection.h" #include "ui_TaskComplexSection.h" -#include "DrawGuiUtil.h" using namespace Gui; using namespace TechDraw; using namespace TechDrawGui; +using DU = DrawUtil; //ctor for creation -TaskComplexSection::TaskComplexSection(TechDraw::DrawPage* page, - TechDraw::DrawViewPart* baseView, +TaskComplexSection::TaskComplexSection(TechDraw::DrawPage* page, TechDraw::DrawViewPart* baseView, std::vector shapes, std::vector xShapes, App::DocumentObject* profileObject, @@ -73,7 +73,8 @@ TaskComplexSection::TaskComplexSection(TechDraw::DrawPage* page, m_createMode(true), m_applyDeferred(0), m_angle(0.0), - m_directionIsSet(false) + m_directionIsSet(false), + m_modelIsDirty(false) { m_sectionName = std::string(); if (m_page) { @@ -88,8 +89,8 @@ TaskComplexSection::TaskComplexSection(TechDraw::DrawPage* page, saveSectionState(); setUiPrimary(); - m_applyDeferred = 0; //setting the direction widgets causes an increment of the deferred count, - //so we reset the counter and the message. + m_applyDeferred = 0;//setting the direction widgets causes an increment of the deferred count, + //so we reset the counter and the message. } //ctor for edit @@ -103,14 +104,15 @@ TaskComplexSection::TaskComplexSection(TechDraw::DrawComplexSection* complexSect m_createMode(false), m_applyDeferred(0), m_angle(0.0), - m_directionIsSet(true) + m_directionIsSet(true), + m_modelIsDirty(false) { m_sectionName = m_section->getNameInDocument(); - m_doc = m_section->getDocument(); - m_page = m_section->findParentPage(); + m_doc = m_section->getDocument(); + m_page = m_section->findParentPage(); m_savePageName = m_page->getNameInDocument(); - m_baseView = dynamic_cast (m_section->BaseView.getValue()); + m_baseView = dynamic_cast(m_section->BaseView.getValue()); if (m_baseView) { m_saveBaseName = m_baseView->getNameInDocument(); } @@ -124,8 +126,8 @@ TaskComplexSection::TaskComplexSection(TechDraw::DrawComplexSection* complexSect saveSectionState(); setUiEdit(); - m_applyDeferred = 0; //setting the direction widgets causes an increment of the deferred count, - //so we reset the counter and the message. + m_applyDeferred = 0;//setting the direction widgets causes an increment of the deferred count, + //so we reset the counter and the message. ui->lPendingUpdates->setText(QString()); } @@ -135,7 +137,8 @@ void TaskComplexSection::setUiPrimary() if (m_baseView) { ui->sbScale->setValue(m_baseView->getScale()); ui->cmbScaleType->setCurrentIndex(m_baseView->ScaleType.getValue()); - } else { + } + else { ui->sbScale->setValue(Preferences::scale()); ui->cmbScaleType->setCurrentIndex(Preferences::scaleType()); } @@ -149,24 +152,25 @@ void TaskComplexSection::setUiPrimary() //one is picked in the dialog Base::Vector3d defaultNormal(-1.0, 0.0, 0.0); m_saveNormal = defaultNormal; - m_localUnit = defaultNormal; m_saveXDir = Base::Vector3d(0.0, 1.0, 0.0); ui->leBaseView->setText(Base::Tools::fromStdString(m_baseView->getNameInDocument())); - m_viewDirectionWidget->setValue(Base::Vector3d(0.0, 0.0, 0.0)); - } else { + m_compass->setDialAngle(0.0); + m_viewDirectionWidget->setValueNoNotify(Base::Vector3d(1.0, 0.0, 0.0)); + } + else { //if there is no baseView, we use the 3d view to determine the SectionNormal //and XDirection. std::pair dirs = DrawGuiUtil::get3DDirAndRot(); m_saveNormal = dirs.first; - m_localUnit = dirs.first; m_saveXDir = dirs.second; - m_viewDirectionWidget->setValue(m_saveNormal * -1.0); //this will propagate to m_compass + m_viewDirectionWidget->setValue(m_saveNormal * -1.0);//this will propagate to m_compass } //don't allow updates until a direction is picked ui->pbUpdateNow->setEnabled(false); ui->cbLiveUpdate->setEnabled(false); - QString msgLiteral = QString::fromUtf8(QT_TRANSLATE_NOOP("TaskComplexSection", "No direction set")); + QString msgLiteral = + QString::fromUtf8(QT_TRANSLATE_NOOP("TaskComplexSection", "No direction set")); ui->lPendingUpdates->setText(msgLiteral); } @@ -188,11 +192,11 @@ void TaskComplexSection::setUiEdit() if (m_baseView) { ui->leBaseView->setText(Base::Tools::fromStdString(m_baseView->getNameInDocument())); Base::Vector3d projectedViewDirection = m_baseView->projectPoint(sectionNormalVec, false); - double viewAngle = atan2(-projectedViewDirection.y, - -projectedViewDirection.x); + double viewAngle = atan2(-projectedViewDirection.y, -projectedViewDirection.x); m_compass->setDialAngle(viewAngle * 180.0 / M_PI); - m_viewDirectionWidget->setValue(projectedViewDirection * -1.0); - } else { + m_viewDirectionWidget->setValueNoNotify(projectedViewDirection * -1.0); + } + else { //no local angle makes sense if there is no baseView? m_viewDirectionWidget->setValue(sectionNormalVec * -1.0); } @@ -201,9 +205,9 @@ void TaskComplexSection::setUiEdit() void TaskComplexSection::setUiCommon() { ui->leSectionObjects->setText(sourcesToString()); - ui->leProfileObject->setText(Base::Tools::fromStdString(m_profileObject->getNameInDocument()) + - QString::fromUtf8(" / ") + - Base::Tools::fromStdString(m_profileObject->Label.getValue())); + ui->leProfileObject->setText(Base::Tools::fromStdString(m_profileObject->getNameInDocument()) + + QString::fromUtf8(" / ") + + Base::Tools::fromStdString(m_profileObject->Label.getValue())); m_compass = new CompassWidget(this); auto layout = ui->compassLayout; @@ -211,9 +215,11 @@ void TaskComplexSection::setUiCommon() m_viewDirectionWidget = new VectorEditWidget(this); m_viewDirectionWidget->setLabel(QObject::tr("Current View Direction")); + m_viewDirectionWidget->setToolTip(QObject::tr("The view direction in BaseView coordinates")); auto editLayout = ui->viewDirectionLayout; editLayout->addWidget(m_viewDirectionWidget); + connect(m_compass, SIGNAL(angleChanged(double)), this, SLOT(slotChangeAngle(double))); connect(ui->pbUp, SIGNAL(clicked(bool)), this, SLOT(onUpClicked())); @@ -224,28 +230,29 @@ void TaskComplexSection::setUiCommon() connect(ui->pbUpdateNow, SIGNAL(clicked(bool)), this, SLOT(updateNowClicked())); connect(ui->cbLiveUpdate, SIGNAL(clicked(bool)), this, SLOT(liveUpdateClicked())); - connect(ui->pbSectionObjects, SIGNAL(clicked()), this, SLOT(onSectionObjectsUseSelectionClicked())); - connect(ui->pbProfileObject, SIGNAL(clicked()), this, SLOT(onProfileObjectsUseSelectionClicked())); + connect(ui->pbSectionObjects, SIGNAL(clicked()), this, + SLOT(onSectionObjectsUseSelectionClicked())); + connect(ui->pbProfileObject, SIGNAL(clicked()), this, + SLOT(onProfileObjectsUseSelectionClicked())); connect(m_compass, SIGNAL(angleChanged(double)), this, SLOT(slotChangeAngle(double))); - connect(m_viewDirectionWidget, SIGNAL(valueChanged(Base::Vector3d)), - this, SLOT(slotViewDirectionChanged(Base::Vector3d))); + connect(m_viewDirectionWidget, SIGNAL(valueChanged(Base::Vector3d)), this, + SLOT(slotViewDirectionChanged(Base::Vector3d))); } //save the start conditions void TaskComplexSection::saveSectionState() { -// Base::Console().Message("TCS::saveSectionState()\n"); + // Base::Console().Message("TCS::saveSectionState()\n"); if (m_section) { m_saveSymbol = m_section->SectionSymbol.getValue(); - m_saveScale = m_section->getScale(); + m_saveScale = m_section->getScale(); m_saveScaleType = m_section->ScaleType.getValue(); m_saveNormal = m_section->SectionNormal.getValue(); m_saveDirection = m_section->Direction.getValue(); - m_localUnit = m_saveNormal; m_saveXDir = m_section->XDirection.getValue(); - m_saveOrigin = m_section->SectionOrigin.getValue(); - m_saveDirName = m_section->SectionDirection.getValueAsString(); + m_saveOrigin = m_section->SectionOrigin.getValue(); + m_saveDirName = m_section->SectionDirection.getValueAsString(); m_saved = true; } if (m_baseView) { @@ -257,7 +264,7 @@ void TaskComplexSection::saveSectionState() //restore the start conditions void TaskComplexSection::restoreSectionState() { -// Base::Console().Message("TCS::restoreSectionState()\n"); + // Base::Console().Message("TCS::restoreSectionState()\n"); if (!m_section) return; @@ -277,11 +284,12 @@ void TaskComplexSection::onSectionObjectsUseSelectionClicked() std::vector newSelection; std::vector newXSelection; for (auto& sel : selection) { - if (sel.getObject()->isDerivedFrom(App::LinkElement::getClassTypeId()) || - sel.getObject()->isDerivedFrom(App::LinkGroup::getClassTypeId()) || - sel.getObject()->isDerivedFrom(App::Link::getClassTypeId()) ) { + if (sel.getObject()->isDerivedFrom(App::LinkElement::getClassTypeId()) + || sel.getObject()->isDerivedFrom(App::LinkGroup::getClassTypeId()) + || sel.getObject()->isDerivedFrom(App::Link::getClassTypeId())) { newXSelection.push_back(sel.getObject()); - } else { + } + else { newSelection.push_back(sel.getObject()); } } @@ -293,68 +301,67 @@ void TaskComplexSection::onSectionObjectsUseSelectionClicked() //the VectorEditWidget reports a change in direction void TaskComplexSection::slotViewDirectionChanged(Base::Vector3d newDirection) { -// Base::Console().Message("TCS::slotViewDirectionChanged(%s)\n", -// DrawUtil::formatVector(newDirection).c_str()); + // Base::Console().Message("TCS::slotViewDirectionChanged(%s)\n", + // DrawUtil::formatVector(newDirection).c_str()); Base::Vector3d projectedViewDirection = newDirection; if (m_baseView) { projectedViewDirection = m_baseView->projectPoint(newDirection, false); } projectedViewDirection.Normalize(); - double viewAngle = atan2(projectedViewDirection.y, - projectedViewDirection.x); + double viewAngle = atan2(projectedViewDirection.y, projectedViewDirection.x); m_compass->setDialAngle(viewAngle * 180.0 / M_PI); checkAll(false); - applyAligned(projectedViewDirection); + applyAligned(); } //the CompassWidget reports the view direction. This is the reverse of the //SectionNormal void TaskComplexSection::slotChangeAngle(double newAngle) { -// Base::Console().Message("TCS::slotAngleChanged(%.3f)\n", newAngle); + // Base::Console().Message("TCS::slotAngleChanged(%.3f)\n", newAngle); double angleRadians = newAngle * M_PI / 180.0; double unitX = cos(angleRadians); double unitY = sin(angleRadians); Base::Vector3d localUnit(unitX, unitY, 0.0); - m_viewDirectionWidget->setValue(localUnit); + m_viewDirectionWidget->setValueNoNotify(localUnit); checkAll(false); - applyAligned(localUnit); + applyAligned(); } void TaskComplexSection::onUpClicked() { -// Base::Console().Message("TCS::onUpClicked()\n"); + // Base::Console().Message("TCS::onUpClicked()\n"); checkAll(false); m_compass->setToNorth(); m_viewDirectionWidget->setValueNoNotify(Base::Vector3d(0.0, 1.0, 0.0)); - applyAligned(Base::Vector3d(0.0, 1.0, 0.0)); + applyAligned(); } void TaskComplexSection::onDownClicked() { -// Base::Console().Message("TCS::onDownClicked()\n"); + // Base::Console().Message("TCS::onDownClicked()\n"); checkAll(false); m_compass->setToSouth(); m_viewDirectionWidget->setValueNoNotify(Base::Vector3d(0.0, -1.0, 0.0)); - applyAligned(Base::Vector3d(0.0, -1.0, 0.0)); + applyAligned(); } void TaskComplexSection::onLeftClicked() { -// Base::Console().Message("TCS::onLeftClicked()\n"); + // Base::Console().Message("TCS::onLeftClicked()\n"); checkAll(false); m_compass->setToWest(); m_viewDirectionWidget->setValueNoNotify(Base::Vector3d(-1.0, 0.0, 0.0)); - applyAligned(Base::Vector3d(-1.0, 0.0, 0.0)); + applyAligned(); } void TaskComplexSection::onRightClicked() { -// Base::Console().Message("TCS::onRightClicked()\n"); + // Base::Console().Message("TCS::onRightClicked()\n"); checkAll(false); m_compass->setToEast(); m_viewDirectionWidget->setValueNoNotify(Base::Vector3d(1.0, 0.0, 0.0)); - applyAligned(Base::Vector3d(1.0, 0.0, 0.0)); + applyAligned(); } void TaskComplexSection::onIdentifierChanged() @@ -375,9 +382,10 @@ void TaskComplexSection::onProfileObjectsUseSelectionClicked() //check for single selection and ability to make profile from selected object if (!selection.empty()) { m_profileObject = selection.front().getObject(); - ui->leProfileObject->setText(Base::Tools::fromStdString(m_profileObject->getNameInDocument()) + - QString::fromUtf8(" / ") + - Base::Tools::fromStdString(m_profileObject->Label.getValue())); + ui->leProfileObject->setText( + Base::Tools::fromStdString(m_profileObject->getNameInDocument()) + + QString::fromUtf8(" / ") + + Base::Tools::fromStdString(m_profileObject->Label.getValue())); } } void TaskComplexSection::scaleTypeChanged(int index) @@ -389,21 +397,25 @@ void TaskComplexSection::scaleTypeChanged(int index) ui->sbScale->setValue(m_baseView->findParentPage()->Scale.getValue()); ui->sbScale->setEnabled(false); } - } else if (index == 1) { + } + else if (index == 1) { // Automatic Scale Type ui->sbScale->setEnabled(false); if (m_section) { ui->sbScale->setValue(m_section->autoScale()); } - } else if (index == 2) { + } + else if (index == 2) { // Custom Scale Type ui->sbScale->setEnabled(true); if (m_section) { ui->sbScale->setValue(m_section->Scale.getValue()); ui->sbScale->setEnabled(true); } - } else { - Base::Console().Log("Error - TaskComplexSection::scaleTypeChanged - unknown scale type: %d\n", index); + } + else { + Base::Console().Log( + "Error - TaskComplexSection::scaleTypeChanged - unknown scale type: %d\n", index); return; } } @@ -423,22 +435,17 @@ void TaskComplexSection::enableAll(bool enable) ui->cmbScaleType->setEnabled(enable); QString qScaleType = ui->cmbScaleType->currentText(); //Allow or prevent scale changing initially - if (qScaleType == QString::fromUtf8("Custom")) { + if (qScaleType == QString::fromUtf8("Custom")) { ui->sbScale->setEnabled(true); } else { ui->sbScale->setEnabled(false); } - } -void TaskComplexSection::liveUpdateClicked() { - apply(true); -} +void TaskComplexSection::liveUpdateClicked() { apply(true); } -void TaskComplexSection::updateNowClicked() { - apply(true); -} +void TaskComplexSection::updateNowClicked() { apply(true); } QString TaskComplexSection::sourcesToString() { @@ -447,32 +454,25 @@ QString TaskComplexSection::sourcesToString() QString currentSeparator; if (m_baseView) { for (auto& obj : m_baseView->Source.getValues()) { - result += currentSeparator + - Base::Tools::fromStdString(obj->getNameInDocument()) + - QString::fromUtf8(" / ") + - Base::Tools::fromStdString(obj->Label.getValue()); + result += currentSeparator + Base::Tools::fromStdString(obj->getNameInDocument()) + + QString::fromUtf8(" / ") + Base::Tools::fromStdString(obj->Label.getValue()); currentSeparator = separator; } currentSeparator = QString(); for (auto& obj : m_baseView->XSource.getValues()) { - result += currentSeparator + - Base::Tools::fromStdString(obj->getNameInDocument()) + - QString::fromUtf8(" / ") + - Base::Tools::fromStdString(obj->Label.getValue()); + result += currentSeparator + Base::Tools::fromStdString(obj->getNameInDocument()) + + QString::fromUtf8(" / ") + Base::Tools::fromStdString(obj->Label.getValue()); } - } else { + } + else { for (auto& obj : m_shapes) { - result += currentSeparator + - Base::Tools::fromStdString(obj->getNameInDocument()) + - QString::fromUtf8(" / ") + - Base::Tools::fromStdString(obj->Label.getValue()); + result += currentSeparator + Base::Tools::fromStdString(obj->getNameInDocument()) + + QString::fromUtf8(" / ") + Base::Tools::fromStdString(obj->Label.getValue()); } currentSeparator = QString(); for (auto& obj : m_xShapes) { - result += currentSeparator + - Base::Tools::fromStdString(obj->getNameInDocument()) + - QString::fromUtf8(" / ") + - Base::Tools::fromStdString(obj->Label.getValue()); + result += currentSeparator + Base::Tools::fromStdString(obj->getNameInDocument()) + + QString::fromUtf8(" / ") + Base::Tools::fromStdString(obj->Label.getValue()); } } return result; @@ -481,39 +481,49 @@ QString TaskComplexSection::sourcesToString() //****************************************************************************** bool TaskComplexSection::apply(bool forceUpdate) { -// Base::Console().Message("TCS::apply() - liveUpdate: %d forece: %d\n", -// ui->cbLiveUpdate->isChecked(), forceUpdate); - if(!ui->cbLiveUpdate->isChecked() && - !forceUpdate) { + // Base::Console().Message("TCS::apply() - liveUpdate: %d force: %d\n", + // ui->cbLiveUpdate->isChecked(), forceUpdate); + if (!ui->cbLiveUpdate->isChecked() && !forceUpdate) { //nothing to do m_applyDeferred++; - QString msgLiteral = QString::fromUtf8(QT_TRANSLATE_NOOP("TaskPojGroup", " updates pending")); + QString msgLiteral = + QString::fromUtf8(QT_TRANSLATE_NOOP("TaskPojGroup", " updates pending")); QString msgNumber = QString::number(m_applyDeferred); ui->lPendingUpdates->setText(msgNumber + msgLiteral); return false; } + + Base::Vector3d localUnit = m_viewDirectionWidget->value(); if (m_baseView) { - if (!DrawComplexSection::canBuild(m_baseView->localVectorToCS(m_localUnit), m_profileObject)) { - Base::Console().Error("Can not build Complex Section with this profile and direction\n"); + if (!DrawComplexSection::canBuild(m_baseView->localVectorToCS(localUnit), + m_profileObject)) { + Base::Console().Error( + "Can not build Complex Section with this profile and direction (1)\n"); return false; } - } else { + } + else { gp_Pnt stdOrigin(0.0, 0.0, 0.0); - gp_Ax2 sectionCS(stdOrigin, DrawUtil::togp_Dir(m_saveNormal), DrawUtil::togp_Dir(m_saveXDir)); + gp_Ax2 sectionCS(stdOrigin, DrawUtil::togp_Dir(m_saveNormal), + DrawUtil::togp_Dir(m_saveXDir)); if (!DrawComplexSection::canBuild(sectionCS, m_profileObject)) { - Base::Console().Error("Can not build Complex Section with this profile and direction\n"); + Base::Console().Error( + "Can not build Complex Section with this profile and direction (2)\n"); return false; } } Gui::WaitCursor wc; + m_modelIsDirty = true; + if (!m_section) { createComplexSection(); } if (isSectionValid()) { updateComplexSection(); - } else { + } + else { failNoObject(); } @@ -531,12 +541,10 @@ bool TaskComplexSection::apply(bool forceUpdate) return true; } -void TaskComplexSection::applyAligned(Base::Vector3d localUnit) +void TaskComplexSection::applyAligned() { -// Base::Console().Message("TCS::applyAligned(%s)\n", -// DrawUtil::formatVector(localUnit).c_str()); + // Base::Console().Message("TCS::applyAligned()\n"); m_dirName = "Aligned"; - m_localUnit = localUnit; enableAll(true); m_directionIsSet = true; ui->pbUpdateNow->setEnabled(true); @@ -549,7 +557,7 @@ void TaskComplexSection::applyAligned(Base::Vector3d localUnit) //pointer to created view is not returned, but stored in m_section void TaskComplexSection::createComplexSection() { -// Base::Console().Message("TCS::createComplexSection()\n"); + // Base::Console().Message("TCS::createComplexSection()\n"); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Create ComplexSection")); if (!m_section) { @@ -561,22 +569,16 @@ void TaskComplexSection::createComplexSection() Command::doCommand(Command::Doc, "App.ActiveDocument.%s.addView(App.ActiveDocument.%s)", m_page->getNameInDocument(), m_sectionName.c_str()); - QString qTemp = ui->leSymbol->text(); + QString qTemp = ui->leSymbol->text(); std::string temp = Base::Tools::toStdString(qTemp); Command::doCommand(Command::Doc, "App.ActiveDocument.%s.SectionSymbol = '%s'", - m_sectionName.c_str(), - temp.c_str()); - std::string lblText = "Section " + - temp + - " - " + - temp; + m_sectionName.c_str(), temp.c_str()); + std::string lblText = "Section " + temp + " - " + temp; Command::doCommand(Command::Doc, "App.ActiveDocument.%s.Label = '%s'", - m_sectionName.c_str(), - lblText.c_str()); + m_sectionName.c_str(), lblText.c_str()); Command::doCommand(Command::Doc, "App.ActiveDocument.%s.Scale = %0.6f", - m_sectionName.c_str(), - ui->sbScale->value()); + m_sectionName.c_str(), ui->sbScale->value()); int scaleType = ui->cmbScaleType->currentIndex(); Command::doCommand(Command::Doc, "App.ActiveDocument.%s.ScaleType = %d", m_sectionName.c_str(), scaleType); @@ -584,31 +586,36 @@ void TaskComplexSection::createComplexSection() Command::doCommand(Command::Doc, "App.ActiveDocument.%s.ProjectionStrategy = %d", m_sectionName.c_str(), projectionStrategy); - Command::doCommand(Command::Doc, "App.activeDocument().%s.SectionOrigin = FreeCAD.Vector(0.0, 0.0, 0.0)", - m_sectionName.c_str()); + Command::doCommand(Command::Doc, + "App.activeDocument().%s.SectionOrigin = FreeCAD.Vector(0.0, 0.0, 0.0)", + m_sectionName.c_str()); Command::doCommand(Command::Doc, "App.activeDocument().%s.SectionDirection = 'Aligned'", - m_sectionName.c_str()); + m_sectionName.c_str()); App::DocumentObject* newObj = m_page->getDocument()->getObject(m_sectionName.c_str()); m_section = dynamic_cast(newObj); - if (!newObj || !m_section) { + if (!newObj || !m_section) { throw Base::RuntimeError("TaskComplexSection - new section object not found"); } + Base::Vector3d localUnit = m_viewDirectionWidget->value(); if (m_baseView) { - Command::doCommand(Command::Doc, "App.ActiveDocument.%s.BaseView = App.ActiveDocument.%s", + Command::doCommand(Command::Doc, + "App.ActiveDocument.%s.BaseView = App.ActiveDocument.%s", m_sectionName.c_str(), m_baseView->getNameInDocument()); - m_section->setCSFromBase(m_localUnit * -1.0); + m_section->setCSFromBase(localUnit * -1.0); m_section->Source.setValues(m_baseView->Source.getValues()); m_section->XSource.setValues(m_baseView->XSource.getValues()); - } else { - //if we have not changed the direction, we should use the 3d directions saved in the - //constructor - if (m_localUnit.IsEqual(m_saveNormal, EWTOLERANCE)) { + } + else { + if (m_directionIsSet) { + //if we have changed the direction, use the local unit to create a CS + m_section->setCSFromLocalUnit(localUnit * -1.0); + } + else { + //if we have not changed the direction, we should use the 3d directions saved in the + //constructor m_section->SectionNormal.setValue(m_saveNormal); m_section->XDirection.setValue(m_saveXDir); - } else { - //if we have changed the direction, use the local unit to create a CS - m_section->setCSFromLocalUnit(m_localUnit * -1.0); } m_section->Source.setValues(m_shapes); m_section->XSource.setValues(m_xShapes); @@ -617,13 +624,19 @@ void TaskComplexSection::createComplexSection() m_section->SectionDirection.setValue("Aligned"); m_section->Source.setValues(m_shapes); m_section->XSource.setValues(m_xShapes); + + //auto orientation of view relative to base view + double viewDirectionAngle = m_compass->positiveValue(); + double rotation = requiredRotation(viewDirectionAngle); + Command::doCommand(Command::Doc, "App.ActiveDocument.%s.Rotation = %.6f", + m_sectionName.c_str(), rotation); } Gui::Command::commitCommand(); } void TaskComplexSection::updateComplexSection() { -// Base::Console().Message("TCS:;updateComplexSection()\n"); + // Base::Console().Message("TCS:;updateComplexSection()\n"); if (!isSectionValid()) { failNoObject(); return; @@ -631,22 +644,16 @@ void TaskComplexSection::updateComplexSection() Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Edit SectionView")); if (m_section) { - QString qTemp = ui->leSymbol->text(); + QString qTemp = ui->leSymbol->text(); std::string temp = Base::Tools::toStdString(qTemp); Command::doCommand(Command::Doc, "App.ActiveDocument.%s.SectionSymbol = '%s'", - m_sectionName.c_str(), - temp.c_str()); - std::string lblText = "Section " + - temp + - " - " + - temp; + m_sectionName.c_str(), temp.c_str()); + std::string lblText = "Section " + temp + " - " + temp; Command::doCommand(Command::Doc, "App.ActiveDocument.%s.Label = '%s'", - m_sectionName.c_str(), - lblText.c_str()); + m_sectionName.c_str(), lblText.c_str()); Command::doCommand(Command::Doc, "App.ActiveDocument.%s.Scale = %0.6f", - m_sectionName.c_str(), - ui->sbScale->value()); + m_sectionName.c_str(), ui->sbScale->value()); int scaleType = ui->cmbScaleType->currentIndex(); Command::doCommand(Command::Doc, "App.ActiveDocument.%s.ScaleType = %d", m_sectionName.c_str(), scaleType); @@ -654,18 +661,26 @@ void TaskComplexSection::updateComplexSection() Command::doCommand(Command::Doc, "App.ActiveDocument.%s.ProjectionStrategy = %d", m_sectionName.c_str(), projectionStrategy); Command::doCommand(Command::Doc, "App.activeDocument().%s.SectionDirection = 'Aligned'", - m_sectionName.c_str()); + m_sectionName.c_str()); m_section->CuttingToolWireObject.setValue(m_profileObject); m_section->SectionDirection.setValue("Aligned"); - m_section->setCSFromBase(m_localUnit * -1.0); + Base::Vector3d localUnit = m_viewDirectionWidget->value(); + m_section->setCSFromBase(localUnit * -1.0); if (m_baseView) { m_section->Source.setValues(m_baseView->Source.getValues()); m_section->XSource.setValues(m_baseView->XSource.getValues()); - } else { + } + else { //without a baseView, our choice of SectionNormal and XDirection may well be wrong m_section->Source.setValues(m_shapes); m_section->XSource.setValues(m_xShapes); } + + //auto orientation of view relative to base view + double viewDirectionAngle = m_compass->positiveValue(); + double rotation = requiredRotation(viewDirectionAngle); + Command::doCommand(Command::Doc, "App.ActiveDocument.%s.Rotation = %.6f", + m_sectionName.c_str(), rotation); } Gui::Command::commitCommand(); } @@ -702,23 +717,37 @@ bool TaskComplexSection::isSectionValid() return true; } + +//get required rotation from input angle in [0, 360] +//NOTE: shared code with simple section - reuse opportunity +double TaskComplexSection::requiredRotation(double inputAngle) +{ + double rotation = inputAngle - 90.0; + if (rotation == 180.0) { + //if the view direction is 90/270, then the section is drawn properly and no + //rotation is needed. 90.0 becomes 0.0, but 270.0 needs special handling. + rotation = 0.0; + } + return rotation; +} + //****************************************************************************** bool TaskComplexSection::accept() { -// Base::Console().Message("TCS::accept()\n"); + // Base::Console().Message("TCS::accept()\n"); apply(true); - Gui::Command::doCommand(Gui::Command::Gui,"Gui.ActiveDocument.resetEdit()"); + Gui::Command::doCommand(Gui::Command::Gui, "Gui.ActiveDocument.resetEdit()"); return true; } bool TaskComplexSection::reject() { - if (!m_section) { //no section created, nothing to undo + if (!m_section) {//no section created, nothing to undo Gui::Command::doCommand(Gui::Command::Gui, "Gui.ActiveDocument.resetEdit()"); return false; } - if (!isSectionValid()) { //section !exist. nothing to undo + if (!isSectionValid()) {//section !exist. nothing to undo if (isBaseValid()) { m_baseView->requestPaint(); } @@ -731,13 +760,14 @@ bool TaskComplexSection::reject() Gui::Command::doCommand(Gui::Command::Gui, "App.ActiveDocument.%s.removeView(App.ActiveDocument.%s)", m_savePageName.c_str(), SectionName.c_str()); - Gui::Command::doCommand(Gui::Command::Gui, - "App.ActiveDocument.removeObject('%s')", + Gui::Command::doCommand(Gui::Command::Gui, "App.ActiveDocument.removeObject('%s')", SectionName.c_str()); } else { - restoreSectionState(); - m_section->recomputeFeature(); - m_section->requestPaint(); + if (m_modelIsDirty) { + restoreSectionState(); + m_section->recomputeFeature(); + m_section->requestPaint(); + } } if (isBaseValid()) { @@ -758,16 +788,17 @@ void TaskComplexSection::changeEvent(QEvent* event) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TaskDlgComplexSection::TaskDlgComplexSection(TechDraw::DrawPage* page, - TechDraw::DrawViewPart *baseView, + TechDraw::DrawViewPart* baseView, std::vector shapes, std::vector xShapes, App::DocumentObject* profileObject, std::vector profileSubs) : TaskDialog() { - widget = new TaskComplexSection(page, baseView, shapes, xShapes, profileObject, profileSubs); - taskbox = new Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("actions/TechDraw_ComplexSection"), - widget->windowTitle(), true, nullptr); + widget = new TaskComplexSection(page, baseView, shapes, xShapes, profileObject, profileSubs); + taskbox = + new Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("actions/TechDraw_ComplexSection"), + widget->windowTitle(), true, nullptr); taskbox->groupLayout()->addWidget(widget); Content.push_back(taskbox); } @@ -775,26 +806,23 @@ TaskDlgComplexSection::TaskDlgComplexSection(TechDraw::DrawPage* page, TaskDlgComplexSection::TaskDlgComplexSection(TechDraw::DrawComplexSection* complexSection) : TaskDialog() { - widget = new TaskComplexSection(complexSection); - taskbox = new Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("actions/TechDraw_ComplexSection"), - widget->windowTitle(), true, nullptr); + widget = new TaskComplexSection(complexSection); + taskbox = + new Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("actions/TechDraw_ComplexSection"), + widget->windowTitle(), true, nullptr); taskbox->groupLayout()->addWidget(widget); Content.push_back(taskbox); } -TaskDlgComplexSection::~TaskDlgComplexSection() -{ -} +TaskDlgComplexSection::~TaskDlgComplexSection() {} void TaskDlgComplexSection::update() { -// widget->updateTask(); + // widget->updateTask(); } //==== calls from the TaskView =============================================================== -void TaskDlgComplexSection::open() -{ -} +void TaskDlgComplexSection::open() {} bool TaskDlgComplexSection::accept() { diff --git a/src/Mod/TechDraw/Gui/TaskComplexSection.h b/src/Mod/TechDraw/Gui/TaskComplexSection.h index ae667bb81c3e..a6f249807213 100644 --- a/src/Mod/TechDraw/Gui/TaskComplexSection.h +++ b/src/Mod/TechDraw/Gui/TaskComplexSection.h @@ -75,7 +75,7 @@ class TaskComplexSection : public QWidget bool apply(bool forceUpdate = false); void applyQuick(std::string dir); - void applyAligned(Base::Vector3d localUnit); + void applyAligned(); void setUiPrimary(); void setUiEdit(); @@ -106,6 +106,8 @@ protected Q_SLOTS: void slotViewDirectionChanged(Base::Vector3d newDirection); private: + double requiredRotation(double inputAngle); + void createComplexSection(); void updateComplexSection(); @@ -137,11 +139,11 @@ protected Q_SLOTS: Base::Vector3d m_normal; int m_applyDeferred; - Base::Vector3d m_localUnit; CompassWidget* m_compass; double m_angle; VectorEditWidget* m_viewDirectionWidget; bool m_directionIsSet; + bool m_modelIsDirty; }; diff --git a/src/Mod/TechDraw/Gui/TaskSectionView.cpp b/src/Mod/TechDraw/Gui/TaskSectionView.cpp index ad9253eef659..6ff82a4cc18e 100644 --- a/src/Mod/TechDraw/Gui/TaskSectionView.cpp +++ b/src/Mod/TechDraw/Gui/TaskSectionView.cpp @@ -22,10 +22,12 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -#endif // #ifndef _PreComp_ +#include +#include +#endif// #ifndef _PreComp_ +#include "Widgets/CompassWidget.h" +#include "Widgets/VectorEditWidget.h" #include #include #include @@ -40,11 +42,11 @@ #include #include #include -#include "Widgets/CompassWidget.h" -#include "Widgets/VectorEditWidget.h" +// clang-format off #include "ui_TaskSectionView.h" #include "TaskSectionView.h" +// clang-format on using namespace Gui; @@ -62,12 +64,13 @@ TaskSectionView::TaskSectionView(TechDraw::DrawViewPart* base) : m_createMode(true), m_saved(false), m_applyDeferred(0), - m_directionIsSet(false) + m_directionIsSet(false), + m_modelIsDirty(false) { //existence of base is guaranteed by CmdTechDrawSectionView (Command.cpp) m_sectionName = std::string(); - m_doc = m_base->getDocument(); + m_doc = m_base->getDocument(); m_saveBaseName = m_base->getNameInDocument(); m_savePageName = m_base->findParentPage()->getNameInDocument(); @@ -75,8 +78,8 @@ TaskSectionView::TaskSectionView(TechDraw::DrawViewPart* base) : ui->setupUi(this); setUiPrimary(); - m_applyDeferred = 0; //setting the direction widgets causes an increment of the deferred count, - //so we reset the counter and the message. + m_applyDeferred = 0;//setting the direction widgets causes an increment of the deferred count, + //so we reset the counter and the message. } //ctor for edit @@ -89,7 +92,8 @@ TaskSectionView::TaskSectionView(TechDraw::DrawViewSection* section) : m_createMode(false), m_saved(false), m_applyDeferred(0), - m_directionIsSet(true) + m_directionIsSet(true), + m_modelIsDirty(false) { //existence of section is guaranteed by ViewProviderViewSection.setEdit @@ -110,21 +114,21 @@ TaskSectionView::TaskSectionView(TechDraw::DrawViewSection* section) : saveSectionState(); setUiEdit(); - m_applyDeferred = 0; //setting the direction widgets causes an increment of the deferred count, - //so we reset the counter and the message. + m_applyDeferred = 0;//setting the direction widgets causes an increment of the deferred count, + //so we reset the counter and the message. ui->lPendingUpdates->setText(QString()); } void TaskSectionView::setUiPrimary() { -// Base::Console().Message("TSV::setUiPrimary()\n"); + // Base::Console().Message("TSV::setUiPrimary()\n"); setWindowTitle(QObject::tr("Create Section View")); ui->sbScale->setValue(m_base->getScale()); ui->cmbScaleType->setCurrentIndex(m_base->ScaleType.getValue()); //Allow or prevent scale changing initially - if (m_base->ScaleType.isValue("Custom")) { + if (m_base->ScaleType.isValue("Custom")) { ui->sbScale->setEnabled(true); } else { @@ -134,18 +138,20 @@ void TaskSectionView::setUiPrimary() Base::Vector3d origin = m_base->getOriginalCentroid(); setUiCommon(origin); - m_viewDirectionWidget->setValue(Base::Vector3d(1.0, 0.0, 0.0)); + m_compass->setDialAngle(0.0); + m_viewDirectionWidget->setValueNoNotify(Base::Vector3d(1.0, 0.0, 0.0)); //don't allow updates until a direction is picked ui->pbUpdateNow->setEnabled(false); ui->cbLiveUpdate->setEnabled(false); - QString msgLiteral = QString::fromUtf8(QT_TRANSLATE_NOOP("TaskSectionView", "No direction set")); + QString msgLiteral = + QString::fromUtf8(QT_TRANSLATE_NOOP("TaskSectionView", "No direction set")); ui->lPendingUpdates->setText(msgLiteral); } void TaskSectionView::setUiEdit() { -// Base::Console().Message("TSV::setUiEdit()\n"); + // Base::Console().Message("TSV::setUiEdit()\n"); setWindowTitle(QObject::tr("Edit Section View")); std::string temp = m_section->SectionSymbol.getValue(); QString qTemp = Base::Tools::fromStdString(temp); @@ -154,7 +160,7 @@ void TaskSectionView::setUiEdit() ui->sbScale->setValue(m_section->getScale()); ui->cmbScaleType->setCurrentIndex(m_section->ScaleType.getValue()); //Allow or prevent scale changing initially - if (m_section->ScaleType.isValue("Custom")) { + if (m_section->ScaleType.isValue("Custom")) { ui->sbScale->setEnabled(true); } else { @@ -166,17 +172,18 @@ void TaskSectionView::setUiEdit() // convert section normal to view angle Base::Vector3d sectionNormalVec = m_section->SectionNormal.getValue(); + sectionNormalVec.Normalize(); Base::Vector3d projectedViewDirection = m_base->projectPoint(sectionNormalVec, false); - double viewAngle = atan2(-projectedViewDirection.y, - -projectedViewDirection.x); + projectedViewDirection.Normalize(); + double viewAngle = atan2(-projectedViewDirection.y, -projectedViewDirection.x); m_compass->setDialAngle(viewAngle * 180.0 / M_PI); - m_viewDirectionWidget->setValue(sectionNormalVec * -1.0); + m_viewDirectionWidget->setValueNoNotify(sectionNormalVec * -1.0); } void TaskSectionView::setUiCommon(Base::Vector3d origin) { std::string temp = m_base->getNameInDocument(); - QString qTemp = Base::Tools::fromStdString(temp); + QString qTemp = Base::Tools::fromStdString(temp); ui->leBaseView->setText(qTemp); ui->sbOrgX->setUnit(Base::Unit::Length); @@ -217,25 +224,26 @@ void TaskSectionView::setUiCommon(Base::Vector3d origin) m_viewDirectionWidget = new VectorEditWidget(this); m_viewDirectionWidget->setLabel(QObject::tr("Current View Direction")); + m_viewDirectionWidget->setToolTip(QObject::tr("The view direction in BaseView coordinates")); auto editLayout = ui->viewDirectionLayout; editLayout->addWidget(m_viewDirectionWidget); - connect(m_viewDirectionWidget, SIGNAL(valueChanged(Base::Vector3d)), - this, SLOT(slotViewDirectionChanged(Base::Vector3d))); + connect(m_viewDirectionWidget, SIGNAL(valueChanged(Base::Vector3d)), this, + SLOT(slotViewDirectionChanged(Base::Vector3d))); } //save the start conditions void TaskSectionView::saveSectionState() { -// Base::Console().Message("TSV::saveSectionState()\n"); + // Base::Console().Message("TSV::saveSectionState()\n"); if (m_section) { m_saveSymbol = m_section->SectionSymbol.getValue(); - m_saveScale = m_section->getScale(); + m_saveScale = m_section->getScale(); m_saveScaleType = m_section->ScaleType.getValue(); m_saveNormal = m_section->SectionNormal.getValue(); m_normal = m_saveNormal; m_saveDirection = m_section->Direction.getValue(); - m_saveOrigin = m_section->SectionOrigin.getValue(); - m_saveDirName = m_section->SectionDirection.getValueAsString(); + m_saveOrigin = m_section->SectionOrigin.getValue(); + m_saveDirName = m_section->SectionDirection.getValueAsString(); m_saved = true; } } @@ -243,7 +251,7 @@ void TaskSectionView::saveSectionState() //restore the start conditions void TaskSectionView::restoreSectionState() { -// Base::Console().Message("TSV::restoreSectionState()\n"); + // Base::Console().Message("TSV::restoreSectionState()\n"); if (!m_section) return; @@ -259,64 +267,64 @@ void TaskSectionView::restoreSectionState() //the VectorEditWidget reports a change in direction void TaskSectionView::slotViewDirectionChanged(Base::Vector3d newDirection) { -// Base::Console().Message("TSV::slotViewDirectionChanged(%s)\n", -// DrawUtil::formatVector(newDirection).c_str()); + // Base::Console().Message("TSV::slotViewDirectionChanged(%s)\n", + // DrawUtil::formatVector(newDirection).c_str()); Base::Vector3d projectedViewDirection = m_base->projectPoint(newDirection, false); projectedViewDirection.Normalize(); - double viewAngle = atan2(projectedViewDirection.y, - projectedViewDirection.x); + double viewAngle = atan2(projectedViewDirection.y, projectedViewDirection.x); m_compass->setDialAngle(viewAngle * 180.0 / M_PI); checkAll(false); - applyAligned(projectedViewDirection); + applyAligned(); } //the CompassWidget reports that the view direction angle has changed void TaskSectionView::slotChangeAngle(double newAngle) { -// Base::Console().Message("TSV::slotChangeAngle(%.3f)\n", newAngle); + // Base::Console().Message("TSV::slotChangeAngle(%.3f)\n", newAngle); double angleRadians = newAngle * M_PI / 180.0; double unitX = cos(angleRadians); double unitY = sin(angleRadians); Base::Vector3d localUnit(unitX, unitY, 0.0); m_viewDirectionWidget->setValueNoNotify(localUnit); checkAll(false); - applyAligned(localUnit); + applyAligned(); } //preset view directions void TaskSectionView::onUpClicked() { -// Base::Console().Message("TSV::onUpClicked()\n"); + // Base::Console().Message("TSV::onUpClicked()\n"); checkAll(false); m_compass->setToNorth(); m_viewDirectionWidget->setValueNoNotify(Base::Vector3d(0.0, 1.0, 0.0)); - applyAligned(Base::Vector3d(0.0, 1.0, 0.0));} + applyAligned(); +} void TaskSectionView::onDownClicked() { -// Base::Console().Message("TSV::onDownClicked()\n"); + // Base::Console().Message("TSV::onDownClicked()\n"); checkAll(false); m_compass->setToSouth(); m_viewDirectionWidget->setValueNoNotify(Base::Vector3d(0.0, -1.0, 0.0)); - applyAligned(Base::Vector3d(0.0, -1.0, 0.0)); + applyAligned(); } void TaskSectionView::onLeftClicked() { -// Base::Console().Message("TSV::onLeftClicked()\n"); + // Base::Console().Message("TSV::onLeftClicked()\n"); checkAll(false); m_compass->setToWest(); m_viewDirectionWidget->setValueNoNotify(Base::Vector3d(-1.0, 0.0, 0.0)); - applyAligned(Base::Vector3d(-1.0, 0.0, 0.0)); + applyAligned(); } void TaskSectionView::onRightClicked() { -// Base::Console().Message("TSV::onRightClicked()\n"); + // Base::Console().Message("TSV::onRightClicked()\n"); checkAll(false); m_compass->setToEast(); m_viewDirectionWidget->setValueNoNotify(Base::Vector3d(1.0, 0.0, 0.0)); - applyAligned(Base::Vector3d(1.0, 0.0, 0.0)); + applyAligned(); } void TaskSectionView::onIdentifierChanged() @@ -357,21 +365,25 @@ void TaskSectionView::scaleTypeChanged(int index) ui->sbScale->setValue(m_base->findParentPage()->Scale.getValue()); ui->sbScale->setEnabled(false); } - } else if (index == 1) { + } + else if (index == 1) { // Automatic Scale Type ui->sbScale->setEnabled(false); if (m_section) { ui->sbScale->setValue(m_section->autoScale()); } - } else if (index == 2) { + } + else if (index == 2) { // Custom Scale Type ui->sbScale->setEnabled(true); if (m_section) { ui->sbScale->setValue(m_section->Scale.getValue()); ui->sbScale->setEnabled(true); } - } else { - Base::Console().Log("Error - TaskSectionView::scaleTypeChanged - unknown scale type: %d\n", index); + } + else { + Base::Console().Log("Error - TaskSectionView::scaleTypeChanged - unknown scale type: %d\n", + index); return; } } @@ -394,7 +406,7 @@ void TaskSectionView::enableAll(bool enable) ui->cmbScaleType->setEnabled(enable); QString qScaleType = ui->cmbScaleType->currentText(); //Allow or prevent scale changing initially - if (qScaleType == QString::fromUtf8("Custom")) { + if (qScaleType == QString::fromUtf8("Custom")) { ui->sbScale->setEnabled(true); } else { @@ -402,30 +414,28 @@ void TaskSectionView::enableAll(bool enable) } } -void TaskSectionView::liveUpdateClicked() { - apply(true); -} +void TaskSectionView::liveUpdateClicked() { apply(true); } -void TaskSectionView::updateNowClicked() { - apply(true); -} +void TaskSectionView::updateNowClicked() { apply(true); } //****************************************************************************** bool TaskSectionView::apply(bool forceUpdate) { -// Base::Console().Message("TSV::apply() - liveUpdate: %d force: %d deferred: %d\n", -// ui->cbLiveUpdate->isChecked(), forceUpdate, m_applyDeferred); - if(!ui->cbLiveUpdate->isChecked() && - !forceUpdate) { + // Base::Console().Message("TSV::apply() - liveUpdate: %d force: %d deferred: %d\n", + // ui->cbLiveUpdate->isChecked(), forceUpdate, m_applyDeferred); + if (!ui->cbLiveUpdate->isChecked() && !forceUpdate) { //nothing to do m_applyDeferred++; - QString msgLiteral = QString::fromUtf8(QT_TRANSLATE_NOOP("TaskPojGroup", " updates pending")); + QString msgLiteral = + QString::fromUtf8(QT_TRANSLATE_NOOP("TaskPojGroup", " updates pending")); QString msgNumber = QString::number(m_applyDeferred); ui->lPendingUpdates->setText(msgNumber + msgLiteral); return false; } Gui::WaitCursor wc; + m_modelIsDirty = true; + if (m_dirName.empty()) { //this should never happen std::string msg = @@ -439,7 +449,8 @@ bool TaskSectionView::apply(bool forceUpdate) if (isSectionValid()) { updateSectionView(); - } else { + } + else { failNoObject(); } @@ -459,17 +470,16 @@ bool TaskSectionView::apply(bool forceUpdate) void TaskSectionView::applyQuick(std::string dir) { -// Base::Console().Message("TSV::applyQuick(%s)\n", dir.c_str()); + // Base::Console().Message("TSV::applyQuick(%s)\n", dir.c_str()); m_dirName = dir; enableAll(true); apply(); } -void TaskSectionView::applyAligned(Base::Vector3d localUnit) +void TaskSectionView::applyAligned() { -// Base::Console().Message("TSV::applyAligned()\n"); + // Base::Console().Message("TSV::applyAligned()\n"); m_dirName = "Aligned"; - m_localUnit = localUnit; enableAll(true); m_directionIsSet = true; ui->pbUpdateNow->setEnabled(true); @@ -481,7 +491,7 @@ void TaskSectionView::applyAligned(Base::Vector3d localUnit) TechDraw::DrawViewSection* TaskSectionView::createSectionView(void) { -// Base::Console().Message("TSV::createSectionView()\n"); + // Base::Console().Message("TSV::createSectionView()\n"); if (!isBaseValid()) { failNoObject(); return nullptr; @@ -501,17 +511,15 @@ TechDraw::DrawViewSection* TaskSectionView::createSectionView(void) m_savePageName.c_str(), m_sectionName.c_str()); Command::doCommand(Command::Doc, "App.ActiveDocument.%s.BaseView = App.ActiveDocument.%s", m_sectionName.c_str(), baseName.c_str()); - Command::doCommand(Command::Doc, "App.ActiveDocument.%s.Source = App.ActiveDocument.%s.Source", + Command::doCommand(Command::Doc, + "App.ActiveDocument.%s.Source = App.ActiveDocument.%s.Source", m_sectionName.c_str(), baseName.c_str()); Command::doCommand(Command::Doc, "App.ActiveDocument.%s.SectionOrigin = FreeCAD.Vector(%.6f, %.6f, %.6f)", - m_sectionName.c_str(), - ui->sbOrgX->value().getValue(), - ui->sbOrgY->value().getValue(), - ui->sbOrgZ->value().getValue()); + m_sectionName.c_str(), ui->sbOrgX->value().getValue(), + ui->sbOrgY->value().getValue(), ui->sbOrgZ->value().getValue()); Command::doCommand(Command::Doc, "App.ActiveDocument.%s.Scale = %0.6f", - m_sectionName.c_str(), - ui->sbScale->value().getValue()); + m_sectionName.c_str(), ui->sbScale->value().getValue()); int scaleType = ui->cmbScaleType->currentIndex(); Command::doCommand(Command::Doc, "App.ActiveDocument.%s.ScaleType = %d", m_sectionName.c_str(), scaleType); @@ -523,14 +531,22 @@ TechDraw::DrawViewSection* TaskSectionView::createSectionView(void) if (!newObj || !m_section) { throw Base::RuntimeError("TaskSectionView - new section object not found"); } + Base::Vector3d localUnit = m_viewDirectionWidget->value(); + localUnit.Normalize(); if (m_dirName == "Aligned") { - //m_localUnit is a view direction so we need to reverse it to make a + //localUnit is a view direction so we need to reverse it to make a //section normal - m_section->setCSFromBase(m_localUnit * -1.0); - } else { + m_section->setCSFromBase(localUnit * -1.0); + } + else { //Note: DirectionName is to be deprecated in the future m_section->setCSFromBase(m_dirName.c_str()); } + //auto orientation of view relative to base view + double viewDirectionAngle = m_compass->positiveValue(); + double rotation = requiredRotation(viewDirectionAngle); + Command::doCommand(Command::Doc, "App.ActiveDocument.%s.Rotation = %.6f", + m_sectionName.c_str(), rotation); } Gui::Command::commitCommand(); return m_section; @@ -538,7 +554,7 @@ TechDraw::DrawViewSection* TaskSectionView::createSectionView(void) void TaskSectionView::updateSectionView() { -// Base::Console().Message("TSV::updateSectionView() - m_sectionName: %s\n", m_sectionName.c_str()); + // Base::Console().Message("TSV::updateSectionView() - m_sectionName: %s\n", m_sectionName.c_str()); if (!isSectionValid()) { failNoObject(); return; @@ -550,39 +566,38 @@ void TaskSectionView::updateSectionView() m_sectionName.c_str(), m_dirName.c_str()); Command::doCommand(Command::Doc, "App.ActiveDocument.%s.SectionOrigin = FreeCAD.Vector(%.3f, %.3f, %.3f)", - m_sectionName.c_str(), - ui->sbOrgX->value().getValue(), - ui->sbOrgY->value().getValue(), - ui->sbOrgZ->value().getValue()); - QString qTemp = ui->leSymbol->text(); + m_sectionName.c_str(), ui->sbOrgX->value().getValue(), + ui->sbOrgY->value().getValue(), ui->sbOrgZ->value().getValue()); + QString qTemp = ui->leSymbol->text(); std::string temp = Base::Tools::toStdString(qTemp); Command::doCommand(Command::Doc, "App.ActiveDocument.%s.SectionSymbol = '%s'", - m_sectionName.c_str(), - temp.c_str()); - std::string lblText = "Section " + - temp + - " - " + - temp; + m_sectionName.c_str(), temp.c_str()); + std::string lblText = "Section " + temp + " - " + temp; Command::doCommand(Command::Doc, "App.ActiveDocument.%s.Label = '%s'", - m_sectionName.c_str(), - lblText.c_str()); + m_sectionName.c_str(), lblText.c_str()); Command::doCommand(Command::Doc, "App.ActiveDocument.%s.Scale = %0.6f", - m_sectionName.c_str(), - ui->sbScale->value().getValue()); + m_sectionName.c_str(), ui->sbScale->value().getValue()); int scaleType = ui->cmbScaleType->currentIndex(); Command::doCommand(Command::Doc, "App.ActiveDocument.%s.ScaleType = %d", m_sectionName.c_str(), scaleType); Command::doCommand(Command::Doc, "App.ActiveDocument.%s.SectionDirection = '%s'", m_sectionName.c_str(), m_dirName.c_str()); + Base::Vector3d localUnit = m_viewDirectionWidget->value(); + localUnit.Normalize(); if (m_dirName == "Aligned") { - //m_localUnit is a view direction so we need to reverse it to make a + //localUnit is a view direction so we need to reverse it to make a //section normal - m_section->setCSFromBase(m_localUnit * -1.0); - } else { + m_section->setCSFromBase(localUnit * -1.0); + } + else { //Note: DirectionName is to be deprecated in the future m_section->setCSFromBase(m_dirName.c_str()); } - + //auto orientation of view relative to base view + double viewDirectionAngle = m_compass->positiveValue(); + double rotation = requiredRotation(viewDirectionAngle); + Command::doCommand(Command::Doc, "App.ActiveDocument.%s.Rotation = %.6f", + m_sectionName.c_str(), rotation); } Gui::Command::commitCommand(); } @@ -620,25 +635,37 @@ bool TaskSectionView::isSectionValid() return true; } +//get required rotation from input angle in [0, 360] +double TaskSectionView::requiredRotation(double inputAngle) +{ + double rotation = inputAngle - 90.0; + if (rotation == 180.0) { + //if the view direction is 90/270, then the section is drawn properly and no + //rotation is needed. 90.0 becomes 0.0, but 270.0 needs special handling. + rotation = 0.0; + } + return rotation; +} + //****************************************************************************** bool TaskSectionView::accept() { -// Base::Console().Message("TSV::accept()\n"); + // Base::Console().Message("TSV::accept()\n"); apply(true); - Gui::Command::doCommand(Gui::Command::Gui,"Gui.ActiveDocument.resetEdit()"); + Gui::Command::doCommand(Gui::Command::Gui, "Gui.ActiveDocument.resetEdit()"); return true; } bool TaskSectionView::reject() { -// Base::Console().Message("TSV::reject()\n"); - if (!m_section) { //no section created, nothing to undo + // Base::Console().Message("TSV::reject()\n"); + if (!m_section) {//no section created, nothing to undo Gui::Command::doCommand(Gui::Command::Gui, "Gui.ActiveDocument.resetEdit()"); return false; } - if (!isSectionValid()) { //section !exist. nothing to undo + if (!isSectionValid()) {//section !exist. nothing to undo if (isBaseValid()) { m_base->requestPaint(); } @@ -651,13 +678,15 @@ bool TaskSectionView::reject() Gui::Command::doCommand(Gui::Command::Gui, "App.ActiveDocument.%s.removeView(App.ActiveDocument.%s)", m_savePageName.c_str(), SectionName.c_str()); - Gui::Command::doCommand(Gui::Command::Gui, - "App.ActiveDocument.removeObject('%s')", + Gui::Command::doCommand(Gui::Command::Gui, "App.ActiveDocument.removeObject('%s')", SectionName.c_str()); + } else { - restoreSectionState(); - m_section->recomputeFeature(); - m_section->requestPaint(); + if (m_modelIsDirty) { + restoreSectionState(); + m_section->recomputeFeature(); + m_section->requestPaint(); + } } if (isBaseValid()) { @@ -669,7 +698,7 @@ bool TaskSectionView::reject() return false; } -void TaskSectionView::changeEvent(QEvent *event) +void TaskSectionView::changeEvent(QEvent* event) { if (event->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -677,29 +706,27 @@ void TaskSectionView::changeEvent(QEvent *event) } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -TaskDlgSectionView::TaskDlgSectionView(TechDraw::DrawViewPart* base) : - TaskDialog() +TaskDlgSectionView::TaskDlgSectionView(TechDraw::DrawViewPart* base) : TaskDialog() { - widget = new TaskSectionView(base); - taskbox = new Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("actions/TechDraw_SectionView"), - widget->windowTitle(), true, nullptr); + widget = new TaskSectionView(base); + taskbox = + new Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("actions/TechDraw_SectionView"), + widget->windowTitle(), true, nullptr); taskbox->groupLayout()->addWidget(widget); Content.push_back(taskbox); } -TaskDlgSectionView::TaskDlgSectionView(TechDraw::DrawViewSection* section) : - TaskDialog() +TaskDlgSectionView::TaskDlgSectionView(TechDraw::DrawViewSection* section) : TaskDialog() { - widget = new TaskSectionView(section); - taskbox = new Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("actions/TechDraw_SectionView"), - widget->windowTitle(), true, nullptr); + widget = new TaskSectionView(section); + taskbox = + new Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("actions/TechDraw_SectionView"), + widget->windowTitle(), true, nullptr); taskbox->groupLayout()->addWidget(widget); Content.push_back(taskbox); } -TaskDlgSectionView::~TaskDlgSectionView() -{ -} +TaskDlgSectionView::~TaskDlgSectionView() {} void TaskDlgSectionView::update() { @@ -707,9 +734,7 @@ void TaskDlgSectionView::update() } //==== calls from the TaskView =============================================================== -void TaskDlgSectionView::open() -{ -} +void TaskDlgSectionView::open() {} bool TaskDlgSectionView::accept() { diff --git a/src/Mod/TechDraw/Gui/TaskSectionView.h b/src/Mod/TechDraw/Gui/TaskSectionView.h index c4a8bb6ae128..9412f290da88 100644 --- a/src/Mod/TechDraw/Gui/TaskSectionView.h +++ b/src/Mod/TechDraw/Gui/TaskSectionView.h @@ -60,7 +60,7 @@ class TaskSectionView : public QWidget bool apply(bool forceUpdate = false); void applyQuick(std::string dir); - void applyAligned(Base::Vector3d localUnit); + void applyAligned(); TechDraw::DrawViewSection* createSectionView(); void updateSectionView(); @@ -93,6 +93,8 @@ protected Q_SLOTS: void slotViewDirectionChanged(Base::Vector3d newDirection); private: + double requiredRotation(double inputAngle); + std::unique_ptr ui; TechDraw::DrawViewPart* m_base; TechDraw::DrawViewSection* m_section; @@ -121,10 +123,10 @@ protected Q_SLOTS: std::string m_savePageName; int m_applyDeferred; - Base::Vector3d m_localUnit; CompassWidget* m_compass; VectorEditWidget* m_viewDirectionWidget; bool m_directionIsSet; + bool m_modelIsDirty; }; class TaskDlgSectionView : public Gui::TaskView::TaskDialog diff --git a/src/Mod/TechDraw/Gui/ViewProviderDimension.cpp b/src/Mod/TechDraw/Gui/ViewProviderDimension.cpp index b299a9fbc431..fb82514f8c47 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderDimension.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderDimension.cpp @@ -138,9 +138,9 @@ bool ViewProviderDimension::setEdit(int ModNum) return true; } -void ViewProviderDimension::updateData(const App::Property* p) +void ViewProviderDimension::updateData(const App::Property* prop) { - if (p == &(getViewObject()->Type)) { + if (prop == &(getViewObject()->Type)) { if (getViewObject()->Type.isValue("DistanceX")) { sPixmap = "TechDraw_HorizontalDimension"; } else if (getViewObject()->Type.isValue("DistanceY")) { @@ -154,20 +154,33 @@ void ViewProviderDimension::updateData(const App::Property* p) } else if (getViewObject()->Type.isValue("Angle3Pt")) { sPixmap = "TechDraw_3PtAngleDimension"; } + return; } //Dimension handles X, Y updates differently that other QGIView //call QGIViewDimension::updateView - if (p == &(getViewObject()->X) || - p == &(getViewObject()->Y) ){ + if (prop == &(getViewObject()->X) || + prop == &(getViewObject()->Y) || + prop == &(getViewObject()->FormatSpec) || + prop == &(getViewObject()->Arbitrary) || + prop == &(getViewObject()->FormatSpecOverTolerance) || + prop == &(getViewObject()->FormatSpecUnderTolerance) || + prop == &(getViewObject()->ArbitraryTolerances) || + prop == &(getViewObject()->MeasureType) || + prop == &(getViewObject()->TheoreticalExact) || + prop == &(getViewObject()->EqualTolerance) || + prop == &(getViewObject()->OverTolerance) || + prop == &(getViewObject()->UnderTolerance) || + prop == &(getViewObject()->Inverted) ){ QGIView* qgiv = getQView(); if (qgiv) { qgiv->updateView(true); } + return; } //Skip QGIView X, Y processing - do not call ViewProviderDrawingView - Gui::ViewProviderDocumentObject::updateData(p); + Gui::ViewProviderDocumentObject::updateData(prop); } void ViewProviderDimension::onChanged(const App::Property* p) diff --git a/src/Mod/TechDraw/Gui/Widgets/CompassWidget.cpp b/src/Mod/TechDraw/Gui/Widgets/CompassWidget.cpp index c02b67ab7d3a..0f068ef88cd9 100644 --- a/src/Mod/TechDraw/Gui/Widgets/CompassWidget.cpp +++ b/src/Mod/TechDraw/Gui/Widgets/CompassWidget.cpp @@ -21,8 +21,8 @@ ***************************************************************************/ // The CompassWidget has several children widgets - a CompassDialWidget, a fine -// adjustment QDoubleSpinBox and a QPushButton that acts as an enter key -// for the spin box. +// adjustment QDoubleSpinBox and QPushButtons that increment the spin box by a +// (usually) larger step than the arrows on the spinbox #include "PreCompiled.h" #ifndef _PreComp_ @@ -45,7 +45,7 @@ using namespace TechDrawGui; -CompassWidget::CompassWidget(QWidget *parent) +CompassWidget::CompassWidget(QWidget* parent) : QWidget(parent), m_minimumWidth(200), m_minimumHeight(200), m_defaultMargin(10), m_angle(0.0), m_advanceIncrement(10.0) { @@ -54,7 +54,6 @@ CompassWidget::CompassWidget(QWidget *parent) buildWidget(); compassDial->setSize(m_minimumHeight - 2 * m_defaultMargin); - connect(pbUseCompassSetting, &QPushButton::pressed, this, &CompassWidget::slotUseSpinboxValue); dsbAngle->installEventFilter(this); connect(pbCWAdvance, &QPushButton::pressed, this, &CompassWidget::slotCWAdvance); @@ -62,17 +61,22 @@ CompassWidget::CompassWidget(QWidget *parent) } //trap Enter press in dsbAngle so as not to invoke task accept processing -bool CompassWidget::eventFilter(QObject *target, QEvent *event) +bool CompassWidget::eventFilter(QObject* target, QEvent* event) { if (target == dsbAngle) { if (event->type() == QEvent::KeyPress) { - QKeyEvent *keyEvent = static_cast(event); + QKeyEvent* keyEvent = static_cast(event); if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) { dsbAngle->interpretText(); slotSpinBoxEnter(dsbAngle->value()); return true; } } + else if (event->type() == QEvent::FocusOut) { + dsbAngle->interpretText(); + slotSpinBoxEnter(dsbAngle->value()); + return true; + } } return QWidget::eventFilter(target, event); } @@ -140,15 +144,6 @@ void CompassWidget::buildWidget() compassControlLayout->addWidget(dsbAngle); - pbUseCompassSetting = new QPushButton(this); - pbUseCompassSetting->setObjectName(QString::fromUtf8("pbUseCompassSetting")); - QIcon icon; - icon.addFile(QString::fromUtf8(":/icons/edit_OK.svg"), QSize(), QIcon::Normal, QIcon::On); - pbUseCompassSetting->setIcon(icon); - pbUseCompassSetting->setText(QString()); - - compassControlLayout->addWidget(pbUseCompassSetting); - compassControlLayout->setStretch(0, 3); compassControlLayout->setStretch(1, 2); @@ -164,8 +159,6 @@ void CompassWidget::retranslateUi() #ifndef QT_NO_TOOLTIP dsbAngle->setToolTip(QApplication::translate( "CompassWidget", "The view direction angle relative to +X in the BaseView.", nullptr)); - pbUseCompassSetting->setToolTip(QApplication::translate( - "CompassWidget", "Use the current view direction to set the Section Normal.", nullptr)); pbCWAdvance->setToolTip(QApplication::translate( "CompassWidget", "Advance the view direction in clockwise direction.", nullptr)); pbCCWAdvance->setToolTip(QApplication::translate( @@ -180,7 +173,7 @@ QSize CompassWidget::minimumSizeHint() const return QRect(0, 0, m_minimumWidth, m_minimumHeight).size(); } -void CompassWidget::paintEvent(QPaintEvent *event) +void CompassWidget::paintEvent(QPaintEvent* event) { Q_UNUSED(event); QWidget::paintEvent(event); @@ -199,17 +192,6 @@ void CompassWidget::setDialAngle(double newAngle) } } -//slot for updates from spinbox arrows or typing. -void CompassWidget::slotSpinBoxUpdate(double newAngle) -{ - // Base::Console().Message("CW::slotSpinBoxUpdate(%.3f)\n", newAngle); - m_angle = newAngle; - Q_EMIT angleChanged(m_angle); - if (compassDial) { - compassDial->setAngle(m_angle); - } -} - //slot for updates from spinbox on Enter/Return press. void CompassWidget::slotSpinBoxEnter(double newAngle) { @@ -223,20 +205,6 @@ void CompassWidget::slotSpinBoxEnter(double newAngle) } } -//slot for OK button press -void CompassWidget::slotUseSpinboxValue() -{ - // Base::Console().Message("CW::slotUseSpinboxValue()\n"); - if (dsbAngle) { - dsbAngle->interpretText(); - m_angle = dsbAngle->value(); - Q_EMIT angleChanged(m_angle); - } - if (compassDial) { - compassDial->setAngle(m_angle); - } -} - void CompassWidget::slotCWAdvance() { double angle = m_angle - m_advanceIncrement; @@ -249,7 +217,13 @@ void CompassWidget::slotCWAdvance() void CompassWidget::slotCCWAdvance() { double angle = m_angle + m_advanceIncrement; - setDialAngle(fmod(angle, 360.0)); + if (angle > dsbAngle->maximum()) { + angle = angle - dsbAngle->maximum(); + } + if (angle < dsbAngle->minimum()) { + angle = angle + dsbAngle->minimum(); + } + setDialAngle(angle); } void CompassWidget::setAdvanceIncrement(double newIncrement) { m_advanceIncrement = newIncrement; } diff --git a/src/Mod/TechDraw/Gui/Widgets/CompassWidget.h b/src/Mod/TechDraw/Gui/Widgets/CompassWidget.h index 191235f16e6f..7a6b1fda8288 100644 --- a/src/Mod/TechDraw/Gui/Widgets/CompassWidget.h +++ b/src/Mod/TechDraw/Gui/Widgets/CompassWidget.h @@ -25,8 +25,8 @@ #include #include -#include #include +#include QT_BEGIN_NAMESPACE class QLabel; @@ -35,14 +35,15 @@ class QPushButton; class QVBoxLayout; QT_END_NAMESPACE -namespace TechDrawGui { +namespace TechDrawGui +{ class CompassDialWidget; -class CompassWidget : public QWidget +class CompassWidget: public QWidget { Q_OBJECT - Q_PROPERTY( double angle READ dialAngle WRITE setDialAngle NOTIFY angleChanged) + Q_PROPERTY(double angle READ dialAngle WRITE setDialAngle NOTIFY angleChanged) public: CompassWidget(QWidget* parent = 0); @@ -50,9 +51,11 @@ class CompassWidget : public QWidget QSize sizeHint() const override; QSize minimumSizeHint() const override; - bool eventFilter(QObject *target, QEvent *event) override; + bool eventFilter(QObject* target, QEvent* event) override; void retranslateUi(); double dialAngle() const { return m_angle; } + double value() const { return m_angle; } + double positiveValue() { return m_angle < 0.0 ? m_angle + 360.0 : m_angle; } void setDialAngle(double newAngle); void setAdvanceIncrement(double newIncrement); double advanceIncrement() const { return m_advanceIncrement; } @@ -63,13 +66,11 @@ class CompassWidget : public QWidget public Q_SLOTS: void slotChangeAngle(double angle) { setDialAngle(angle); } - void slotSpinBoxUpdate(double newAngle); void slotSpinBoxEnter(double newAngle); - void slotUseSpinboxValue(); - void resetAngle() { setDialAngle(0.0); } //conventional angles - void setToEast() { setDialAngle(0.0); } + void resetAngle() { setDialAngle(0.0); }//conventional angles + void setToEast() { setDialAngle(0.0); } void setToNorth() { setDialAngle(90.0); } - void setToWest() { setDialAngle(180.0); } + void setToWest() { setDialAngle(180.0); } void setToSouth() { setDialAngle(270.0); } void slotCWAdvance(); void slotCCWAdvance(); @@ -92,14 +93,12 @@ public Q_SLOTS: QHBoxLayout* compassControlLayout; CompassDialWidget* compassDial; -// DoubleSpinBoxNoEnter* dsbAngle; + // DoubleSpinBoxNoEnter* dsbAngle; QDoubleSpinBox* dsbAngle; QLabel* compassControlLabel; - QPushButton* pbUseCompassSetting; QPushButton* pbCWAdvance; QPushButton* pbCCWAdvance; }; -} //namespace TechDrawGui -#endif // COMPASSWIDGET_H - +}//namespace TechDrawGui +#endif// COMPASSWIDGET_H diff --git a/src/Mod/TechDraw/Gui/Widgets/VectorEditWidget.cpp b/src/Mod/TechDraw/Gui/Widgets/VectorEditWidget.cpp index 15b68ad713c1..5f0fd2555873 100644 --- a/src/Mod/TechDraw/Gui/Widgets/VectorEditWidget.cpp +++ b/src/Mod/TechDraw/Gui/Widgets/VectorEditWidget.cpp @@ -66,9 +66,9 @@ VectorEditWidget::VectorEditWidget(QWidget* parent) : QWidget(parent), buildWidget(); connect(tbExpand, SIGNAL(toggled(bool)), this, SLOT(slotExpandButtonToggled(bool))); - connect(dsbX, SIGNAL(valueChanged(double)), this, SLOT(xValueChanged(double))); - connect(dsbY, SIGNAL(valueChanged(double)), this, SLOT(yValueChanged(double))); - connect(dsbZ, SIGNAL(valueChanged(double)), this, SLOT(zValueChanged(double))); + connect(dsbX, SIGNAL(valueChanged(double)), this, SLOT(slotXValueChanged(double))); + connect(dsbY, SIGNAL(valueChanged(double)), this, SLOT(slotYValueChanged(double))); + connect(dsbZ, SIGNAL(valueChanged(double)), this, SLOT(slotZValueChanged(double))); dsbX->installEventFilter(this); dsbY->installEventFilter(this); @@ -107,7 +107,7 @@ void VectorEditWidget::setLabel(QString newLabel) void VectorEditWidget::setValue(Base::Vector3d newValue) { -// Base::Console().Message("VEW::setValue(%s)\n", DrawUtil::formatVector(newValue).c_str()); +// Base::Console().Message("VEW::setValue(%.6f, %.6f, %.6f)\n", newValue.x, newValue.y, newValue.z); m_value = newValue; dsbX->setValue(m_value.x); dsbY->setValue(m_value.y); @@ -117,7 +117,7 @@ void VectorEditWidget::setValue(Base::Vector3d newValue) void VectorEditWidget::setValueNoNotify(Base::Vector3d newValue) { -// Base::Console().Message("VEW::setValue(%s)\n", DrawUtil::formatVector(newValue).c_str()); +// Base::Console().Message("VEW::setValueNoNotify(%.6f, %.6f, %.6f)\n", newValue.x, newValue.y, newValue.z); m_value = newValue; m_blockNotify = true; dsbX->setValue(m_value.x); @@ -142,30 +142,35 @@ void VectorEditWidget::slotExpandButtonToggled(bool checked) } } -void VectorEditWidget::xValueChanged(double newValue) +//slotXValueChanged can be triggered by the Ui or programmatically. We only want +//to tell the world about the change if it comes from the Ui. +void VectorEditWidget::slotXValueChanged(double newValue) { -// Base::Console().Message("VEW::xValueChanged(%.3f)\n", newValue); - m_value.x = newValue; - updateDisplay(); +// Base::Console().Message("VEW::xValueChanged(%.6f) - m_value.x: %.6f\n", newValue, m_value.x); if (!m_blockNotify) { + //this is a change from the dsb + m_value.x = newValue; + updateDisplay(); Q_EMIT valueChanged(m_value); } } -void VectorEditWidget::yValueChanged(double newValue) +void VectorEditWidget::slotYValueChanged(double newValue) { -// Base::Console().Message("VEW::yValueChanged(%.3f)\n", newValue); - m_value.y = newValue; - updateDisplay(); +// Base::Console().Message("VEW::yValueChanged(%.6f) - m_value.y: %.6f\n", newValue, m_value.y); if (!m_blockNotify) { + //this is a change from the dsb + m_value.y = newValue; + updateDisplay(); Q_EMIT valueChanged(m_value); } } -void VectorEditWidget::zValueChanged(double newValue) +void VectorEditWidget::slotZValueChanged(double newValue) { -// Base::Console().Message("VEW::zValueChanged(%.3f)\n", newValue); - m_value.z = newValue; - updateDisplay(); +// Base::Console().Message("VEW::zValueChanged(%.6f)\n", newValue); if (!m_blockNotify) { + //this is a change from the dsb + m_value.z = newValue; + updateDisplay(); Q_EMIT valueChanged(m_value); } } @@ -262,4 +267,3 @@ void VectorEditWidget::buildWidget() verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); } - diff --git a/src/Mod/TechDraw/Gui/Widgets/VectorEditWidget.h b/src/Mod/TechDraw/Gui/Widgets/VectorEditWidget.h index f6c7e38b36d6..5ca66ab76d02 100644 --- a/src/Mod/TechDraw/Gui/Widgets/VectorEditWidget.h +++ b/src/Mod/TechDraw/Gui/Widgets/VectorEditWidget.h @@ -72,9 +72,9 @@ public Q_SLOTS: protected Q_SLOTS: void slotExpandButtonToggled(bool checked); - void xValueChanged(double newValue); - void yValueChanged(double newValue); - void zValueChanged(double newValue); + void slotXValueChanged(double newValue); + void slotYValueChanged(double newValue); + void slotZValueChanged(double newValue); void updateDisplay();