From 987b4bda2ac8570969dc07fa887bda420f77e441 Mon Sep 17 00:00:00 2001 From: Abdullah Tahiri Date: Thu, 18 May 2023 19:01:34 +0200 Subject: [PATCH] Sketcher: App - Clang-format --- src/Mod/Sketcher/App/Analyse.h | 36 +- src/Mod/Sketcher/App/AppSketcher.cpp | 43 +- src/Mod/Sketcher/App/AppSketcherPy.cpp | 36 +- src/Mod/Sketcher/App/Constraint.cpp | 149 +- src/Mod/Sketcher/App/Constraint.h | 134 +- src/Mod/Sketcher/App/ConstraintPyImp.cpp | 478 +- .../App/ExternalGeometryExtension.cpp | 44 +- .../Sketcher/App/ExternalGeometryExtension.h | 98 +- .../App/ExternalGeometryExtensionPyImp.cpp | 48 +- .../Sketcher/App/ExternalGeometryFacade.cpp | 101 +- src/Mod/Sketcher/App/ExternalGeometryFacade.h | 298 +- .../App/ExternalGeometryFacadePyImp.cpp | 216 +- src/Mod/Sketcher/App/GeoEnum.h | 81 +- src/Mod/Sketcher/App/GeoList.cpp | 300 +- src/Mod/Sketcher/App/GeoList.h | 181 +- src/Mod/Sketcher/App/GeometryFacade.cpp | 90 +- src/Mod/Sketcher/App/GeometryFacade.h | 379 +- src/Mod/Sketcher/App/GeometryFacadePyImp.cpp | 193 +- src/Mod/Sketcher/App/PreCompiled.cpp | 2 +- src/Mod/Sketcher/App/PreCompiled.h | 40 +- .../Sketcher/App/PropertyConstraintList.cpp | 214 +- src/Mod/Sketcher/App/PropertyConstraintList.h | 85 +- src/Mod/Sketcher/App/PythonConverter.cpp | 625 +- src/Mod/Sketcher/App/PythonConverter.h | 36 +- src/Mod/Sketcher/App/Sketch.cpp | 3417 ++++----- src/Mod/Sketcher/App/Sketch.h | 796 ++- src/Mod/Sketcher/App/SketchAnalysis.cpp | 478 +- src/Mod/Sketcher/App/SketchAnalysis.h | 107 +- .../Sketcher/App/SketchGeometryExtension.cpp | 110 +- .../Sketcher/App/SketchGeometryExtension.h | 140 +- .../App/SketchGeometryExtensionPyImp.cpp | 46 +- src/Mod/Sketcher/App/SketchObject.cpp | 6082 +++++++++-------- src/Mod/Sketcher/App/SketchObject.h | 579 +- src/Mod/Sketcher/App/SketchObjectPyImp.cpp | 763 ++- src/Mod/Sketcher/App/SketchObjectSF.cpp | 15 +- src/Mod/Sketcher/App/SketchObjectSF.h | 16 +- src/Mod/Sketcher/App/SketchObjectSFPyImp.cpp | 6 +- src/Mod/Sketcher/App/SketchPyImp.cpp | 63 +- .../Sketcher/App/SolverGeometryExtension.cpp | 94 +- .../Sketcher/App/SolverGeometryExtension.h | 417 +- 40 files changed, 9714 insertions(+), 7322 deletions(-) diff --git a/src/Mod/Sketcher/App/Analyse.h b/src/Mod/Sketcher/App/Analyse.h index 2a4c968ccf..3e558c3db0 100644 --- a/src/Mod/Sketcher/App/Analyse.h +++ b/src/Mod/Sketcher/App/Analyse.h @@ -29,15 +29,17 @@ #include "Constraint.h" -namespace Sketcher { +namespace Sketcher +{ -struct ConstraintIds { - Base::Vector3d v; - int First; - int Second; - Sketcher::PointPos FirstPos; - Sketcher::PointPos SecondPos; - Sketcher::ConstraintType Type; +struct ConstraintIds +{ + Base::Vector3d v; + int First; + int Second; + Sketcher::PointPos FirstPos; + Sketcher::PointPos SecondPos; + Sketcher::ConstraintType Type; }; struct Constraint_Equal @@ -45,21 +47,21 @@ struct Constraint_Equal using argument_type = ConstraintIds; using result_type = bool; struct Sketcher::ConstraintIds c; - explicit Constraint_Equal(const ConstraintIds& c) : c(c) - { - } + explicit Constraint_Equal(const ConstraintIds& c) + : c(c) + {} bool operator()(const ConstraintIds& x) const { - if (c.First == x.First && c.FirstPos == x.FirstPos && - c.Second == x.Second && c.SecondPos == x.SecondPos) + if (c.First == x.First && c.FirstPos == x.FirstPos && c.Second == x.Second + && c.SecondPos == x.SecondPos) return true; - if (c.Second == x.First && c.SecondPos == x.FirstPos && - c.First == x.Second && c.FirstPos == x.SecondPos) + if (c.Second == x.First && c.SecondPos == x.FirstPos && c.First == x.Second + && c.FirstPos == x.SecondPos) return true; return false; } }; -} //namespace Sketcher +}// namespace Sketcher -#endif // SKETCHER_ANALYSE_H +#endif// SKETCHER_ANALYSE_H diff --git a/src/Mod/Sketcher/App/AppSketcher.cpp b/src/Mod/Sketcher/App/AppSketcher.cpp index 8e45af68cd..62f7b0dfa1 100644 --- a/src/Mod/Sketcher/App/AppSketcher.cpp +++ b/src/Mod/Sketcher/App/AppSketcher.cpp @@ -43,7 +43,8 @@ #include "SolverGeometryExtension.h" -namespace Sketcher { +namespace Sketcher +{ extern PyObject* initModule(); } @@ -54,7 +55,7 @@ PyMOD_INIT_FUNC(Sketcher) try { Base::Interpreter().runString("import Part"); } - catch(const Base::Exception& e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ImportError, e.what()); PyMOD_Return(nullptr); } @@ -62,29 +63,33 @@ PyMOD_INIT_FUNC(Sketcher) PyObject* sketcherModule = Sketcher::initModule(); // Add Types to module - Base::Interpreter().addType(&Sketcher::ConstraintPy ::Type,sketcherModule,"Constraint"); - Base::Interpreter().addType(&Sketcher::SketchPy ::Type,sketcherModule,"Sketch"); - Base::Interpreter().addType(&Sketcher::ExternalGeometryExtensionPy ::Type,sketcherModule,"ExternalGeometryExtension"); - Base::Interpreter().addType(&Sketcher::SketchGeometryExtensionPy ::Type,sketcherModule,"SketchGeometryExtension"); - Base::Interpreter().addType(&Sketcher::GeometryFacadePy ::Type,sketcherModule,"GeometryFacade"); - Base::Interpreter().addType(&Sketcher::ExternalGeometryFacadePy ::Type,sketcherModule,"ExternalGeometryFacade"); + Base::Interpreter().addType(&Sketcher::ConstraintPy ::Type, sketcherModule, "Constraint"); + Base::Interpreter().addType(&Sketcher::SketchPy ::Type, sketcherModule, "Sketch"); + Base::Interpreter().addType( + &Sketcher::ExternalGeometryExtensionPy ::Type, sketcherModule, "ExternalGeometryExtension"); + Base::Interpreter().addType( + &Sketcher::SketchGeometryExtensionPy ::Type, sketcherModule, "SketchGeometryExtension"); + Base::Interpreter().addType( + &Sketcher::GeometryFacadePy ::Type, sketcherModule, "GeometryFacade"); + Base::Interpreter().addType( + &Sketcher::ExternalGeometryFacadePy ::Type, sketcherModule, "ExternalGeometryFacade"); // NOTE: To finish the initialization of our own type objects we must // call PyType_Ready, otherwise we run into a segmentation fault, later on. // This function is responsible for adding inherited slots from a type's base class. - Sketcher::SketchGeometryExtension ::init(); - Sketcher::ExternalGeometryExtension ::init(); - Sketcher::SolverGeometryExtension ::init(); - Sketcher::GeometryFacade ::init(); - Sketcher::ExternalGeometryFacade ::init(); - Sketcher::SketchObjectSF ::init(); - Sketcher::SketchObject ::init(); - Sketcher::SketchObjectPython ::init(); - Sketcher::Sketch ::init(); - Sketcher::Constraint ::init(); - Sketcher::PropertyConstraintList ::init(); + Sketcher::SketchGeometryExtension ::init(); + Sketcher::ExternalGeometryExtension ::init(); + Sketcher::SolverGeometryExtension ::init(); + Sketcher::GeometryFacade ::init(); + Sketcher::ExternalGeometryFacade ::init(); + Sketcher::SketchObjectSF ::init(); + Sketcher::SketchObject ::init(); + Sketcher::SketchObjectPython ::init(); + Sketcher::Sketch ::init(); + Sketcher::Constraint ::init(); + Sketcher::PropertyConstraintList ::init(); Base::Console().Log("Loading Sketcher module... done\n"); diff --git a/src/Mod/Sketcher/App/AppSketcherPy.cpp b/src/Mod/Sketcher/App/AppSketcherPy.cpp index 6624c44e40..406dcadb05 100644 --- a/src/Mod/Sketcher/App/AppSketcherPy.cpp +++ b/src/Mod/Sketcher/App/AppSketcherPy.cpp @@ -32,31 +32,32 @@ #include "SketchObjectSF.h" -namespace Sketcher { -class Module : public Py::ExtensionModule +namespace Sketcher +{ +class Module: public Py::ExtensionModule { public: - Module() : Py::ExtensionModule("Sketcher") + Module() + : Py::ExtensionModule("Sketcher") { - add_varargs_method("open",&Module::open - ); - add_varargs_method("insert",&Module::insert - ); - initialize("This module is the Sketcher module."); // register with Python + add_varargs_method("open", &Module::open); + add_varargs_method("insert", &Module::insert); + initialize("This module is the Sketcher module.");// register with Python } - ~Module() override {} + ~Module() override + {} private: Py::Object open(const Py::Tuple& args) { char* Name; - if (!PyArg_ParseTuple(args.ptr(), "et","utf-8",&Name)) + if (!PyArg_ParseTuple(args.ptr(), "et", "utf-8", &Name)) throw Py::Exception(); std::string EncodedName = std::string(Name); PyMem_Free(Name); - //Base::Console().Log("Open in Part with %s",Name); + // Base::Console().Log("Open in Part with %s",Name); Base::FileInfo file(EncodedName.c_str()); // extract extension @@ -64,33 +65,34 @@ private: throw Py::RuntimeError("No file extension"); throw Py::RuntimeError("Unknown file extension"); - //return Py::None(); + // return Py::None(); } Py::Object insert(const Py::Tuple& args) { char* Name; const char* DocName; - if (!PyArg_ParseTuple(args.ptr(), "ets","utf-8",&Name,&DocName)) + if (!PyArg_ParseTuple(args.ptr(), "ets", "utf-8", &Name, &DocName)) throw Py::Exception(); std::string EncodedName = std::string(Name); PyMem_Free(Name); try { - //Base::Console().Log("Insert in Part with %s",Name); + // Base::Console().Log("Insert in Part with %s",Name); Base::FileInfo file(EncodedName.c_str()); // extract extension if (file.extension().empty()) throw Py::RuntimeError("No file extension"); - App::Document *pcDoc = App::GetApplication().getDocument(DocName); + App::Document* pcDoc = App::GetApplication().getDocument(DocName); if (!pcDoc) { pcDoc = App::GetApplication().newDocument(DocName); } if (file.hasExtension("skf")) { - Sketcher::SketchObjectSF *pcFeature = static_cast(pcDoc->addObject("Sketcher::SketchObjectSF",file.fileNamePure().c_str())); + Sketcher::SketchObjectSF* pcFeature = static_cast( + pcDoc->addObject("Sketcher::SketchObjectSF", file.fileNamePure().c_str())); pcFeature->SketchFlatFile.setValue(EncodedName.c_str()); pcDoc->recompute(); @@ -113,4 +115,4 @@ PyObject* initModule() } /// @endcond -} // namespace Sketcher +}// namespace Sketcher diff --git a/src/Mod/Sketcher/App/Constraint.cpp b/src/Mod/Sketcher/App/Constraint.cpp index 5032dd6e3f..9e4bfd9cd2 100644 --- a/src/Mod/Sketcher/App/Constraint.cpp +++ b/src/Mod/Sketcher/App/Constraint.cpp @@ -22,13 +22,13 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include +#include +#include #endif #include -#include #include +#include #include "Constraint.h" #include "ConstraintPy.h" @@ -41,21 +41,21 @@ using namespace Base; TYPESYSTEM_SOURCE(Sketcher::Constraint, Base::Persistence) Constraint::Constraint() -: Value(0.0), - Type(None), - AlignmentType(Undef), - First(GeoEnum::GeoUndef), - FirstPos(PointPos::none), - Second(GeoEnum::GeoUndef), - SecondPos(PointPos::none), - Third(GeoEnum::GeoUndef), - ThirdPos(PointPos::none), - LabelDistance(10.f), - LabelPosition(0.f), - isDriving(true), - InternalAlignmentIndex(-1), - isInVirtualSpace(false), - isActive(true) + : Value(0.0), + Type(None), + AlignmentType(Undef), + First(GeoEnum::GeoUndef), + FirstPos(PointPos::none), + Second(GeoEnum::GeoUndef), + SecondPos(PointPos::none), + Third(GeoEnum::GeoUndef), + ThirdPos(PointPos::none), + LabelDistance(10.f), + LabelPosition(0.f), + isDriving(true), + InternalAlignmentIndex(-1), + isInVirtualSpace(false), + isActive(true) { // Initialize a random number generator, to avoid Valgrind false positives. static boost::mt19937 ran; @@ -70,14 +70,14 @@ Constraint::Constraint() tag = gen(); } -Constraint *Constraint::clone() const +Constraint* Constraint::clone() const { return new Constraint(*this); } -Constraint *Constraint::copy() const +Constraint* Constraint::copy() const { - Constraint *temp = new Constraint(); + Constraint* temp = new Constraint(); temp->Value = this->Value; temp->Type = this->Type; temp->AlignmentType = this->AlignmentType; @@ -98,7 +98,7 @@ Constraint *Constraint::copy() const return temp; } -PyObject *Constraint::getPyObject() +PyObject* Constraint::getPyObject() { return new ConstraintPy(new Constraint(*this)); } @@ -107,80 +107,79 @@ Quantity Constraint::getPresentationValue() const { Quantity quantity; switch (Type) { - case Distance: - case Radius: - case Diameter: - case DistanceX: - case DistanceY: - quantity.setValue(Value); - quantity.setUnit(Unit::Length); - break; - case Angle: - quantity.setValue(toDegrees(Value)); - quantity.setUnit(Unit::Angle); - break; - case SnellsLaw: - case Weight: - quantity.setValue(Value); - break; - default: - quantity.setValue(Value); - break; + case Distance: + case Radius: + case Diameter: + case DistanceX: + case DistanceY: + quantity.setValue(Value); + quantity.setUnit(Unit::Length); + break; + case Angle: + quantity.setValue(toDegrees(Value)); + quantity.setUnit(Unit::Angle); + break; + case SnellsLaw: + case Weight: + quantity.setValue(Value); + break; + default: + quantity.setValue(Value); + break; } QuantityFormat format = quantity.getFormat(); format.option = QuantityFormat::None; format.format = QuantityFormat::Default; - format.precision = 6; // QString's default + format.precision = 6;// QString's default quantity.setFormat(format); return quantity; } -unsigned int Constraint::getMemSize () const +unsigned int Constraint::getMemSize() const { return 0; } -void Constraint::Save (Writer &writer) const +void Constraint::Save(Writer& writer) const { std::string encodeName = encodeAttribute(Name); - writer.Stream() << writer.ind() << "Type==InternalAlignment) - writer.Stream() - << "InternalAlignmentType=\"" << (int)AlignmentType << "\" " - << "InternalAlignmentIndex=\"" << InternalAlignmentIndex << "\" "; - writer.Stream() - << "Value=\"" << Value << "\" " - << "First=\"" << First << "\" " - << "FirstPos=\"" << (int) FirstPos << "\" " - << "Second=\"" << Second << "\" " - << "SecondPos=\"" << (int) SecondPos << "\" " - << "Third=\"" << Third << "\" " - << "ThirdPos=\"" << (int) ThirdPos << "\" " - << "LabelDistance=\"" << LabelDistance << "\" " - << "LabelPosition=\"" << LabelPosition << "\" " - << "IsDriving=\"" << (int)isDriving << "\" " - << "IsInVirtualSpace=\"" << (int)isInVirtualSpace << "\" " - << "IsActive=\"" << (int)isActive << "\" />" + writer.Stream() << writer.ind() << "Type == InternalAlignment) + writer.Stream() << "InternalAlignmentType=\"" << (int)AlignmentType << "\" " + << "InternalAlignmentIndex=\"" << InternalAlignmentIndex << "\" "; + writer.Stream() << "Value=\"" << Value << "\" " + << "First=\"" << First << "\" " + << "FirstPos=\"" << (int)FirstPos << "\" " + << "Second=\"" << Second << "\" " + << "SecondPos=\"" << (int)SecondPos << "\" " + << "Third=\"" << Third << "\" " + << "ThirdPos=\"" << (int)ThirdPos << "\" " + << "LabelDistance=\"" << LabelDistance << "\" " + << "LabelPosition=\"" << LabelPosition << "\" " + << "IsDriving=\"" << (int)isDriving << "\" " + << "IsInVirtualSpace=\"" << (int)isInVirtualSpace << "\" " + << "IsActive=\"" << (int)isActive << "\" />" - << std::endl; + << std::endl; } -void Constraint::Restore(XMLReader &reader) +void Constraint::Restore(XMLReader& reader) { reader.readElement("Constrain"); - Name = reader.getAttribute("Name"); - Type = static_cast(reader.getAttributeAsInteger("Type")); - Value = reader.getAttributeAsFloat("Value"); - First = reader.getAttributeAsInteger("First"); - FirstPos = static_cast(reader.getAttributeAsInteger("FirstPos")); - Second = reader.getAttributeAsInteger("Second"); + Name = reader.getAttribute("Name"); + Type = static_cast(reader.getAttributeAsInteger("Type")); + Value = reader.getAttributeAsFloat("Value"); + First = reader.getAttributeAsInteger("First"); + FirstPos = static_cast(reader.getAttributeAsInteger("FirstPos")); + Second = reader.getAttributeAsInteger("Second"); SecondPos = static_cast(reader.getAttributeAsInteger("SecondPos")); - if(this->Type==InternalAlignment) { - AlignmentType = static_cast(reader.getAttributeAsInteger("InternalAlignmentType")); + if (this->Type == InternalAlignment) { + AlignmentType = static_cast( + reader.getAttributeAsInteger("InternalAlignmentType")); if (reader.hasAttribute("InternalAlignmentIndex")) InternalAlignmentIndex = reader.getAttributeAsInteger("InternalAlignmentIndex"); @@ -191,7 +190,7 @@ void Constraint::Restore(XMLReader &reader) // read the third geo group if present if (reader.hasAttribute("Third")) { - Third = reader.getAttributeAsInteger("Third"); + Third = reader.getAttributeAsInteger("Third"); ThirdPos = static_cast(reader.getAttributeAsInteger("ThirdPos")); } diff --git a/src/Mod/Sketcher/App/Constraint.h b/src/Mod/Sketcher/App/Constraint.h index c995cb0731..1e53a23ab2 100644 --- a/src/Mod/Sketcher/App/Constraint.h +++ b/src/Mod/Sketcher/App/Constraint.h @@ -36,11 +36,13 @@ namespace Sketcher { /*! - Important note: New constraint types must be always added at the end but before 'NumConstraintTypes'. - This is mandatory in order to keep the handling of constraint types upward compatible which means that - this program version ignores later introduced constraint types when reading them from a project file. + Important note: New constraint types must be always added at the end but before + 'NumConstraintTypes'. This is mandatory in order to keep the handling of constraint types upward + compatible which means that this program version ignores later introduced constraint types when + reading them from a project file. */ -enum ConstraintType : int { +enum ConstraintType : int +{ None = 0, Coincident = 1, Horizontal = 2, @@ -61,26 +63,27 @@ enum ConstraintType : int { Block = 17, Diameter = 18, Weight = 19, - NumConstraintTypes // must be the last item! + NumConstraintTypes// must be the last item! }; -enum InternalAlignmentType { - Undef = 0, - EllipseMajorDiameter = 1, - EllipseMinorDiameter = 2, - EllipseFocus1 = 3, - EllipseFocus2 = 4, - HyperbolaMajor = 5, - HyperbolaMinor = 6, - HyperbolaFocus = 7, - ParabolaFocus = 8, - BSplineControlPoint = 9, - BSplineKnotPoint = 10, - ParabolaFocalAxis = 11, - NumInternalAlignmentType // must be the last item! +enum InternalAlignmentType +{ + Undef = 0, + EllipseMajorDiameter = 1, + EllipseMinorDiameter = 2, + EllipseFocus1 = 3, + EllipseFocus2 = 4, + HyperbolaMajor = 5, + HyperbolaMinor = 6, + HyperbolaFocus = 7, + ParabolaFocus = 8, + BSplineControlPoint = 9, + BSplineKnotPoint = 10, + ParabolaFocalAxis = 11, + NumInternalAlignmentType// must be the last item! }; -class SketcherExport Constraint : public Base::Persistence +class SketcherExport Constraint: public Base::Persistence { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -90,7 +93,7 @@ public: // Constraints objects explicitly not copiable with standard methods // Copy constructor is private for internal use only - Constraint &operator =(const Constraint &a) = delete; + Constraint& operator=(const Constraint& a) = delete; // Constraints objects explicitly not movable Constraint(Constraint&&) = delete; @@ -98,55 +101,92 @@ public: ~Constraint() override = default; - Constraint *clone() const; // does copy the tag, it will be treated as a rename by the expression engine. - Constraint *copy() const; // does not copy the tag, but generates a new one + // does copy the tag, it will be treated as a rename by the expression engine. + Constraint* clone() const; + // does not copy the tag, but generates a new one + Constraint* copy() const; // from base class unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; - PyObject *getPyObject() override; + PyObject* getPyObject() override; Base::Quantity getPresentationValue() const; - inline void setValue(double newValue) { + inline void setValue(double newValue) + { Value = newValue; } - inline double getValue() const { + inline double getValue() const + { return Value; } - inline bool isDimensional() const { - return Type == Distance || Type == DistanceX || Type == DistanceY || - Type == Radius || Type == Diameter || Type == Angle || Type == SnellsLaw || Type == Weight; + inline bool isDimensional() const + { + return Type == Distance || Type == DistanceX || Type == DistanceY || Type == Radius + || Type == Diameter || Type == Angle || Type == SnellsLaw || Type == Weight; } - /// utility function to swap the index in First/Second/Third of the provided constraint from the fromGeoId GeoId to toGeoId + /// utility function to swap the index in First/Second/Third of the provided constraint from the + /// fromGeoId GeoId to toGeoId void substituteIndex(int fromGeoId, int toGeoId); - std::string typeToString() const {return typeToString(Type);} + std::string typeToString() const + { + return typeToString(Type); + } static std::string typeToString(ConstraintType type); - std::string internalAlignmentTypeToString() const {return internalAlignmentTypeToString(AlignmentType);} + std::string internalAlignmentTypeToString() const + { + return internalAlignmentTypeToString(AlignmentType); + } static std::string internalAlignmentTypeToString(InternalAlignmentType alignment); friend class PropertyConstraintList; private: - Constraint(const Constraint&) = default; // only for internal use + Constraint(const Constraint&) = default;// only for internal use private: double Value; - constexpr static std::array type2str { - { "None", "Horizontal", "Vertical","Parallel", "Tangent", "Distance", "DistanceX", "DistanceY", "Angle", "Perpendicular", "Radius", - "Equal", "PointOnObject", "Symmetric", "InternalAlignment", "SnellsLaw", "Block", "Diameter", "Weight"} - }; + constexpr static std::array type2str { + {"None", + "Horizontal", + "Vertical", + "Parallel", + "Tangent", + "Distance", + "DistanceX", + "DistanceY", + "Angle", + "Perpendicular", + "Radius", + "Equal", + "PointOnObject", + "Symmetric", + "InternalAlignment", + "SnellsLaw", + "Block", + "Diameter", + "Weight"}}; - constexpr static std::array internalAlignmentType2str { - { "Undef", "EllipseMajorDiameter", "EllipseMinorDiameter", "EllipseFocus1", "EllipseFocus2", "HyperbolaMajor", "HyperbolaMinor", - "HyperbolaFocus", "ParabolaFocus", "BSplineControlPoint", "BSplineKnotPoint", "ParabolaFocalAxis"} - }; + constexpr static std::array + internalAlignmentType2str {{"Undef", + "EllipseMajorDiameter", + "EllipseMinorDiameter", + "EllipseFocus1", + "EllipseFocus2", + "HyperbolaMajor", + "HyperbolaMinor", + "HyperbolaFocus", + "ParabolaFocus", + "BSplineControlPoint", + "BSplineKnotPoint", + "ParabolaFocalAxis"}}; public: ConstraintType Type; @@ -161,7 +201,9 @@ public: float LabelDistance; float LabelPosition; bool isDriving; - int InternalAlignmentIndex; // Note: for InternalAlignment Type this index indexes equal internal geometry elements (e.g. index of pole in a bspline). It is not a GeoId!! + // Note: for InternalAlignment Type this index indexes equal internal geometry elements (e.g. + // index of pole in a bspline). It is not a GeoId!! + int InternalAlignmentIndex; bool isInVirtualSpace; bool isActive; @@ -170,7 +212,7 @@ protected: boost::uuids::uuid tag; }; -} //namespace Sketcher +}// namespace Sketcher -#endif // SKETCHER_CONSTRAINT_H +#endif// SKETCHER_CONSTRAINT_H diff --git a/src/Mod/Sketcher/App/ConstraintPyImp.cpp b/src/Mod/Sketcher/App/ConstraintPyImp.cpp index 35c9705c54..d3ce49c2db 100644 --- a/src/Mod/Sketcher/App/ConstraintPyImp.cpp +++ b/src/Mod/Sketcher/App/ConstraintPyImp.cpp @@ -22,18 +22,19 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include #include "ConstraintPy.h" + #include "ConstraintPy.cpp" using namespace Sketcher; -PyObject *ConstraintPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ConstraintPy::PyMake(struct _typeobject*, PyObject*, PyObject*)// Python wrapper { // create a new instance of ConstraintPy and the Twin object return new ConstraintPy(new Constraint); @@ -48,17 +49,17 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_Clear(); - char *ConstraintType; - int FirstIndex = GeoEnum::GeoUndef; - int FirstPos = static_cast(PointPos::none); - int SecondIndex= GeoEnum::GeoUndef; - int SecondPos = static_cast(PointPos::none); - int ThirdIndex = GeoEnum::GeoUndef; - int ThirdPos = static_cast(PointPos::none); - double Value = 0; + char* ConstraintType; + int FirstIndex = GeoEnum::GeoUndef; + int FirstPos = static_cast(PointPos::none); + int SecondIndex = GeoEnum::GeoUndef; + int SecondPos = static_cast(PointPos::none); + int ThirdIndex = GeoEnum::GeoUndef; + int ThirdPos = static_cast(PointPos::none); + double Value = 0; int intArg1, intArg2, intArg3, intArg4, intArg5; - // Note: In Python 2.x PyArg_ParseTuple prints a warning if a float is given but an integer is expected. - // This means we must use a PyObject and check afterwards if it's a float or integer. + // Note: In Python 2.x PyArg_ParseTuple prints a warning if a float is given but an integer is + // expected. This means we must use a PyObject and check afterwards if it's a float or integer. PyObject* index_or_value; PyObject* oNumArg4; PyObject* oNumArg5; @@ -66,17 +67,17 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) // ConstraintType, GeoIndex if (PyArg_ParseTuple(args, "si", &ConstraintType, &FirstIndex)) { - if (strcmp("Horizontal",ConstraintType) == 0) { + if (strcmp("Horizontal", ConstraintType) == 0) { this->getConstraintPtr()->Type = Horizontal; this->getConstraintPtr()->First = FirstIndex; return 0; } - else if (strcmp("Vertical",ConstraintType) == 0) { + else if (strcmp("Vertical", ConstraintType) == 0) { this->getConstraintPtr()->Type = Vertical; this->getConstraintPtr()->First = FirstIndex; return 0; } - else if (strcmp("Block",ConstraintType) == 0) { + else if (strcmp("Block", ConstraintType) == 0) { this->getConstraintPtr()->Type = Block; this->getConstraintPtr()->First = FirstIndex; return 0; @@ -89,32 +90,32 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) if (PyLong_Check(index_or_value)) { SecondIndex = PyLong_AsLong(index_or_value); bool valid = false; - if (strcmp("Tangent",ConstraintType) == 0) { + if (strcmp("Tangent", ConstraintType) == 0) { this->getConstraintPtr()->Type = Tangent; valid = true; } - else if (strcmp("Parallel",ConstraintType) == 0) { + else if (strcmp("Parallel", ConstraintType) == 0) { this->getConstraintPtr()->Type = Parallel; valid = true; } - else if (strcmp("Perpendicular",ConstraintType) == 0) { + else if (strcmp("Perpendicular", ConstraintType) == 0) { this->getConstraintPtr()->Type = Perpendicular; valid = true; } - else if (strcmp("Equal",ConstraintType) == 0) { + else if (strcmp("Equal", ConstraintType) == 0) { this->getConstraintPtr()->Type = Equal; valid = true; } - else if (strstr(ConstraintType,"InternalAlignment")) { + else if (strstr(ConstraintType, "InternalAlignment")) { this->getConstraintPtr()->Type = InternalAlignment; valid = true; - if(strstr(ConstraintType,"EllipseMajorDiameter")) - this->getConstraintPtr()->AlignmentType=EllipseMajorDiameter; - else if(strstr(ConstraintType,"EllipseMinorDiameter")) - this->getConstraintPtr()->AlignmentType=EllipseMinorDiameter; + if (strstr(ConstraintType, "EllipseMajorDiameter")) + this->getConstraintPtr()->AlignmentType = EllipseMajorDiameter; + else if (strstr(ConstraintType, "EllipseMinorDiameter")) + this->getConstraintPtr()->AlignmentType = EllipseMinorDiameter; else { - this->getConstraintPtr()->AlignmentType=Undef; + this->getConstraintPtr()->AlignmentType = Undef; valid = false; } } @@ -126,45 +127,46 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) } } // ConstraintType, GeoIndex, Value - if (PyNumber_Check(index_or_value)) { // can be float or int + if (PyNumber_Check(index_or_value)) {// can be float or int Value = PyFloat_AsDouble(index_or_value); bool valid = false; - if (strcmp("Distance",ConstraintType) == 0 ) { + if (strcmp("Distance", ConstraintType) == 0) { this->getConstraintPtr()->Type = Distance; valid = true; } - else if (strcmp("Angle",ConstraintType) == 0 ) { + else if (strcmp("Angle", ConstraintType) == 0) { if (PyObject_TypeCheck(index_or_value, &(Base::QuantityPy::Type))) { - Base::Quantity q = *(static_cast(index_or_value)->getQuantityPtr()); + Base::Quantity q = + *(static_cast(index_or_value)->getQuantityPtr()); if (q.getUnit() == Base::Unit::Angle) Value = q.getValueAs(Base::Quantity::Radian); } this->getConstraintPtr()->Type = Angle; valid = true; } - else if (strcmp("DistanceX",ConstraintType) == 0) { + else if (strcmp("DistanceX", ConstraintType) == 0) { this->getConstraintPtr()->Type = DistanceX; valid = true; } - else if (strcmp("DistanceY",ConstraintType) == 0) { + else if (strcmp("DistanceY", ConstraintType) == 0) { this->getConstraintPtr()->Type = DistanceY; valid = true; } - else if (strcmp("Radius",ConstraintType) == 0) { + else if (strcmp("Radius", ConstraintType) == 0) { this->getConstraintPtr()->Type = Radius; // set a value that is out of range of result of atan2 // this value is handled in ViewProviderSketch this->getConstraintPtr()->LabelPosition = 10; valid = true; } - else if (strcmp("Diameter",ConstraintType) == 0) { + else if (strcmp("Diameter", ConstraintType) == 0) { this->getConstraintPtr()->Type = Diameter; // set a value that is out of range of result of atan2 // this value is handled in ViewProviderSketch this->getConstraintPtr()->LabelPosition = 10; valid = true; } - else if (strcmp("Weight",ConstraintType) == 0) { + else if (strcmp("Weight", ConstraintType) == 0) { this->getConstraintPtr()->Type = Weight; // set a value that is out of range of result of atan2 // this value is handled in ViewProviderSketch @@ -172,7 +174,7 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) valid = true; } if (valid) { - this->getConstraintPtr()->First = FirstIndex; + this->getConstraintPtr()->First = FirstIndex; this->getConstraintPtr()->setValue(Value); return 0; } @@ -198,65 +200,66 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) this->getConstraintPtr()->Type = PointOnObject; valid = true; } - else if (strstr(ConstraintType,"InternalAlignment")) { + else if (strstr(ConstraintType, "InternalAlignment")) { this->getConstraintPtr()->Type = InternalAlignment; valid = true; - if(strstr(ConstraintType,"EllipseFocus1")) - this->getConstraintPtr()->AlignmentType=EllipseFocus1; - else if(strstr(ConstraintType,"EllipseFocus2")) - this->getConstraintPtr()->AlignmentType=EllipseFocus2; + if (strstr(ConstraintType, "EllipseFocus1")) + this->getConstraintPtr()->AlignmentType = EllipseFocus1; + else if (strstr(ConstraintType, "EllipseFocus2")) + this->getConstraintPtr()->AlignmentType = EllipseFocus2; else { - this->getConstraintPtr()->AlignmentType=Undef; + this->getConstraintPtr()->AlignmentType = Undef; valid = false; } } if (valid) { - this->getConstraintPtr()->First = FirstIndex; + this->getConstraintPtr()->First = FirstIndex; this->getConstraintPtr()->FirstPos = static_cast(FirstPos); - this->getConstraintPtr()->Second = SecondIndex; + this->getConstraintPtr()->Second = SecondIndex; return 0; } } // ConstraintType, GeoIndex1, GeoIndex2, Value // ConstraintType, GeoIndex, PosIndex, Value - if (PyNumber_Check(index_or_value)) { // can be float or int + if (PyNumber_Check(index_or_value)) {// can be float or int SecondIndex = any_index; Value = PyFloat_AsDouble(index_or_value); - if (strcmp("Angle",ConstraintType) == 0) { + if (strcmp("Angle", ConstraintType) == 0) { if (PyObject_TypeCheck(index_or_value, &(Base::QuantityPy::Type))) { - Base::Quantity q = *(static_cast(index_or_value)->getQuantityPtr()); + Base::Quantity q = + *(static_cast(index_or_value)->getQuantityPtr()); if (q.getUnit() == Base::Unit::Angle) Value = q.getValueAs(Base::Quantity::Radian); } - this->getConstraintPtr()->Type = Angle; - this->getConstraintPtr()->First = FirstIndex; + this->getConstraintPtr()->Type = Angle; + this->getConstraintPtr()->First = FirstIndex; this->getConstraintPtr()->Second = SecondIndex; this->getConstraintPtr()->setValue(Value); return 0; } - else if (strcmp("Distance",ConstraintType) == 0) { + else if (strcmp("Distance", ConstraintType) == 0) { this->getConstraintPtr()->Type = Distance; this->getConstraintPtr()->First = FirstIndex; this->getConstraintPtr()->Second = SecondIndex; this->getConstraintPtr()->setValue(Value); return 0; } - else if (strcmp("DistanceX",ConstraintType) == 0) { + else if (strcmp("DistanceX", ConstraintType) == 0) { FirstPos = SecondIndex; SecondIndex = -1; this->getConstraintPtr()->Type = DistanceX; - this->getConstraintPtr()->First = FirstIndex; + this->getConstraintPtr()->First = FirstIndex; this->getConstraintPtr()->FirstPos = static_cast(FirstPos); this->getConstraintPtr()->setValue(Value); return 0; } - else if (strcmp("DistanceY",ConstraintType) == 0) { + else if (strcmp("DistanceY", ConstraintType) == 0) { FirstPos = SecondIndex; SecondIndex = -1; this->getConstraintPtr()->Type = DistanceY; - this->getConstraintPtr()->First = FirstIndex; + this->getConstraintPtr()->First = FirstIndex; this->getConstraintPtr()->FirstPos = static_cast(FirstPos); this->getConstraintPtr()->setValue(Value); return 0; @@ -292,68 +295,67 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) } else if (strcmp("TangentViaPoint", ConstraintType) == 0) { this->getConstraintPtr()->Type = Tangent; - //valid = true;//non-standard assignment - this->getConstraintPtr()->First = intArg1; - this->getConstraintPtr()->FirstPos = Sketcher::PointPos::none; - this->getConstraintPtr()->Second = intArg2; + // valid = true;//non-standard assignment + this->getConstraintPtr()->First = intArg1; + this->getConstraintPtr()->FirstPos = Sketcher::PointPos::none; + this->getConstraintPtr()->Second = intArg2; this->getConstraintPtr()->SecondPos = Sketcher::PointPos::none; - this->getConstraintPtr()->Third = intArg3; - this->getConstraintPtr()->ThirdPos = static_cast(intArg4); + this->getConstraintPtr()->Third = intArg3; + this->getConstraintPtr()->ThirdPos = static_cast(intArg4); return 0; } else if (strcmp("PerpendicularViaPoint", ConstraintType) == 0) { this->getConstraintPtr()->Type = Perpendicular; - //valid = true;//non-standard assignment - this->getConstraintPtr()->First = intArg1; - this->getConstraintPtr()->FirstPos = Sketcher::PointPos::none; - this->getConstraintPtr()->Second = intArg2; + // valid = true;//non-standard assignment + this->getConstraintPtr()->First = intArg1; + this->getConstraintPtr()->FirstPos = Sketcher::PointPos::none; + this->getConstraintPtr()->Second = intArg2; this->getConstraintPtr()->SecondPos = Sketcher::PointPos::none; - this->getConstraintPtr()->Third = intArg3; - this->getConstraintPtr()->ThirdPos = static_cast(intArg4); + this->getConstraintPtr()->Third = intArg3; + this->getConstraintPtr()->ThirdPos = static_cast(intArg4); return 0; } - else if (strstr(ConstraintType,"InternalAlignment")) { // InteralAlignment with InternalElementIndex argument + else if (strstr(ConstraintType, "InternalAlignment")) {// InteralAlignment with + // InternalElementIndex argument this->getConstraintPtr()->Type = InternalAlignment; valid = true; - if (strstr(ConstraintType,"BSplineControlPoint")) { - this->getConstraintPtr()->AlignmentType=BSplineControlPoint; + if (strstr(ConstraintType, "BSplineControlPoint")) { + this->getConstraintPtr()->AlignmentType = BSplineControlPoint; } - else if (strstr(ConstraintType,"BSplineKnotPoint")) { - this->getConstraintPtr()->AlignmentType=BSplineKnotPoint; + else if (strstr(ConstraintType, "BSplineKnotPoint")) { + this->getConstraintPtr()->AlignmentType = BSplineKnotPoint; } - else - { - this->getConstraintPtr()->AlignmentType=Undef; + else { + this->getConstraintPtr()->AlignmentType = Undef; valid = false; } if (valid) { - this->getConstraintPtr()->First = intArg1; - this->getConstraintPtr()->FirstPos = static_cast(intArg2); - this->getConstraintPtr()->Second = intArg3; + this->getConstraintPtr()->First = intArg1; + this->getConstraintPtr()->FirstPos = static_cast(intArg2); + this->getConstraintPtr()->Second = intArg3; this->getConstraintPtr()->InternalAlignmentIndex = intArg4; return 0; } - } if (valid) { - this->getConstraintPtr()->First = intArg1; - this->getConstraintPtr()->FirstPos = static_cast(intArg2); - this->getConstraintPtr()->Second = intArg3; + this->getConstraintPtr()->First = intArg1; + this->getConstraintPtr()->FirstPos = static_cast(intArg2); + this->getConstraintPtr()->Second = intArg3; this->getConstraintPtr()->SecondPos = static_cast(intArg4); return 0; } } // ConstraintType, GeoIndex1, PosIndex1, GeoIndex2, Value - if (PyNumber_Check(oNumArg4)) { // can be float or int + if (PyNumber_Check(oNumArg4)) {// can be float or int Value = PyFloat_AsDouble(oNumArg4); - if (strcmp("Distance",ConstraintType) == 0 ) { + if (strcmp("Distance", ConstraintType) == 0) { this->getConstraintPtr()->Type = Distance; - this->getConstraintPtr()->First = intArg1; + this->getConstraintPtr()->First = intArg1; this->getConstraintPtr()->FirstPos = static_cast(intArg2); - this->getConstraintPtr()->Second = intArg3; + this->getConstraintPtr()->Second = intArg3; this->getConstraintPtr()->setValue(Value); return 0; } @@ -361,66 +363,69 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - if (PyArg_ParseTuple(args, "siiiiO", &ConstraintType, &intArg1, &intArg2, &intArg3, &intArg4, &oNumArg5)) { + if (PyArg_ParseTuple( + args, "siiiiO", &ConstraintType, &intArg1, &intArg2, &intArg3, &intArg4, &oNumArg5)) { // ConstraintType, GeoIndex1, PosIndex1, GeoIndex2, PosIndex2, GeoIndex3 if (PyLong_Check(oNumArg5)) { intArg5 = PyLong_AsLong(oNumArg5); - if (strcmp("Symmetric",ConstraintType) == 0 ) { + if (strcmp("Symmetric", ConstraintType) == 0) { this->getConstraintPtr()->Type = Symmetric; - this->getConstraintPtr()->First = intArg1; - this->getConstraintPtr()->FirstPos = static_cast(intArg2); - this->getConstraintPtr()->Second = intArg3; + this->getConstraintPtr()->First = intArg1; + this->getConstraintPtr()->FirstPos = static_cast(intArg2); + this->getConstraintPtr()->Second = intArg3; this->getConstraintPtr()->SecondPos = static_cast(intArg4); - this->getConstraintPtr()->Third = intArg5; + this->getConstraintPtr()->Third = intArg5; return 0; } } // ConstraintType, GeoIndex1, PosIndex1, GeoIndex2, PosIndex2, Value - if (PyNumber_Check(oNumArg5)) { // can be float or int + if (PyNumber_Check(oNumArg5)) {// can be float or int Value = PyFloat_AsDouble(oNumArg5); - bool valid=false; - if (strcmp("Distance",ConstraintType) == 0 ) { + bool valid = false; + if (strcmp("Distance", ConstraintType) == 0) { this->getConstraintPtr()->Type = Distance; valid = true; } - else if (strcmp("DistanceX",ConstraintType) == 0) { + else if (strcmp("DistanceX", ConstraintType) == 0) { this->getConstraintPtr()->Type = DistanceX; valid = true; } - else if (strcmp("DistanceY",ConstraintType) == 0) { + else if (strcmp("DistanceY", ConstraintType) == 0) { this->getConstraintPtr()->Type = DistanceY; valid = true; } - else if (strcmp("Angle",ConstraintType) == 0 ) { + else if (strcmp("Angle", ConstraintType) == 0) { if (PyObject_TypeCheck(oNumArg5, &(Base::QuantityPy::Type))) { - Base::Quantity q = *(static_cast(oNumArg5)->getQuantityPtr()); + Base::Quantity q = + *(static_cast(oNumArg5)->getQuantityPtr()); if (q.getUnit() == Base::Unit::Angle) Value = q.getValueAs(Base::Quantity::Radian); } this->getConstraintPtr()->Type = Angle; valid = true; } - else if (strcmp("AngleViaPoint",ConstraintType) == 0 ) { + else if (strcmp("AngleViaPoint", ConstraintType) == 0) { if (PyObject_TypeCheck(oNumArg5, &(Base::QuantityPy::Type))) { - Base::Quantity q = *(static_cast(oNumArg5)->getQuantityPtr()); + Base::Quantity q = + *(static_cast(oNumArg5)->getQuantityPtr()); if (q.getUnit() == Base::Unit::Angle) Value = q.getValueAs(Base::Quantity::Radian); } this->getConstraintPtr()->Type = Angle; - //valid = true;//non-standard assignment - this->getConstraintPtr()->First = intArg1; - this->getConstraintPtr()->FirstPos = Sketcher::PointPos::none; - this->getConstraintPtr()->Second = intArg2; //let's goof up all the terminology =) + // valid = true;//non-standard assignment + this->getConstraintPtr()->First = intArg1; + this->getConstraintPtr()->FirstPos = Sketcher::PointPos::none; + this->getConstraintPtr()->Second = intArg2;// let's goof up all the terminology =) this->getConstraintPtr()->SecondPos = Sketcher::PointPos::none; - this->getConstraintPtr()->Third = intArg3; - this->getConstraintPtr()->ThirdPos = static_cast(intArg4); + this->getConstraintPtr()->Third = intArg3; + this->getConstraintPtr()->ThirdPos = static_cast(intArg4); this->getConstraintPtr()->setValue(Value); return 0; } if (valid) { - this->getConstraintPtr()->First = intArg1; - this->getConstraintPtr()->FirstPos = static_cast(intArg2); - this->getConstraintPtr()->Second = intArg3; + this->getConstraintPtr()->First = intArg1; + this->getConstraintPtr()->FirstPos = static_cast(intArg2); + this->getConstraintPtr()->Second = intArg3; this->getConstraintPtr()->SecondPos = static_cast(intArg4); this->getConstraintPtr()->setValue(Value); return 0; @@ -429,31 +434,39 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - if (PyArg_ParseTuple(args, "siiiiiO", &ConstraintType, &FirstIndex, &FirstPos, &SecondIndex, &SecondPos, &ThirdIndex, &index_or_value)) { + if (PyArg_ParseTuple(args, + "siiiiiO", + &ConstraintType, + &FirstIndex, + &FirstPos, + &SecondIndex, + &SecondPos, + &ThirdIndex, + &index_or_value)) { if (PyLong_Check(index_or_value)) { ThirdPos = PyLong_AsLong(index_or_value); // ConstraintType, GeoIndex1, PosIndex1, GeoIndex2, PosIndex2, GeoIndex3, PosIndex3 - if (strcmp("Symmetric",ConstraintType) == 0 ) { + if (strcmp("Symmetric", ConstraintType) == 0) { this->getConstraintPtr()->Type = Symmetric; - this->getConstraintPtr()->First = FirstIndex; - this->getConstraintPtr()->FirstPos = static_cast(FirstPos); - this->getConstraintPtr()->Second = SecondIndex; + this->getConstraintPtr()->First = FirstIndex; + this->getConstraintPtr()->FirstPos = static_cast(FirstPos); + this->getConstraintPtr()->Second = SecondIndex; this->getConstraintPtr()->SecondPos = static_cast(SecondPos); - this->getConstraintPtr()->Third = ThirdIndex; - this->getConstraintPtr()->ThirdPos = static_cast(ThirdPos); + this->getConstraintPtr()->Third = ThirdIndex; + this->getConstraintPtr()->ThirdPos = static_cast(ThirdPos); return 0; } } - if (PyNumber_Check(index_or_value)) { // can be float or int + if (PyNumber_Check(index_or_value)) {// can be float or int Value = PyFloat_AsDouble(index_or_value); - if (strcmp("SnellsLaw",ConstraintType) == 0 ) { + if (strcmp("SnellsLaw", ConstraintType) == 0) { this->getConstraintPtr()->Type = SnellsLaw; - this->getConstraintPtr()->First = FirstIndex; - this->getConstraintPtr()->FirstPos = static_cast(FirstPos); - this->getConstraintPtr()->Second = SecondIndex; + this->getConstraintPtr()->First = FirstIndex; + this->getConstraintPtr()->FirstPos = static_cast(FirstPos); + this->getConstraintPtr()->Second = SecondIndex; this->getConstraintPtr()->SecondPos = static_cast(SecondPos); - this->getConstraintPtr()->Third = ThirdIndex; - this->getConstraintPtr()->ThirdPos = Sketcher::PointPos::none; + this->getConstraintPtr()->Third = ThirdIndex; + this->getConstraintPtr()->ThirdPos = Sketcher::PointPos::none; this->getConstraintPtr()->setValue(Value); return 0; } @@ -476,81 +489,171 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) std::string ConstraintPy::representation() const { std::stringstream result; - result << "getConstraintPtr()->Type) { - case None : result << "'None'>";break; - case DistanceX : result << "'DistanceX'>";break; - case DistanceY : result << "'DistanceY'>";break; - case Coincident : result << "'Coincident'>";break; - case Horizontal : result << "'Horizontal' (" << getConstraintPtr()->First << ")>";break; - case Vertical : result << "'Vertical' (" << getConstraintPtr()->First << ")>";break; - case Block : result << "'Block' (" << getConstraintPtr()->First << ")>";break; - case Radius : result << "'Radius'>";break; - case Diameter : result << "'Diameter'>";break; - case Weight : result << "'Weight'>";break; - case Parallel : result << "'Parallel'>";break; - case Tangent : + result << "getConstraintPtr()->Type) { + case None: + result << "'None'>"; + break; + case DistanceX: + result << "'DistanceX'>"; + break; + case DistanceY: + result << "'DistanceY'>"; + break; + case Coincident: + result << "'Coincident'>"; + break; + case Horizontal: + result << "'Horizontal' (" << getConstraintPtr()->First << ")>"; + break; + case Vertical: + result << "'Vertical' (" << getConstraintPtr()->First << ")>"; + break; + case Block: + result << "'Block' (" << getConstraintPtr()->First << ")>"; + break; + case Radius: + result << "'Radius'>"; + break; + case Diameter: + result << "'Diameter'>"; + break; + case Weight: + result << "'Weight'>"; + break; + case Parallel: + result << "'Parallel'>"; + break; + case Tangent: if (this->getConstraintPtr()->Third == GeoEnum::GeoUndef) result << "'Tangent'>"; else result << "'TangentViaPoint'>"; - break; - case Perpendicular : + break; + case Perpendicular: if (this->getConstraintPtr()->Third == GeoEnum::GeoUndef) result << "'Perpendicular'>"; else result << "'PerpendicularViaPoint'>"; - break; - case Distance : result << "'Distance'>";break; - case Angle : + break; + case Distance: + result << "'Distance'>"; + break; + case Angle: if (this->getConstraintPtr()->Third == GeoEnum::GeoUndef) result << "'Angle'>"; else result << "'AngleViaPoint'>"; - break; - case Symmetric : result << "'Symmetric'>"; break; - case SnellsLaw : result << "'SnellsLaw'>"; break; - case InternalAlignment : - switch(this->getConstraintPtr()->AlignmentType) { - case Undef : result << "'InternalAlignment:Undef'>";break; - case EllipseMajorDiameter : result << "'InternalAlignment:EllipseMajorDiameter'>";break; - case EllipseMinorDiameter : result << "'InternalAlignment:EllipseMinorDiameter'>";break; - case EllipseFocus1 : result << "'InternalAlignment:EllipseFocus1'>";break; - case EllipseFocus2 : result << "'InternalAlignment:EllipseFocus2'>";break; - default : result << "'InternalAlignment:?'>";break; + break; + case Symmetric: + result << "'Symmetric'>"; + break; + case SnellsLaw: + result << "'SnellsLaw'>"; + break; + case InternalAlignment: + switch (this->getConstraintPtr()->AlignmentType) { + case Undef: + result << "'InternalAlignment:Undef'>"; + break; + case EllipseMajorDiameter: + result << "'InternalAlignment:EllipseMajorDiameter'>"; + break; + case EllipseMinorDiameter: + result << "'InternalAlignment:EllipseMinorDiameter'>"; + break; + case EllipseFocus1: + result << "'InternalAlignment:EllipseFocus1'>"; + break; + case EllipseFocus2: + result << "'InternalAlignment:EllipseFocus2'>"; + break; + default: + result << "'InternalAlignment:?'>"; + break; } - break; - case Equal : result << "'Equal' (" << getConstraintPtr()->First << "," << getConstraintPtr()->Second << ")>";break; - case PointOnObject : result << "'PointOnObject' (" << getConstraintPtr()->First << "," << getConstraintPtr()->Second << ")>";break; - default : result << "'?'>";break; + break; + case Equal: + result << "'Equal' (" << getConstraintPtr()->First << "," << getConstraintPtr()->Second + << ")>"; + break; + case PointOnObject: + result << "'PointOnObject' (" << getConstraintPtr()->First << "," + << getConstraintPtr()->Second << ")>"; + break; + default: + result << "'?'>"; + break; } return result.str(); } Py::String ConstraintPy::getType() const { - switch(this->getConstraintPtr()->Type) { - case None : return Py::String("None");break; - case DistanceX : return Py::String("DistanceX");break; - case DistanceY : return Py::String("DistanceY");break; - case Coincident : return Py::String("Coincident");break; - case Horizontal : return Py::String("Horizontal");break; - case Vertical : return Py::String("Vertical");break; - case Block : return Py::String("Block");break; - case Radius : return Py::String("Radius");break; - case Diameter : return Py::String("Diameter");break; - case Weight : return Py::String("Weight");break; - case Parallel : return Py::String("Parallel");break; - case Tangent : return Py::String("Tangent");break; - case Perpendicular : return Py::String("Perpendicular");break; - case Distance : return Py::String("Distance");break; - case Angle : return Py::String("Angle");break; - case Symmetric : return Py::String("Symmetric"); break; - case SnellsLaw : return Py::String("SnellsLaw"); break; - case InternalAlignment : return Py::String("InternalAlignment"); break; - case Equal : return Py::String("Equal"); break; - case PointOnObject : return Py::String("PointOnObject"); break; - default : return Py::String("Undefined");break; + switch (this->getConstraintPtr()->Type) { + case None: + return Py::String("None"); + break; + case DistanceX: + return Py::String("DistanceX"); + break; + case DistanceY: + return Py::String("DistanceY"); + break; + case Coincident: + return Py::String("Coincident"); + break; + case Horizontal: + return Py::String("Horizontal"); + break; + case Vertical: + return Py::String("Vertical"); + break; + case Block: + return Py::String("Block"); + break; + case Radius: + return Py::String("Radius"); + break; + case Diameter: + return Py::String("Diameter"); + break; + case Weight: + return Py::String("Weight"); + break; + case Parallel: + return Py::String("Parallel"); + break; + case Tangent: + return Py::String("Tangent"); + break; + case Perpendicular: + return Py::String("Perpendicular"); + break; + case Distance: + return Py::String("Distance"); + break; + case Angle: + return Py::String("Angle"); + break; + case Symmetric: + return Py::String("Symmetric"); + break; + case SnellsLaw: + return Py::String("SnellsLaw"); + break; + case InternalAlignment: + return Py::String("InternalAlignment"); + break; + case Equal: + return Py::String("Equal"); + break; + case PointOnObject: + return Py::String("PointOnObject"); + break; + default: + return Py::String("Undefined"); + break; } } @@ -559,7 +662,7 @@ Py::Long ConstraintPy::getFirst() const return Py::Long(this->getConstraintPtr()->First); } -void ConstraintPy::setFirst(Py::Long arg) +void ConstraintPy::setFirst(Py::Long arg) { this->getConstraintPtr()->First = arg; } @@ -573,7 +676,8 @@ void ConstraintPy::setFirstPos(Py::Long arg) { int pos = arg; - if(pos>=static_cast(Sketcher::PointPos::none) && pos<=static_cast(Sketcher::PointPos::mid)) { + if (pos >= static_cast(Sketcher::PointPos::none) + && pos <= static_cast(Sketcher::PointPos::mid)) { this->getConstraintPtr()->FirstPos = static_cast(pos); } else { @@ -589,7 +693,7 @@ Py::Long ConstraintPy::getSecond() const return Py::Long(this->getConstraintPtr()->Second); } -void ConstraintPy::setSecond(Py::Long arg) +void ConstraintPy::setSecond(Py::Long arg) { this->getConstraintPtr()->Second = arg; } @@ -603,7 +707,8 @@ void ConstraintPy::setSecondPos(Py::Long arg) { int pos = arg; - if(pos>=static_cast(Sketcher::PointPos::none) && pos<=static_cast(Sketcher::PointPos::mid)) { + if (pos >= static_cast(Sketcher::PointPos::none) + && pos <= static_cast(Sketcher::PointPos::mid)) { this->getConstraintPtr()->SecondPos = static_cast(pos); } else { @@ -619,7 +724,7 @@ Py::Long ConstraintPy::getThird() const return Py::Long(this->getConstraintPtr()->Third); } -void ConstraintPy::setThird(Py::Long arg) +void ConstraintPy::setThird(Py::Long arg) { this->getConstraintPtr()->Third = arg; } @@ -633,7 +738,8 @@ void ConstraintPy::setThirdPos(Py::Long arg) { int pos = arg; - if(pos>=static_cast(Sketcher::PointPos::none) && pos<=static_cast(Sketcher::PointPos::mid)) { + if (pos >= static_cast(Sketcher::PointPos::none) + && pos <= static_cast(Sketcher::PointPos::mid)) { this->getConstraintPtr()->ThirdPos = static_cast(pos); } else { @@ -649,7 +755,7 @@ Py::String ConstraintPy::getName() const return Py::String(this->getConstraintPtr()->Name); } -void ConstraintPy::setName(Py::String arg) +void ConstraintPy::setName(Py::String arg) { this->getConstraintPtr()->Name = arg; } @@ -674,7 +780,7 @@ Py::Boolean ConstraintPy::getIsActive() const return Py::Boolean(this->getConstraintPtr()->isActive); } -PyObject *ConstraintPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ConstraintPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Sketcher/App/ExternalGeometryExtension.cpp b/src/Mod/Sketcher/App/ExternalGeometryExtension.cpp index 9f1daea08c..cbc5eed357 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryExtension.cpp +++ b/src/Mod/Sketcher/App/ExternalGeometryExtension.cpp @@ -33,19 +33,20 @@ using namespace Sketcher; //---------- Geometry Extension -constexpr std::array ExternalGeometryExtension::flag2str; +constexpr std::array + ExternalGeometryExtension::flag2str; -TYPESYSTEM_SOURCE(Sketcher::ExternalGeometryExtension,Part::GeometryPersistenceExtension) +TYPESYSTEM_SOURCE(Sketcher::ExternalGeometryExtension, Part::GeometryPersistenceExtension) -void ExternalGeometryExtension::copyAttributes(Part::GeometryExtension * cpy) const +void ExternalGeometryExtension::copyAttributes(Part::GeometryExtension* cpy) const { Part::GeometryPersistenceExtension::copyAttributes(cpy); - static_cast(cpy)->Ref = this->Ref; - static_cast(cpy)->Flags = this->Flags; + static_cast(cpy)->Ref = this->Ref; + static_cast(cpy)->Flags = this->Flags; } -void ExternalGeometryExtension::restoreAttributes(Base::XMLReader &reader) +void ExternalGeometryExtension::restoreAttributes(Base::XMLReader& reader) { Part::GeometryPersistenceExtension::restoreAttributes(reader); @@ -53,12 +54,11 @@ void ExternalGeometryExtension::restoreAttributes(Base::XMLReader &reader) Flags = FlagType(reader.getAttribute("Flags")); } -void ExternalGeometryExtension::saveAttributes(Base::Writer &writer) const +void ExternalGeometryExtension::saveAttributes(Base::Writer& writer) const { Part::GeometryPersistenceExtension::saveAttributes(writer); - writer.Stream() << "\" Ref=\"" << Ref - << "\" Flags=\"" << Flags.to_string(); + writer.Stream() << "\" Ref=\"" << Ref << "\" Flags=\"" << Flags.to_string(); } std::unique_ptr ExternalGeometryExtension::copy() const @@ -67,32 +67,32 @@ std::unique_ptr ExternalGeometryExtension::copy() const copyAttributes(cpy.get()); -#if defined (__GNUC__) && (__GNUC__ <=4) +#if defined(__GNUC__) && (__GNUC__ <= 4) return std::move(cpy); #else return cpy; #endif } -PyObject * ExternalGeometryExtension::getPyObject() +PyObject* ExternalGeometryExtension::getPyObject() { return new ExternalGeometryExtensionPy(new ExternalGeometryExtension(*this)); } -bool ExternalGeometryExtension::getFlagsFromName(std::string str, ExternalGeometryExtension::Flag &flag) +bool ExternalGeometryExtension::getFlagsFromName(std::string str, + ExternalGeometryExtension::Flag& flag) { - auto pos = std::find_if( ExternalGeometryExtension::flag2str.begin(), - ExternalGeometryExtension::flag2str.end(), - [str](const char * val) { - return strcmp(val,str.c_str())==0; - } - ); + auto pos = std::find_if(ExternalGeometryExtension::flag2str.begin(), + ExternalGeometryExtension::flag2str.end(), + [str](const char* val) { + return strcmp(val, str.c_str()) == 0; + }); - if( pos != ExternalGeometryExtension::flag2str.end()) { - int index = std::distance( ExternalGeometryExtension::flag2str.begin(), pos ); + if (pos != ExternalGeometryExtension::flag2str.end()) { + int index = std::distance(ExternalGeometryExtension::flag2str.begin(), pos); - flag = static_cast(index); - return true; + flag = static_cast(index); + return true; } return false; diff --git a/src/Mod/Sketcher/App/ExternalGeometryExtension.h b/src/Mod/Sketcher/App/ExternalGeometryExtension.h index 077c10e0cf..be0998fe49 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryExtension.h +++ b/src/Mod/Sketcher/App/ExternalGeometryExtension.h @@ -37,75 +37,103 @@ class ISketchExternalGeometryExtension { public: // Identification information - // START_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) + // START_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) + // virtual bool testFlag(int flag) const = 0; - virtual void setFlag(int flag, bool v=true) = 0; - // END_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) + virtual void setFlag(int flag, bool v = true) = 0; + // END_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) + // virtual bool isClear() const = 0; virtual size_t flagSize() const = 0; virtual const std::string& getRef() const = 0; - virtual void setRef(const std::string & ref) = 0; + virtual void setRef(const std::string& ref) = 0; }; -class SketcherExport ExternalGeometryExtension : public Part::GeometryPersistenceExtension, private ISketchExternalGeometryExtension +class SketcherExport ExternalGeometryExtension: public Part::GeometryPersistenceExtension, + private ISketchExternalGeometryExtension { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: - // START_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) - enum Flag { - Defining = 0, // allow an external geometry to build shape - Frozen = 1, // freeze an external geometry - Detached = 2, // signal the intentions of detaching the geometry from external reference - Missing = 3, // geometry with missing external reference - Sync = 4, // signal the intention to synchronize a frozen geometry - NumFlags // Must be the last type + // START_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) + // + enum Flag + { + Defining = 0,// allow an external geometry to build shape + Frozen = 1, // freeze an external geometry + Detached = 2,// signal the intentions of detaching the geometry from external reference + Missing = 3, // geometry with missing external reference + Sync = 4, // signal the intention to synchronize a frozen geometry + NumFlags // Must be the last type }; - // END_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) + // END_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) + // + + constexpr static std::array flag2str { + {"Defining", "Frozen", "Detached", "Missing", "Sync"}}; - constexpr static std::array flag2str {{ "Defining", "Frozen", "Detached","Missing", "Sync" }}; public: - ExternalGeometryExtension() = default; ~ExternalGeometryExtension() override = default; std::unique_ptr copy() const override; - PyObject *getPyObject() override; + PyObject* getPyObject() override; - // START_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) - bool testFlag(int flag) const override { return Flags.test((size_t)(flag)); } - void setFlag(int flag, bool v=true) override { Flags.set((size_t)(flag),v); } - // END_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) + // START_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) + // + bool testFlag(int flag) const override + { + return Flags.test((size_t)(flag)); + } + void setFlag(int flag, bool v = true) override + { + Flags.set((size_t)(flag), v); + } + // END_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) + // - bool isClear() const override {return Flags.none();} - size_t flagSize() const override {return Flags.size();} + bool isClear() const override + { + return Flags.none(); + } + size_t flagSize() const override + { + return Flags.size(); + } - const std::string& getRef() const override {return Ref;} - void setRef(const std::string & ref) override {Ref = ref;} + const std::string& getRef() const override + { + return Ref; + } + void setRef(const std::string& ref) override + { + Ref = ref; + } - static bool getFlagsFromName(std::string str, ExternalGeometryExtension::Flag &flag); + static bool getFlagsFromName(std::string str, ExternalGeometryExtension::Flag& flag); protected: - void copyAttributes(Part::GeometryExtension * cpy) const override; - void restoreAttributes(Base::XMLReader &reader) override; - void saveAttributes(Base::Writer &writer) const override; + void copyAttributes(Part::GeometryExtension* cpy) const override; + void restoreAttributes(Base::XMLReader& reader) override; + void saveAttributes(Base::Writer& writer) const override; private: ExternalGeometryExtension(const ExternalGeometryExtension&) = default; private: using FlagType = std::bitset<32>; - // START_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) + // START_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) + // std::string Ref; FlagType Flags; - // END_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) - - + // END_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) + // }; -} //namespace Sketcher +}// namespace Sketcher -#endif // SKETCHER_EXTERNALGEOMETRYEXTENSION_H +#endif// SKETCHER_EXTERNALGEOMETRYEXTENSION_H diff --git a/src/Mod/Sketcher/App/ExternalGeometryExtensionPyImp.cpp b/src/Mod/Sketcher/App/ExternalGeometryExtensionPyImp.cpp index 1d3cd764b5..5e28b559f7 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryExtensionPyImp.cpp +++ b/src/Mod/Sketcher/App/ExternalGeometryExtensionPyImp.cpp @@ -23,6 +23,7 @@ #include "PreCompiled.h" #include "ExternalGeometryExtensionPy.h" + #include "ExternalGeometryExtensionPy.cpp" @@ -36,23 +37,22 @@ std::string ExternalGeometryExtensionPy::representation() const std::string ref = getExternalGeometryExtensionPtr()->getRef(); - str << "getName().empty()) + if (!getExternalGeometryExtensionPtr()->getName().empty()) str << "\'" << getExternalGeometryExtensionPtr()->getName() << "\', "; str << "\"" << ref; - if(!getExternalGeometryExtensionPtr()->isClear()) { - str<< "\",{"; + if (!getExternalGeometryExtensionPtr()->isClear()) { + str << "\",{"; - bool first=true; + bool first = true; - for(size_t i=0;itestFlag(i)) { - if(first) { - first=false; + for (size_t i = 0; i < ExternalGeometryExtension::NumFlags; i++) { + if (getExternalGeometryExtensionPtr()->testFlag(i)) { + if (first) { + first = false; } else { str << ", "; @@ -62,7 +62,7 @@ std::string ExternalGeometryExtensionPy::representation() const } } - str<< "}"; + str << "}"; } else { str << "\") >"; @@ -73,7 +73,8 @@ std::string ExternalGeometryExtensionPy::representation() const return str.str(); } -PyObject *ExternalGeometryExtensionPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +// Python wrapper +PyObject* ExternalGeometryExtensionPy::PyMake(struct _typeobject*, PyObject*, PyObject*) { // create a new instance of PointPy and the Twin object return new ExternalGeometryExtensionPy(new ExternalGeometryExtension); @@ -88,39 +89,40 @@ int ExternalGeometryExtensionPy::PyInit(PyObject* args, PyObject* /*kwd*/) return 0; } - PyErr_SetString(PyExc_TypeError, "ExternalGeometryExtension constructor accepts:\n" - "-- empty parameter list\n"); + PyErr_SetString(PyExc_TypeError, + "ExternalGeometryExtension constructor accepts:\n" + "-- empty parameter list\n"); return -1; } -PyObject* ExternalGeometryExtensionPy::testFlag(PyObject *args) +PyObject* ExternalGeometryExtensionPy::testFlag(PyObject* args) { char* flag; - if (PyArg_ParseTuple(args, "s",&flag)) { + if (PyArg_ParseTuple(args, "s", &flag)) { ExternalGeometryExtension::Flag flagtype; - if(getExternalGeometryExtensionPtr()->getFlagsFromName(flag, flagtype)) - return new_reference_to(Py::Boolean(this->getExternalGeometryExtensionPtr()->testFlag(flagtype))); + if (getExternalGeometryExtensionPtr()->getFlagsFromName(flag, flagtype)) + return new_reference_to( + Py::Boolean(this->getExternalGeometryExtensionPtr()->testFlag(flagtype))); PyErr_SetString(PyExc_TypeError, "Flag string does not exist."); return nullptr; - } PyErr_SetString(PyExc_TypeError, "No flag string provided."); return nullptr; } -PyObject* ExternalGeometryExtensionPy::setFlag(PyObject *args) +PyObject* ExternalGeometryExtensionPy::setFlag(PyObject* args) { - char * flag; - PyObject * bflag = Py_True; + char* flag; + PyObject* bflag = Py_True; if (PyArg_ParseTuple(args, "s|O!", &flag, &PyBool_Type, &bflag)) { ExternalGeometryExtension::Flag flagtype; - if(getExternalGeometryExtensionPtr()->getFlagsFromName(flag, flagtype)) { + if (getExternalGeometryExtensionPtr()->getFlagsFromName(flag, flagtype)) { this->getExternalGeometryExtensionPtr()->setFlag(flagtype, Base::asBoolean(bflag)); Py_Return; @@ -145,7 +147,7 @@ void ExternalGeometryExtensionPy::setRef(Py::String value) } -PyObject *ExternalGeometryExtensionPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ExternalGeometryExtensionPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Sketcher/App/ExternalGeometryFacade.cpp b/src/Mod/Sketcher/App/ExternalGeometryFacade.cpp index e557399ff2..6149f72113 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryFacade.cpp +++ b/src/Mod/Sketcher/App/ExternalGeometryFacade.cpp @@ -22,7 +22,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include @@ -33,43 +33,45 @@ using namespace Sketcher; -TYPESYSTEM_SOURCE(Sketcher::ExternalGeometryFacade,Base::BaseClass) +TYPESYSTEM_SOURCE(Sketcher::ExternalGeometryFacade, Base::BaseClass) -ExternalGeometryFacade::ExternalGeometryFacade(): Geo(nullptr), SketchGeoExtension(nullptr), ExternalGeoExtension(nullptr) +ExternalGeometryFacade::ExternalGeometryFacade() + : Geo(nullptr), + SketchGeoExtension(nullptr), + ExternalGeoExtension(nullptr) +{} + +ExternalGeometryFacade::ExternalGeometryFacade(const Part::Geometry* geometry) + : Geo(geometry) { - -} - -ExternalGeometryFacade::ExternalGeometryFacade(const Part::Geometry * geometry) -: Geo(geometry) -{ - if(geometry) + if (geometry) initExtensions(); else THROWM(Base::ValueError, "ExternalGeometryFacade initialized with Geometry null pointer"); } -std::unique_ptr ExternalGeometryFacade::getFacade(Part::Geometry * geometry) +std::unique_ptr ExternalGeometryFacade::getFacade(Part::Geometry* geometry) { - if(geometry) + if (geometry) return std::unique_ptr(new ExternalGeometryFacade(geometry)); - else + else return std::unique_ptr(nullptr); } -std::unique_ptr ExternalGeometryFacade::getFacade(const Part::Geometry * geometry) +std::unique_ptr +ExternalGeometryFacade::getFacade(const Part::Geometry* geometry) { - if(geometry) + if (geometry) return std::unique_ptr(new ExternalGeometryFacade(geometry)); - else + else return std::unique_ptr(nullptr); } -void ExternalGeometryFacade::setGeometry(Part::Geometry *geometry) +void ExternalGeometryFacade::setGeometry(Part::Geometry* geometry) { Geo = geometry; - if(geometry) + if (geometry) initExtensions(); else THROWM(Base::ValueError, "ExternalGeometryFacade initialized with Geometry null pointer"); @@ -77,67 +79,72 @@ void ExternalGeometryFacade::setGeometry(Part::Geometry *geometry) void ExternalGeometryFacade::initExtensions() { - if(!Geo->hasExtension(SketchGeometryExtension::getClassTypeId())) { + if (!Geo->hasExtension(SketchGeometryExtension::getClassTypeId())) { - getGeo()->setExtension(std::make_unique()); // Create getExtension + getGeo()->setExtension(std::make_unique());// Create getExtension - Base::Console().Warning("%s\nSketcher External Geometry without Geometry Extension: %s \n", boost::uuids::to_string(Geo->getTag()).c_str()); + Base::Console().Warning("%s\nSketcher External Geometry without Geometry Extension: %s \n", + boost::uuids::to_string(Geo->getTag()).c_str()); } - if(!Geo->hasExtension(ExternalGeometryExtension::getClassTypeId())) { + if (!Geo->hasExtension(ExternalGeometryExtension::getClassTypeId())) { - getGeo()->setExtension(std::make_unique()); // Create getExtension + getGeo()->setExtension(std::make_unique());// Create getExtension - Base::Console().Warning("%s\nSketcher External Geometry without ExternalGeometryExtension: %s \n", boost::uuids::to_string(Geo->getTag()).c_str()); + Base::Console().Warning( + "%s\nSketcher External Geometry without ExternalGeometryExtension: %s \n", + boost::uuids::to_string(Geo->getTag()).c_str()); } - SketchGeoExtension = - std::static_pointer_cast( - (Geo->getExtension(SketchGeometryExtension::getClassTypeId())).lock() - ); + SketchGeoExtension = std::static_pointer_cast( + (Geo->getExtension(SketchGeometryExtension::getClassTypeId())).lock()); - ExternalGeoExtension = - std::static_pointer_cast( - (Geo->getExtension(ExternalGeometryExtension::getClassTypeId())).lock() - ); + ExternalGeoExtension = std::static_pointer_cast( + (Geo->getExtension(ExternalGeometryExtension::getClassTypeId())).lock()); } void ExternalGeometryFacade::initExtensions() const { - if(!Geo->hasExtension(SketchGeometryExtension::getClassTypeId())) - THROWM(Base::ValueError, "ExternalGeometryFacade for const::Geometry without SketchGeometryExtension"); + if (!Geo->hasExtension(SketchGeometryExtension::getClassTypeId())) + THROWM(Base::ValueError, + "ExternalGeometryFacade for const::Geometry without SketchGeometryExtension"); - if(!Geo->hasExtension(ExternalGeometryExtension::getClassTypeId())) - THROWM(Base::ValueError, "ExternalGeometryFacade for const::Geometry without ExternalGeometryExtension"); + if (!Geo->hasExtension(ExternalGeometryExtension::getClassTypeId())) + THROWM(Base::ValueError, + "ExternalGeometryFacade for const::Geometry without ExternalGeometryExtension"); - auto ext = std::static_pointer_cast(Geo->getExtension(SketchGeometryExtension::getClassTypeId()).lock()); + auto ext = std::static_pointer_cast( + Geo->getExtension(SketchGeometryExtension::getClassTypeId()).lock()); - const_cast(this)->SketchGeoExtension = ext; + const_cast(this)->SketchGeoExtension = ext; - auto extext = std::static_pointer_cast(Geo->getExtension(ExternalGeometryExtension::getClassTypeId()).lock()); + auto extext = std::static_pointer_cast( + Geo->getExtension(ExternalGeometryExtension::getClassTypeId()).lock()); - const_cast(this)->ExternalGeoExtension = extext; + const_cast(this)->ExternalGeoExtension = extext; } -void ExternalGeometryFacade::ensureSketchGeometryExtensions(Part::Geometry * geometry) +void ExternalGeometryFacade::ensureSketchGeometryExtensions(Part::Geometry* geometry) { - if(!geometry->hasExtension(SketchGeometryExtension::getClassTypeId())) { - geometry->setExtension(std::make_unique()); // Create geoExtension + if (!geometry->hasExtension(SketchGeometryExtension::getClassTypeId())) { + // Create geoExtension + geometry->setExtension(std::make_unique()); } - if(!geometry->hasExtension(ExternalGeometryExtension::getClassTypeId())) { - geometry->setExtension(std::make_unique()); // Create external geoExtension + if (!geometry->hasExtension(ExternalGeometryExtension::getClassTypeId())) { + // Create external geoExtension + geometry->setExtension(std::make_unique()); } } -void ExternalGeometryFacade::copyId(const Part::Geometry * src, Part::Geometry * dst) +void ExternalGeometryFacade::copyId(const Part::Geometry* src, Part::Geometry* dst) { auto gfsrc = ExternalGeometryFacade::getFacade(src); auto gfdst = ExternalGeometryFacade::getFacade(dst); gfdst->setId(gfsrc->getId()); } -PyObject * ExternalGeometryFacade::getPyObject() +PyObject* ExternalGeometryFacade::getPyObject() { return new ExternalGeometryFacadePy(new ExternalGeometryFacade(this->Geo)); } diff --git a/src/Mod/Sketcher/App/ExternalGeometryFacade.h b/src/Mod/Sketcher/App/ExternalGeometryFacade.h index b53277a21f..fbda7f3c6d 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryFacade.h +++ b/src/Mod/Sketcher/App/ExternalGeometryFacade.h @@ -34,137 +34,277 @@ namespace Sketcher { class ExternalGeometryFacadePy; -// This class is a Facade to handle EXTERNAL sketcher geometry and sketcher geometry extensions with a single sketcher specific interface. +// This class is a Facade to handle EXTERNAL sketcher geometry and sketcher geometry extensions with +// a single sketcher specific interface. // -// Exactly the same considerations as for GeometryFacade apply (see documentation of GeometryFacade). +// Exactly the same considerations as for GeometryFacade apply (see documentation of +// GeometryFacade). // -// It was not made publicly deriving from GeometryFacade because it is not possible to differentiate functions by return type, which is the -// case of getFacade() returning a unique_ptr to GeometryFacade in GeometryFacade, and one to ExternalGeometryFacade. I have not managed to -// find a good solution to this problem, thus the code duplication. +// It was not made publicly deriving from GeometryFacade because it is not possible to differentiate +// functions by return type, which is the case of getFacade() returning a unique_ptr to +// GeometryFacade in GeometryFacade, and one to ExternalGeometryFacade. I have not managed to find a +// good solution to this problem, thus the code duplication. // // Summary Remarks: // It is intended to have a separate type (not being a Geometry type). // it is intended to have the relevant interface in full for the sketcher extension only // It is intended to work on borrowed memory allocation. -class SketcherExport ExternalGeometryFacade : public Base::BaseClass, private ISketchGeometryExtension, private ISketchExternalGeometryExtension +class SketcherExport ExternalGeometryFacade: public Base::BaseClass, + private ISketchGeometryExtension, + private ISketchExternalGeometryExtension { -TYPESYSTEM_HEADER_WITH_OVERRIDE(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); private: - explicit ExternalGeometryFacade(const Part::Geometry * geometry); - ExternalGeometryFacade(); // As TYPESYSTEM requirement + explicit ExternalGeometryFacade(const Part::Geometry* geometry); + ExternalGeometryFacade();// As TYPESYSTEM requirement friend class ExternalGeometryFacadePy; -public: // Factory methods - static std::unique_ptr getFacade(Part::Geometry * geometry); - static std::unique_ptr getFacade(const Part::Geometry * geometry); +public:// Factory methods + static std::unique_ptr getFacade(Part::Geometry* geometry); + static std::unique_ptr getFacade(const Part::Geometry* geometry); -public: // Utility methods - static void ensureSketchGeometryExtensions(Part::Geometry * geometry); - static void copyId(const Part::Geometry * src, Part::Geometry * dst); +public:// Utility methods + static void ensureSketchGeometryExtensions(Part::Geometry* geometry); + static void copyId(const Part::Geometry* src, Part::Geometry* dst); public: - void setGeometry(Part::Geometry *geometry); + void setGeometry(Part::Geometry* geometry); /** External GeometryExtension Interface **/ - bool testFlag(int flag) const override { return getExternalGeoExt()->testFlag(flag); } - void setFlag(int flag, bool v=true) override { getExternalGeoExt()->setFlag(flag, v); } + bool testFlag(int flag) const override + { + return getExternalGeoExt()->testFlag(flag); + } + void setFlag(int flag, bool v = true) override + { + getExternalGeoExt()->setFlag(flag, v); + } - bool isClear() const override {return getExternalGeoExt()->isClear();} - size_t flagSize() const override {return getExternalGeoExt()->flagSize();} + bool isClear() const override + { + return getExternalGeoExt()->isClear(); + } + size_t flagSize() const override + { + return getExternalGeoExt()->flagSize(); + } - const std::string& getRef() const override {return getExternalGeoExt()->getRef();} - void setRef(const std::string & ref) override {getExternalGeoExt()->setRef(ref);} + const std::string& getRef() const override + { + return getExternalGeoExt()->getRef(); + } + void setRef(const std::string& ref) override + { + getExternalGeoExt()->setRef(ref); + } /** GeometryExtension Interface **/ - inline long getId() const override {return getGeoExt()->getId();} - void setId(long id) override {getGeoExt()->setId(id);} + inline long getId() const override + { + return getGeoExt()->getId(); + } + void setId(long id) override + { + getGeoExt()->setId(id); + } - InternalType::InternalType getInternalType() const override {return getGeoExt()->getInternalType();} - void setInternalType(InternalType::InternalType type) override {getGeoExt()->setInternalType(type);} + InternalType::InternalType getInternalType() const override + { + return getGeoExt()->getInternalType(); + } + void setInternalType(InternalType::InternalType type) override + { + getGeoExt()->setInternalType(type); + } - bool testGeometryMode(int flag) const override { return getGeoExt()->testGeometryMode(flag); } - void setGeometryMode(int flag, bool v=true) override { getGeoExt()->setGeometryMode(flag, v); } + bool testGeometryMode(int flag) const override + { + return getGeoExt()->testGeometryMode(flag); + } + void setGeometryMode(int flag, bool v = true) override + { + getGeoExt()->setGeometryMode(flag, v); + } - int getGeometryLayerId() const override { return getGeoExt()->getGeometryLayerId();} - void setGeometryLayerId(int geolayer) override { getGeoExt()->setGeometryLayerId(geolayer);} + int getGeometryLayerId() const override + { + return getGeoExt()->getGeometryLayerId(); + } + void setGeometryLayerId(int geolayer) override + { + getGeoExt()->setGeometryLayerId(geolayer); + } // Convenience accessor - bool getBlocked() const { return this->testGeometryMode(GeometryMode::Blocked);} - void setBlocked(bool status = true) {this->setGeometryMode(GeometryMode::Blocked, status);} + bool getBlocked() const + { + return this->testGeometryMode(GeometryMode::Blocked); + } + void setBlocked(bool status = true) + { + this->setGeometryMode(GeometryMode::Blocked, status); + } - inline bool getConstruction() const {return this->testGeometryMode(GeometryMode::Construction);}; - inline void setConstruction(bool construction) {this->setGeometryMode(GeometryMode::Construction, construction);}; + inline bool getConstruction() const + { + return this->testGeometryMode(GeometryMode::Construction); + }; + inline void setConstruction(bool construction) + { + this->setGeometryMode(GeometryMode::Construction, construction); + }; // Geometry Extension Information - inline const std::string &getSketchExtensionName () const {return SketchGeoExtension->getName();} - inline const std::string &getExternalExtensionName () const {return ExternalGeoExtension->getName();} + inline const std::string& getSketchExtensionName() const + { + return SketchGeoExtension->getName(); + } + inline const std::string& getExternalExtensionName() const + { + return ExternalGeoExtension->getName(); + } // Geometry Element - template < typename GeometryT = Part::Geometry, - typename = typename std::enable_if< - std::is_base_of::type>::value - >::type - > - GeometryT * getGeometry() {return dynamic_cast(const_cast(Geo));} + template::type>::value>::type> + GeometryT* getGeometry() + { + return dynamic_cast(const_cast(Geo)); + } // Geometry Element - template < typename GeometryT = Part::Geometry, - typename = typename std::enable_if< - std::is_base_of::type>::value - >::type - > - GeometryT * getGeometry() const {return dynamic_cast(Geo);} + template::type>::value>::type> + GeometryT* getGeometry() const + { + return dynamic_cast(Geo); + } - PyObject *getPyObject() override; + PyObject* getPyObject() override; /** Geometry Interface **/ - TopoDS_Shape toShape() const {return getGeo()->toShape();}; - const Handle(Geom_Geometry)& handle() const {return getGeo()->handle();}; - Part::Geometry *copy() const {return getGeo()->copy();}; - Part::Geometry *clone() const {return getGeo()->clone();}; - boost::uuids::uuid getTag() const {return getGeo()->getTag();}; + TopoDS_Shape toShape() const + { + return getGeo()->toShape(); + }; + const Handle(Geom_Geometry) & handle() const + { + return getGeo()->handle(); + }; + Part::Geometry* copy() const + { + return getGeo()->copy(); + }; + Part::Geometry* clone() const + { + return getGeo()->clone(); + }; + boost::uuids::uuid getTag() const + { + return getGeo()->getTag(); + }; - std::vector> getExtensions() const {return getGeo()->getExtensions();}; - bool hasExtension(Base::Type type) const {return getGeo()->hasExtension(type);}; - bool hasExtension(const std::string & name) const {return getGeo()->hasExtension(name);}; - std::weak_ptr getExtension(Base::Type type) const {return getGeo()->getExtension(type);}; - std::weak_ptr getExtension(const std::string & name) const {return getGeo()->getExtension(name);}; - void setExtension(std::unique_ptr &&geo) {return getGeo()->setExtension(std::move(geo));}; - void deleteExtension(Base::Type type) {return getGeo()->deleteExtension(type);}; - void deleteExtension(const std::string & name) {return getGeo()->deleteExtension(name);}; + std::vector> getExtensions() const + { + return getGeo()->getExtensions(); + }; + bool hasExtension(Base::Type type) const + { + return getGeo()->hasExtension(type); + }; + bool hasExtension(const std::string& name) const + { + return getGeo()->hasExtension(name); + }; + std::weak_ptr getExtension(Base::Type type) const + { + return getGeo()->getExtension(type); + }; + std::weak_ptr getExtension(const std::string& name) const + { + return getGeo()->getExtension(name); + }; + void setExtension(std::unique_ptr&& geo) + { + return getGeo()->setExtension(std::move(geo)); + }; + void deleteExtension(Base::Type type) + { + return getGeo()->deleteExtension(type); + }; + void deleteExtension(const std::string& name) + { + return getGeo()->deleteExtension(name); + }; - void mirror(const Base::Vector3d & point) {return getGeo()->mirror(point);}; - void mirror(const Base::Vector3d & point, Base::Vector3d dir) {return getGeo()->mirror(point, dir);}; - void rotate(const Base::Placement & plm) {return getGeo()->rotate(plm);}; - void scale(const Base::Vector3d & vec, double scale) {return getGeo()->scale(vec, scale);}; - void transform(const Base::Matrix4D & mat) {return getGeo()->transform(mat);}; - void translate(const Base::Vector3d & vec) {return getGeo()->translate(vec);}; + void mirror(const Base::Vector3d& point) + { + return getGeo()->mirror(point); + }; + void mirror(const Base::Vector3d& point, Base::Vector3d dir) + { + return getGeo()->mirror(point, dir); + }; + void rotate(const Base::Placement& plm) + { + return getGeo()->rotate(plm); + }; + void scale(const Base::Vector3d& vec, double scale) + { + return getGeo()->scale(vec, scale); + }; + void transform(const Base::Matrix4D& mat) + { + return getGeo()->transform(mat); + }; + void translate(const Base::Vector3d& vec) + { + return getGeo()->translate(vec); + }; private: void initExtensions(); void initExtensions() const; - const Part::Geometry * getGeo() const {return Geo;} - Part::Geometry * getGeo() {return const_cast(Geo);} + const Part::Geometry* getGeo() const + { + return Geo; + } + Part::Geometry* getGeo() + { + return const_cast(Geo); + } - std::shared_ptr getGeoExt() const {return SketchGeoExtension;} - std::shared_ptr getGeoExt () {return std::const_pointer_cast(SketchGeoExtension);} + std::shared_ptr getGeoExt() const + { + return SketchGeoExtension; + } + std::shared_ptr getGeoExt() + { + return std::const_pointer_cast(SketchGeoExtension); + } - std::shared_ptr getExternalGeoExt() const {return ExternalGeoExtension;} - std::shared_ptr getExternalGeoExt () {return std::const_pointer_cast(ExternalGeoExtension);} + std::shared_ptr getExternalGeoExt() const + { + return ExternalGeoExtension; + } + std::shared_ptr getExternalGeoExt() + { + return std::const_pointer_cast(ExternalGeoExtension); + } private: - const Part::Geometry * Geo; + const Part::Geometry* Geo; std::shared_ptr SketchGeoExtension; std::shared_ptr ExternalGeoExtension; }; +}// namespace Sketcher -} //namespace Sketcher - - -#endif // SKETCHER_GEOMETRYEXTERNALFACADE_H +#endif// SKETCHER_GEOMETRYEXTERNALFACADE_H diff --git a/src/Mod/Sketcher/App/ExternalGeometryFacadePyImp.cpp b/src/Mod/Sketcher/App/ExternalGeometryFacadePyImp.cpp index 7e12b25732..2367f40269 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryFacadePyImp.cpp +++ b/src/Mod/Sketcher/App/ExternalGeometryFacadePyImp.cpp @@ -27,11 +27,12 @@ #include #include #include -#include #include +#include #include #include "ExternalGeometryFacadePy.h" + #include "ExternalGeometryFacadePy.cpp" @@ -47,7 +48,8 @@ std::string ExternalGeometryFacadePy::representation() const return str.str(); } -PyObject *ExternalGeometryFacadePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ExternalGeometryFacadePy::PyMake(struct _typeobject*, PyObject*, + PyObject*)// Python wrapper { // create a new instance of PointPy and the Twin object return new ExternalGeometryFacadePy(new ExternalGeometryFacade()); @@ -56,60 +58,61 @@ PyObject *ExternalGeometryFacadePy::PyMake(struct _typeobject *, PyObject *, PyO // constructor method int ExternalGeometryFacadePy::PyInit(PyObject* args, PyObject* /*kwd*/) { - PyObject *object; - if (PyArg_ParseTuple(args,"O!",&(Part::GeometryPy::Type), &object)) { - Part::Geometry * geo = static_cast(object)->getGeometryPtr(); + PyObject* object; + if (PyArg_ParseTuple(args, "O!", &(Part::GeometryPy::Type), &object)) { + Part::Geometry* geo = static_cast(object)->getGeometryPtr(); getExternalGeometryFacadePtr()->setGeometry(geo->clone()); return 0; } - PyErr_SetString(PyExc_TypeError, "Sketcher::ExternalGeometryFacade constructor accepts:\n" - "-- Part.Geometry\n" - ); + PyErr_SetString(PyExc_TypeError, + "Sketcher::ExternalGeometryFacade constructor accepts:\n" + "-- Part.Geometry\n"); return -1; } -PyObject* ExternalGeometryFacadePy::testFlag(PyObject *args) +PyObject* ExternalGeometryFacadePy::testFlag(PyObject* args) { char* flag; - if (PyArg_ParseTuple(args, "s",&flag)) { + if (PyArg_ParseTuple(args, "s", &flag)) { auto pos = std::find_if(ExternalGeometryExtension::flag2str.begin(), - ExternalGeometryExtension::flag2str.end(), - [flag](const char * val) { return strcmp(val,flag) == 0;}); + ExternalGeometryExtension::flag2str.end(), + [flag](const char* val) { + return strcmp(val, flag) == 0; + }); - if( pos != ExternalGeometryExtension::flag2str.end()) { - int index = std::distance( ExternalGeometryExtension::flag2str.begin(), pos ); + if (pos != ExternalGeometryExtension::flag2str.end()) { + int index = std::distance(ExternalGeometryExtension::flag2str.begin(), pos); - return new_reference_to(Py::Boolean(this->getExternalGeometryFacadePtr()->testFlag(index))); + return new_reference_to( + Py::Boolean(this->getExternalGeometryFacadePtr()->testFlag(index))); } PyErr_SetString(PyExc_TypeError, "Flag string does not exist."); return nullptr; - } PyErr_SetString(PyExc_TypeError, "No flag string provided."); return nullptr; } -PyObject* ExternalGeometryFacadePy::setFlag(PyObject *args) +PyObject* ExternalGeometryFacadePy::setFlag(PyObject* args) { - char * flag; - PyObject * bflag = Py_True; + char* flag; + PyObject* bflag = Py_True; if (PyArg_ParseTuple(args, "s|O!", &flag, &PyBool_Type, &bflag)) { auto pos = std::find_if(ExternalGeometryExtension::flag2str.begin(), ExternalGeometryExtension::flag2str.end(), - [flag](const char * val) { - return strcmp(val,flag)==0; - } - ); + [flag](const char* val) { + return strcmp(val, flag) == 0; + }); - if( pos != ExternalGeometryExtension::flag2str.end()) { - int index = std::distance( ExternalGeometryExtension::flag2str.begin(), pos ); + if (pos != ExternalGeometryExtension::flag2str.end()) { + int index = std::distance(ExternalGeometryExtension::flag2str.begin(), pos); this->getExternalGeometryFacadePtr()->setFlag(index, Base::asBoolean(bflag)); Py_Return; @@ -147,12 +150,12 @@ Py::String ExternalGeometryFacadePy::getInternalType() const { int internaltypeindex = (int)this->getExternalGeometryFacadePtr()->getInternalType(); - if(internaltypeindex >= InternalType::NumInternalGeometryType) + if (internaltypeindex >= InternalType::NumInternalGeometryType) throw Py::NotImplementedError("String name of enum not implemented"); std::string typestr = SketchGeometryExtension::internaltype2str[internaltypeindex]; - return Py::String(typestr); + return Py::String(typestr); } void ExternalGeometryFacadePy::setInternalType(Py::String arg) @@ -160,7 +163,7 @@ void ExternalGeometryFacadePy::setInternalType(Py::String arg) std::string argstr = arg; InternalType::InternalType type; - if(SketchGeometryExtension::getInternalTypeFromName(argstr, type)) { + if (SketchGeometryExtension::getInternalTypeFromName(argstr, type)) { this->getExternalGeometryFacadePtr()->setInternalType(type); return; } @@ -178,10 +181,10 @@ void ExternalGeometryFacadePy::setBlocked(Py::Boolean arg) getExternalGeometryFacadePtr()->setBlocked(arg); } -PyObject* ExternalGeometryFacadePy::mirror(PyObject *args) +PyObject* ExternalGeometryFacadePy::mirror(PyObject* args) { PyObject* o; - if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type),&o)) { + if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &o)) { Base::Vector3d vec = static_cast(o)->value(); getExternalGeometryFacadePtr()->mirror(vec); Py_Return; @@ -189,22 +192,23 @@ PyObject* ExternalGeometryFacadePy::mirror(PyObject *args) PyErr_Clear(); PyObject* axis; - if (PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type),&o, - &(Base::VectorPy::Type),&axis)) { + if (PyArg_ParseTuple( + args, "O!O!", &(Base::VectorPy::Type), &o, &(Base::VectorPy::Type), &axis)) { Base::Vector3d pnt = static_cast(o)->value(); Base::Vector3d dir = static_cast(axis)->value(); getExternalGeometryFacadePtr()->mirror(pnt, dir); Py_Return; } - PyErr_SetString(Part::PartExceptionOCCError, "either a point (vector) or axis (vector, vector) must be given"); + PyErr_SetString(Part::PartExceptionOCCError, + "either a point (vector) or axis (vector, vector) must be given"); return nullptr; } -PyObject* ExternalGeometryFacadePy::rotate(PyObject *args) +PyObject* ExternalGeometryFacadePy::rotate(PyObject* args) { PyObject* o; - if (!PyArg_ParseTuple(args, "O!", &(Base::PlacementPy::Type),&o)) + if (!PyArg_ParseTuple(args, "O!", &(Base::PlacementPy::Type), &o)) return nullptr; Base::Placement* plm = static_cast(o)->getPlacementPtr(); @@ -212,19 +216,19 @@ PyObject* ExternalGeometryFacadePy::rotate(PyObject *args) Py_Return; } -PyObject* ExternalGeometryFacadePy::scale(PyObject *args) +PyObject* ExternalGeometryFacadePy::scale(PyObject* args) { PyObject* o; double scale; Base::Vector3d vec; - if (PyArg_ParseTuple(args, "O!d", &(Base::VectorPy::Type),&o, &scale)) { + if (PyArg_ParseTuple(args, "O!d", &(Base::VectorPy::Type), &o, &scale)) { vec = static_cast(o)->value(); getExternalGeometryFacadePtr()->scale(vec, scale); Py_Return; } PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!d", &PyTuple_Type,&o, &scale)) { + if (PyArg_ParseTuple(args, "O!d", &PyTuple_Type, &o, &scale)) { vec = Base::getVectorFromTuple(o); getExternalGeometryFacadePtr()->scale(vec, scale); Py_Return; @@ -234,28 +238,28 @@ PyObject* ExternalGeometryFacadePy::scale(PyObject *args) return nullptr; } -PyObject* ExternalGeometryFacadePy::transform(PyObject *args) +PyObject* ExternalGeometryFacadePy::transform(PyObject* args) { PyObject* o; - if (!PyArg_ParseTuple(args, "O!", &(Base::MatrixPy::Type),&o)) + if (!PyArg_ParseTuple(args, "O!", &(Base::MatrixPy::Type), &o)) return nullptr; Base::Matrix4D mat = static_cast(o)->value(); getExternalGeometryFacadePtr()->transform(mat); Py_Return; } -PyObject* ExternalGeometryFacadePy::translate(PyObject *args) +PyObject* ExternalGeometryFacadePy::translate(PyObject* args) { PyObject* o; Base::Vector3d vec; - if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type),&o)) { + if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &o)) { vec = static_cast(o)->value(); getExternalGeometryFacadePtr()->translate(vec); Py_Return; } PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!", &PyTuple_Type,&o)) { + if (PyArg_ParseTuple(args, "O!", &PyTuple_Type, &o)) { vec = Base::getVectorFromTuple(o); getExternalGeometryFacadePtr()->translate(vec); Py_Return; @@ -265,12 +269,12 @@ PyObject* ExternalGeometryFacadePy::translate(PyObject *args) return nullptr; } -PyObject* ExternalGeometryFacadePy::setExtension(PyObject *args) +PyObject* ExternalGeometryFacadePy::setExtension(PyObject* args) { PyObject* o; - if (PyArg_ParseTuple(args, "O!", &(Part::GeometryExtensionPy::Type),&o)) { - Part::GeometryExtension * ext; - ext = static_cast(o)->getGeometryExtensionPtr(); + if (PyArg_ParseTuple(args, "O!", &(Part::GeometryExtensionPy::Type), &o)) { + Part::GeometryExtension* ext; + ext = static_cast(o)->getGeometryExtensionPtr(); // make copy of Python managed memory and wrap it in smart pointer auto cpy = ext->copy(); @@ -283,154 +287,159 @@ PyObject* ExternalGeometryFacadePy::setExtension(PyObject *args) return nullptr; } -PyObject* ExternalGeometryFacadePy::getExtensionOfType(PyObject *args) +PyObject* ExternalGeometryFacadePy::getExtensionOfType(PyObject* args) { char* o; if (PyArg_ParseTuple(args, "s", &o)) { Base::Type type = Base::Type::fromName(o); - if(type != Base::Type::badType()) { + if (type != Base::Type::badType()) { try { - std::shared_ptr ext(this->getExternalGeometryFacadePtr()->getExtension(type)); + std::shared_ptr ext( + this->getExternalGeometryFacadePtr()->getExtension(type)); - // we create a copy and transfer this copy's memory management responsibility to Python + // we create a copy and transfer this copy's memory management responsibility to + // Python PyObject* cpy = ext->copyPyObject(); return cpy; } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); return nullptr; } - catch(const std::bad_weak_ptr&) { - PyErr_SetString(Part::PartExceptionOCCError, "Geometry extension does not exist anymore."); + catch (const std::bad_weak_ptr&) { + PyErr_SetString(Part::PartExceptionOCCError, + "Geometry extension does not exist anymore."); return nullptr; } - catch(Base::NotImplementedError&) { - PyErr_SetString(Part::PartExceptionOCCError, "Geometry extension does not implement a Python counterpart."); + catch (Base::NotImplementedError&) { + PyErr_SetString(Part::PartExceptionOCCError, + "Geometry extension does not implement a Python counterpart."); return nullptr; } } - else - { + else { PyErr_SetString(Part::PartExceptionOCCError, "Exception type does not exist"); return nullptr; } - } - PyErr_SetString(Part::PartExceptionOCCError, "A string with the name of the geometry extension type was expected"); + PyErr_SetString(Part::PartExceptionOCCError, + "A string with the name of the geometry extension type was expected"); return nullptr; } -PyObject* ExternalGeometryFacadePy::getExtensionOfName(PyObject *args) +PyObject* ExternalGeometryFacadePy::getExtensionOfName(PyObject* args) { char* o; if (PyArg_ParseTuple(args, "s", &o)) { try { - std::shared_ptr ext(this->getExternalGeometryFacadePtr()->getExtension(std::string(o))); + std::shared_ptr ext( + this->getExternalGeometryFacadePtr()->getExtension(std::string(o))); // we create a copy and transfer this copy's memory management responsibility to Python PyObject* cpy = ext->copyPyObject(); return cpy; } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); return nullptr; } - catch(const std::bad_weak_ptr&) { - PyErr_SetString(Part::PartExceptionOCCError, "Geometry extension does not exist anymore."); + catch (const std::bad_weak_ptr&) { + PyErr_SetString(Part::PartExceptionOCCError, + "Geometry extension does not exist anymore."); return nullptr; } - catch(Base::NotImplementedError&) { - PyErr_SetString(Part::PartExceptionOCCError, "Geometry extension does not implement a Python counterpart."); + catch (Base::NotImplementedError&) { + PyErr_SetString(Part::PartExceptionOCCError, + "Geometry extension does not implement a Python counterpart."); return nullptr; } - } - PyErr_SetString(Part::PartExceptionOCCError, "A string with the name of the geometry extension was expected"); + PyErr_SetString(Part::PartExceptionOCCError, + "A string with the name of the geometry extension was expected"); return nullptr; } -PyObject* ExternalGeometryFacadePy::hasExtensionOfType(PyObject *args) +PyObject* ExternalGeometryFacadePy::hasExtensionOfType(PyObject* args) { char* o; if (PyArg_ParseTuple(args, "s", &o)) { Base::Type type = Base::Type::fromName(o); - if(type != Base::Type::badType()) { + if (type != Base::Type::badType()) { try { - return Py::new_reference_to(Py::Boolean(this->getExternalGeometryFacadePtr()->hasExtension(type))); + return Py::new_reference_to( + Py::Boolean(this->getExternalGeometryFacadePtr()->hasExtension(type))); } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); return nullptr; } } - else - { + else { PyErr_SetString(Part::PartExceptionOCCError, "Exception type does not exist"); return nullptr; } - } - PyErr_SetString(Part::PartExceptionOCCError, "A string with the type of the geometry extension was expected"); + PyErr_SetString(Part::PartExceptionOCCError, + "A string with the type of the geometry extension was expected"); return nullptr; } -PyObject* ExternalGeometryFacadePy::hasExtensionOfName(PyObject *args) +PyObject* ExternalGeometryFacadePy::hasExtensionOfName(PyObject* args) { char* o; if (PyArg_ParseTuple(args, "s", &o)) { try { - return Py::new_reference_to(Py::Boolean(this->getExternalGeometryFacadePtr()->hasExtension(std::string(o)))); + return Py::new_reference_to( + Py::Boolean(this->getExternalGeometryFacadePtr()->hasExtension(std::string(o)))); } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); return nullptr; } - } - PyErr_SetString(Part::PartExceptionOCCError, "A string with the type of the geometry extension was expected"); + PyErr_SetString(Part::PartExceptionOCCError, + "A string with the type of the geometry extension was expected"); return nullptr; } -PyObject* ExternalGeometryFacadePy::deleteExtensionOfType(PyObject *args) +PyObject* ExternalGeometryFacadePy::deleteExtensionOfType(PyObject* args) { char* o; if (PyArg_ParseTuple(args, "s", &o)) { Base::Type type = Base::Type::fromName(o); - if(type != Base::Type::badType()) { + if (type != Base::Type::badType()) { try { this->getExternalGeometryFacadePtr()->deleteExtension(type); Py_Return; } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); return nullptr; } } - else - { + else { PyErr_SetString(Part::PartExceptionOCCError, "Type does not exist"); return nullptr; } - } PyErr_SetString(Part::PartExceptionOCCError, "A string with a type object was expected"); return nullptr; } -PyObject* ExternalGeometryFacadePy::deleteExtensionOfName(PyObject *args) +PyObject* ExternalGeometryFacadePy::deleteExtensionOfName(PyObject* args) { char* o; if (PyArg_ParseTuple(args, "s", &o)) { @@ -439,38 +448,40 @@ PyObject* ExternalGeometryFacadePy::deleteExtensionOfName(PyObject *args) this->getExternalGeometryFacadePtr()->deleteExtension(std::string(o)); Py_Return; } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); return nullptr; } } - PyErr_SetString(Part::PartExceptionOCCError, "A string with the name of the extension was expected"); + PyErr_SetString(Part::PartExceptionOCCError, + "A string with the name of the extension was expected"); return nullptr; } -PyObject* ExternalGeometryFacadePy::getExtensions(PyObject *args) +PyObject* ExternalGeometryFacadePy::getExtensions(PyObject* args) { - if (!PyArg_ParseTuple(args, "")){ + if (!PyArg_ParseTuple(args, "")) { PyErr_SetString(Part::PartExceptionOCCError, "No arguments were expected"); return nullptr; } try { - const std::vector> ext = this->getExternalGeometryFacadePtr()->getExtensions(); + const std::vector> ext = + this->getExternalGeometryFacadePtr()->getExtensions(); Py::List list; - for (std::size_t i=0; i p = ext[i].lock(); - if(p) { + if (p) { // we create a python copy and add it to the list try { list.append(Py::asObject(p->copyPyObject())); } - catch(Base::NotImplementedError&) { + catch (Base::NotImplementedError&) { // silently ignoring extensions not having a Python object } } @@ -478,11 +489,10 @@ PyObject* ExternalGeometryFacadePy::getExtensions(PyObject *args) return Py::new_reference_to(list); } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); return nullptr; } - } Py::Boolean ExternalGeometryFacadePy::getConstruction() const @@ -490,7 +500,7 @@ Py::Boolean ExternalGeometryFacadePy::getConstruction() const return Py::Boolean(getExternalGeometryFacadePtr()->getConstruction()); } -void ExternalGeometryFacadePy::setConstruction(Py::Boolean arg) +void ExternalGeometryFacadePy::setConstruction(Py::Boolean arg) { if (getExternalGeometryFacadePtr()->getTypeId() != Part::GeomPoint::getClassTypeId()) getExternalGeometryFacadePtr()->setConstruction(arg); @@ -519,17 +529,17 @@ Py::Object ExternalGeometryFacadePy::getGeometry() const return Py::Object(geo->getPyObject(), true); } -void ExternalGeometryFacadePy::setGeometry(Py::Object arg) +void ExternalGeometryFacadePy::setGeometry(Py::Object arg) { if (PyObject_TypeCheck(arg.ptr(), &(Part::GeometryPy::Type))) { - Part::GeometryPy * gp = static_cast(arg.ptr()); + Part::GeometryPy* gp = static_cast(arg.ptr()); getExternalGeometryFacadePtr()->setGeometry(gp->getGeometryPtr()->clone()); } } -PyObject *ExternalGeometryFacadePy::getCustomAttributes(const char* /*attr*/) const +PyObject* ExternalGeometryFacadePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Sketcher/App/GeoEnum.h b/src/Mod/Sketcher/App/GeoEnum.h index d77dc7d755..5c6c0a7309 100644 --- a/src/Mod/Sketcher/App/GeoEnum.h +++ b/src/Mod/Sketcher/App/GeoEnum.h @@ -23,8 +23,8 @@ #ifndef SKETCHER_GeoEnum_H #define SKETCHER_GeoEnum_H -#include #include +#include namespace Sketcher { @@ -56,46 +56,49 @@ namespace Sketcher * * Geometry shapes having more or different elements than those supported by the PointPos * struct, such as conics, in particular an arc of ellipse, are called complex geometries. The extra - * elements of complex geometries are actual separate geometries (focus of an ellipse, line defining the - * major axis of an ellipse, circle representing the weight of a BSpline), and they are call InternalAlignment - * geometries. + * elements of complex geometries are actual separate geometries (focus of an ellipse, line defining + * the major axis of an ellipse, circle representing the weight of a BSpline), and they are call + * InternalAlignment geometries. * * For Geometry lists, refer to GeoListModel template. */ enum GeoEnum { - RtPnt = -1, // GeoId of the Root Point - HAxis = -1, // GeoId of the Horizontal Axis - VAxis = -2, // GeoId of the Vertical Axis - RefExt = -3, // Starting GeoID of external geometry ( negative geoIds starting at this index) - GeoUndef = -2000, // GeoId of an undefined Geometry (uninitialised or unused GeoId) + RtPnt = -1, // GeoId of the Root Point + HAxis = -1, // GeoId of the Horizontal Axis + VAxis = -2, // GeoId of the Vertical Axis + RefExt = -3,// Starting GeoID of external geometry ( negative geoIds starting at this index) + GeoUndef = -2000,// GeoId of an undefined Geometry (uninitialised or unused GeoId) }; /*! * @brief PointPos lets us refer to different aspects of a piece of geometry. * @details sketcher::none refers to an edge itself (eg., for a Perpendicular constraint * on two lines). sketcher::start and sketcher::end denote the endpoints of lines or bounded curves. - * Sketcher::mid denotes geometries with geometrical centers (eg., circle, ellipse). Bare points use 'start'. - * More complex geometries like parabola focus or b-spline knots use InternalAlignment constraints - * in addition to PointPos. + * Sketcher::mid denotes geometries with geometrical centers (eg., circle, ellipse). Bare points use + * 'start'. More complex geometries like parabola focus or b-spline knots use InternalAlignment + * constraints in addition to PointPos. */ -enum class PointPos : int { - none = 0, // Edge of a geometry - start = 1, // Starting point of a geometry - end = 2, // End point of a geometry - mid = 3 // Mid point of a geometry +enum class PointPos : int +{ + none = 0, // Edge of a geometry + start = 1,// Starting point of a geometry + end = 2, // End point of a geometry + mid = 3 // Mid point of a geometry }; /** @brief Struct for storing a {GeoId, PointPos} pair. * * @details - * {GeoId, PointPos} is pervasive in the sketcher as means to identify geometry (edges) and geometry elements (vertices). + * {GeoId, PointPos} is pervasive in the sketcher as means to identify geometry (edges) and geometry + * elements (vertices). * - * GeoElementId intends to substitute this pair whenever appropriate. For example in containers and ordered containers. - * - * It has overloaded equality operator and specialised std::less so that it can safely be used in containers, including + * GeoElementId intends to substitute this pair whenever appropriate. For example in containers and * ordered containers. * + * It has overloaded equality operator and specialised std::less so that it can safely be used in + * containers, including ordered containers. + * */ class SketcherExport GeoElementId { @@ -109,7 +112,7 @@ public: bool operator==(const GeoElementId& obj) const; /** @brief inequality operator - */ + */ bool operator!=(const GeoElementId& obj) const; /** @brief Underlying GeoId (see GeoEnum for definition) @@ -135,15 +138,18 @@ public: }; // inline constexpr constructor -inline constexpr GeoElementId::GeoElementId(int geoId, PointPos pos): GeoId(geoId), Pos(pos) -{ -} +inline constexpr GeoElementId::GeoElementId(int geoId, PointPos pos) + : GeoId(geoId), + Pos(pos) +{} -inline bool GeoElementId::isCurve() const { +inline bool GeoElementId::isCurve() const +{ return Pos == PointPos::none; } -inline int GeoElementId::posIdAsInt() const { +inline int GeoElementId::posIdAsInt() const +{ return static_cast(Pos); } @@ -153,18 +159,19 @@ constexpr const GeoElementId GeoElementId::HAxis = GeoElementId(GeoEnum::HAxis, constexpr const GeoElementId GeoElementId::VAxis = GeoElementId(GeoEnum::VAxis, PointPos::none); #endif -} // namespace Sketcher +}// namespace Sketcher namespace std { - template<> struct less +template<> +struct less +{ + bool operator()(const Sketcher::GeoElementId& lhs, const Sketcher::GeoElementId& rhs) const { - bool operator() (const Sketcher::GeoElementId& lhs, const Sketcher::GeoElementId& rhs) const - { - return (lhs.GeoId != rhs.GeoId)?(lhs.GeoId < rhs.GeoId):(static_cast(lhs.Pos) < static_cast(rhs.Pos)); - } - }; -} // namespace std - -#endif // SKETCHER_GeoEnum_H + return (lhs.GeoId != rhs.GeoId) ? (lhs.GeoId < rhs.GeoId) + : (static_cast(lhs.Pos) < static_cast(rhs.Pos)); + } +}; +}// namespace std +#endif// SKETCHER_GeoEnum_H diff --git a/src/Mod/Sketcher/App/GeoList.cpp b/src/Mod/Sketcher/App/GeoList.cpp index 7ab9438444..199d7d7de9 100644 --- a/src/Mod/Sketcher/App/GeoList.cpp +++ b/src/Mod/Sketcher/App/GeoList.cpp @@ -22,8 +22,8 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -#endif // #ifndef _PreComp_ +#include +#endif// #ifndef _PreComp_ #include @@ -37,179 +37,188 @@ using namespace Sketcher; // Vector is moved -template -GeoListModel::GeoListModel( std::vector && geometrylist, - int intgeocount, - bool ownerT): geomlist(std::move(geometrylist)), - intGeoCount(intgeocount), - OwnerT(ownerT), - indexInit(false) -{ - -} +template +GeoListModel::GeoListModel(std::vector&& geometrylist, int intgeocount, bool ownerT) + : geomlist(std::move(geometrylist)), + intGeoCount(intgeocount), + OwnerT(ownerT), + indexInit(false) +{} // Vector is shallow copied (copy constructed) -template -GeoListModel::GeoListModel( const std::vector & geometrylist, - int intgeocount): geomlist(geometrylist), // copy constructed here - intGeoCount(intgeocount), - OwnerT(false), - indexInit(false) -{ +template +GeoListModel::GeoListModel(const std::vector& geometrylist, + int intgeocount) + : geomlist(geometrylist),// copy constructed here + intGeoCount(intgeocount), + OwnerT(false), + indexInit(false) +{} -} - -template +template GeoListModel::~GeoListModel() { - if(OwnerT) { - for(auto & g : geomlist) + if (OwnerT) { + for (auto& g : geomlist) delete g; } } -template -GeoListModel GeoListModel::getGeoListModel(std::vector && geometrylist, int intgeocount, bool ownerT) +template +GeoListModel GeoListModel::getGeoListModel(std::vector&& geometrylist, int intgeocount, + bool ownerT) { return GeoListModel(std::move(geometrylist), intgeocount, ownerT); } -template -const GeoListModel GeoListModel::getGeoListModel(const std::vector &geometrylist, int intgeocount) +template +const GeoListModel GeoListModel::getGeoListModel(const std::vector& geometrylist, + int intgeocount) { return GeoListModel(geometrylist, intgeocount); } -template +template int GeoListModel::getGeoIdFromGeomListIndex(int index) const { assert(index < int(geomlist.size())); - if(index < intGeoCount) + if (index < intGeoCount) return index; else - return ( index - geomlist.size()); + return (index - geomlist.size()); } -template -const Part::Geometry * GeoListModel::getGeometryFromGeoId(const std::vector & geometrylist, int geoId) +template +const Part::Geometry* GeoListModel::getGeometryFromGeoId(const std::vector& geometrylist, + int geoId) { - if constexpr (std::is_same()) { + if constexpr (std::is_same()) { if (geoId >= 0) return geometrylist[geoId]; else - return geometrylist[geometrylist.size()+geoId]; + return geometrylist[geometrylist.size() + geoId]; } - else if constexpr (std::is_same()) { + else if constexpr (std::is_same()) { if (geoId >= 0) return geometrylist[geoId]->getGeometry(); else - return geometrylist[geometrylist.size()+geoId]->getGeometry(); + return geometrylist[geometrylist.size() + geoId]->getGeometry(); } } -template -const Sketcher::GeometryFacade * GeoListModel::getGeometryFacadeFromGeoId(const std::vector & geometrylist, int geoId) +template +const Sketcher::GeometryFacade* +GeoListModel::getGeometryFacadeFromGeoId(const std::vector& geometrylist, int geoId) { - if constexpr (std::is_same()) { + if constexpr (std::is_same()) { if (geoId >= 0) return GeometryFacade::getFacade(geometrylist[geoId]).release(); else - return GeometryFacade::getFacade(geometrylist[geometrylist.size()+geoId]).release(); + return GeometryFacade::getFacade(geometrylist[geometrylist.size() + geoId]).release(); } - else if constexpr (std::is_same()) { + else if constexpr (std::is_same()) { if (geoId >= 0) return geometrylist[geoId].get(); else - return geometrylist[geometrylist.size()+geoId].get(); + return geometrylist[geometrylist.size() + geoId].get(); } } -// this function is used to simulate cyclic periodic negative geometry indices (for external geometry) -template -const Part::Geometry * GeoListModel::getGeometryFromGeoId(int geoId) const +// this function is used to simulate cyclic periodic negative geometry indices (for external +// geometry) +template +const Part::Geometry* GeoListModel::getGeometryFromGeoId(int geoId) const { return GeoListModel::getGeometryFromGeoId(geomlist, geoId); } -template -const Sketcher::GeometryFacade * GeoListModel::getGeometryFacadeFromGeoId(int geoId) const +template +const Sketcher::GeometryFacade* GeoListModel::getGeometryFacadeFromGeoId(int geoId) const { return GeoListModel::getGeometryFacadeFromGeoId(geomlist, geoId); } -template +template Base::Vector3d GeoListModel::getPoint(int geoId, Sketcher::PointPos pos) const { - const Part::Geometry * geo = getGeometryFromGeoId(geoId); + const Part::Geometry* geo = getGeometryFromGeoId(geoId); return getPoint(geo, pos); } -template -Base::Vector3d GeoListModel::getPoint(const GeoElementId & geid) const +template +Base::Vector3d GeoListModel::getPoint(const GeoElementId& geid) const { return getPoint(geid.GeoId, geid.Pos); } -template -Base::Vector3d GeoListModel::getPoint(const Part::Geometry * geo, Sketcher::PointPos pos) const +template +Base::Vector3d GeoListModel::getPoint(const Part::Geometry* geo, Sketcher::PointPos pos) const { using namespace Sketcher; if (geo->getTypeId() == Part::GeomPoint::getClassTypeId()) { - const Part::GeomPoint *p = static_cast(geo); + const Part::GeomPoint* p = static_cast(geo); if (pos == PointPos::start || pos == PointPos::mid || pos == PointPos::end) return p->getPoint(); - } else if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* lineSeg = static_cast(geo); if (pos == PointPos::start) return lineSeg->getStartPoint(); else if (pos == PointPos::end) return lineSeg->getEndPoint(); - } else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { + const Part::GeomCircle* circle = static_cast(geo); if (pos == PointPos::mid) return circle->getCenter(); - } else if (geo->getTypeId() == Part::GeomEllipse::getClassTypeId()) { - const Part::GeomEllipse *ellipse = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomEllipse::getClassTypeId()) { + const Part::GeomEllipse* ellipse = static_cast(geo); if (pos == PointPos::mid) return ellipse->getCenter(); - } else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *aoc = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* aoc = static_cast(geo); if (pos == PointPos::start) return aoc->getStartPoint(/*emulateCCW=*/true); else if (pos == PointPos::end) return aoc->getEndPoint(/*emulateCCW=*/true); else if (pos == PointPos::mid) return aoc->getCenter(); - } else if (geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { - const Part::GeomArcOfEllipse *aoc = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { + const Part::GeomArcOfEllipse* aoc = static_cast(geo); if (pos == PointPos::start) return aoc->getStartPoint(/*emulateCCW=*/true); else if (pos == PointPos::end) return aoc->getEndPoint(/*emulateCCW=*/true); else if (pos == PointPos::mid) return aoc->getCenter(); - } else if (geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { - const Part::GeomArcOfHyperbola *aoh = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + const Part::GeomArcOfHyperbola* aoh = static_cast(geo); if (pos == PointPos::start) return aoh->getStartPoint(); else if (pos == PointPos::end) return aoh->getEndPoint(); else if (pos == PointPos::mid) return aoh->getCenter(); - } else if (geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { - const Part::GeomArcOfParabola *aop = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + const Part::GeomArcOfParabola* aop = static_cast(geo); if (pos == PointPos::start) return aop->getStartPoint(); else if (pos == PointPos::end) return aop->getEndPoint(); else if (pos == PointPos::mid) return aop->getCenter(); - } else if (geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { - const Part::GeomBSplineCurve *bsp = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { + const Part::GeomBSplineCurve* bsp = static_cast(geo); if (pos == PointPos::start) return bsp->getStartPoint(); else if (pos == PointPos::end) @@ -219,20 +228,20 @@ Base::Vector3d GeoListModel::getPoint(const Part::Geometry * geo, Sketcher::P return Base::Vector3d(); } -template +template void GeoListModel::rebuildVertexIndex() const { VertexId2GeoElementId.clear(); GeoElementId2VertexId.clear(); - int geoId=0; - int pointId=0; + int geoId = 0; + int pointId = 0; auto addGeoElement = [this, &pointId](int geoId, PointPos pos) { - VertexId2GeoElementId.emplace_back(geoId,pos); + VertexId2GeoElementId.emplace_back(geoId, pos); GeoElementId2VertexId.emplace(std::piecewise_construct, - std::forward_as_tuple(geoId, pos), - std::forward_as_tuple(pointId++)); + std::forward_as_tuple(geoId, pos), + std::forward_as_tuple(pointId++)); }; if (geomlist.size() <= 2) @@ -241,72 +250,75 @@ void GeoListModel::rebuildVertexIndex() const Base::Type type; - if constexpr (std::is_same::value) + if constexpr (std::is_same::value) type = (*it)->getTypeId(); else if constexpr (std::is_same>::value) type = (*it)->getGeometry()->getTypeId(); - if ( geoId > getInternalCount()) + if (geoId > getInternalCount()) geoId = -getExternalCount(); if (type == Part::GeomPoint::getClassTypeId()) { - addGeoElement(geoId,PointPos::start); - } else if (type == Part::GeomLineSegment::getClassTypeId() || - type == Part::GeomBSplineCurve::getClassTypeId()) { - addGeoElement(geoId,PointPos::start); - addGeoElement(geoId,PointPos::end); - } else if (type == Part::GeomCircle::getClassTypeId() || - type == Part::GeomEllipse::getClassTypeId()) { - addGeoElement(geoId,PointPos::mid); - } else if (type == Part::GeomArcOfCircle::getClassTypeId() || - type == Part::GeomArcOfEllipse::getClassTypeId() || - type == Part::GeomArcOfHyperbola::getClassTypeId() || - type == Part::GeomArcOfParabola::getClassTypeId()) { - addGeoElement(geoId,PointPos::start); - addGeoElement(geoId,PointPos::end); - addGeoElement(geoId,PointPos::mid); + addGeoElement(geoId, PointPos::start); + } + else if (type == Part::GeomLineSegment::getClassTypeId() + || type == Part::GeomBSplineCurve::getClassTypeId()) { + addGeoElement(geoId, PointPos::start); + addGeoElement(geoId, PointPos::end); + } + else if (type == Part::GeomCircle::getClassTypeId() + || type == Part::GeomEllipse::getClassTypeId()) { + addGeoElement(geoId, PointPos::mid); + } + else if (type == Part::GeomArcOfCircle::getClassTypeId() + || type == Part::GeomArcOfEllipse::getClassTypeId() + || type == Part::GeomArcOfHyperbola::getClassTypeId() + || type == Part::GeomArcOfParabola::getClassTypeId()) { + addGeoElement(geoId, PointPos::start); + addGeoElement(geoId, PointPos::end); + addGeoElement(geoId, PointPos::mid); } } indexInit = true; } -template +template Sketcher::GeoElementId GeoListModel::getGeoElementIdFromVertexId(int vertexId) { - if(!indexInit) // lazy initialised + if (!indexInit)// lazy initialised rebuildVertexIndex(); return VertexId2GeoElementId[vertexId]; } -template -int GeoListModel::getVertexIdFromGeoElementId(const Sketcher::GeoElementId & geoelementId) const +template +int GeoListModel::getVertexIdFromGeoElementId(const Sketcher::GeoElementId& geoelementId) const { - if(!indexInit) // lazy initialised + if (!indexInit)// lazy initialised rebuildVertexIndex(); - auto found = std::find(VertexId2GeoElementId.begin(), VertexId2GeoElementId.end(), geoelementId); + auto found = + std::find(VertexId2GeoElementId.begin(), VertexId2GeoElementId.end(), geoelementId); - if( found != VertexId2GeoElementId.end() ) + if (found != VertexId2GeoElementId.end()) return std::distance(found, VertexId2GeoElementId.begin()); THROWM(Base::IndexError, "GeoElementId not indexed"); } - -namespace Sketcher { +namespace Sketcher +{ // Template specialisations -template <> +template<> GeoListModel::GeoListModel( - std::vector && geometrylist, - int intgeocount, - bool ownerT) : geomlist(std::move(geometrylist)), - intGeoCount(intgeocount), - OwnerT(false), - indexInit(false) + std::vector&& geometrylist, int intgeocount, bool ownerT) + : geomlist(std::move(geometrylist)), + intGeoCount(intgeocount), + OwnerT(false), + indexInit(false) { // GeometryFacades hold the responsibility for releasing the resources. // @@ -321,62 +333,72 @@ GeoListModel::GeoListModel( boost::ignore_unused(ownerT); } -template <> +template<> GeoListModel::GeoListModel( - const std::vector & geometrylist, - int intgeocount): intGeoCount(intgeocount), - OwnerT(false), - indexInit(false) + const std::vector& geometrylist, int intgeocount) + : intGeoCount(intgeocount), + OwnerT(false), + indexInit(false) { - // GeometryFacades are movable, but not copiable, so they need to be reconstructed (shallow copy of vector) - // Under the Single Responsibility Principle, these will not take over a responsibility that shall be enforced - // on the original GeometryFacade. Use the move version of getGeoListModel if moving the responsibility is intended. + // GeometryFacades are movable, but not copiable, so they need to be reconstructed (shallow copy + // of vector) Under the Single Responsibility Principle, these will not take over a + // responsibility that shall be enforced on the original GeometryFacade. Use the move version of + // getGeoListModel if moving the responsibility is intended. geomlist.reserve(geometrylist.size()); - for(auto & v : geometrylist) { + for (auto& v : geometrylist) { geomlist.push_back(GeometryFacade::getFacade(v->getGeometry())); } } -template <> SketcherExport -GeoListModel>::~GeoListModel() +template<> +SketcherExport GeoListModel>::~GeoListModel() { // GeometryFacade is responsible for taken ownership of its pointers and deleting them. - } // instantiate the types so that other translation units can access template constructors -template class SketcherExport GeoListModel; +template class SketcherExport GeoListModel; #if !defined(__MINGW32__) template class SketcherExport GeoListModel>; #else -// Remark: It looks like when implementing a method of GeoListModel for GeometryFacadeUniquePtr then under MinGW -// the explicit template instantiation doesn't do anything. As workaround all other methods must be declared separately -template SketcherExport const Part::Geometry* GeoListModel::getGeometryFromGeoId(int geoId) const; -template SketcherExport const Sketcher::GeometryFacade* GeoListModel::getGeometryFacadeFromGeoId(int geoId) const; -template SketcherExport int GeoListModel::getGeoIdFromGeomListIndex(int index) const; -template SketcherExport int GeoListModel::getVertexIdFromGeoElementId(const Sketcher::GeoElementId &) const; -template SketcherExport GeoElementId GeoListModel::getGeoElementIdFromVertexId(int); -template SketcherExport Base::Vector3d GeoListModel::getPoint(int geoId, Sketcher::PointPos pos) const; -template SketcherExport Base::Vector3d GeoListModel::getPoint(const GeoElementId &) const; -template SketcherExport GeoListModel GeoListModel::getGeoListModel - (std::vector&& geometrylist, int intgeocount, bool ownerT); +// Remark: It looks like when implementing a method of GeoListModel for GeometryFacadeUniquePtr then +// under MinGW the explicit template instantiation doesn't do anything. As workaround all other +// methods must be declared separately +template SketcherExport const Part::Geometry* +GeoListModel::getGeometryFromGeoId(int geoId) const; +template SketcherExport const Sketcher::GeometryFacade* +GeoListModel::getGeometryFacadeFromGeoId(int geoId) const; +template SketcherExport int +GeoListModel::getGeoIdFromGeomListIndex(int index) const; +template SketcherExport int GeoListModel::getVertexIdFromGeoElementId( + const Sketcher::GeoElementId&) const; +template SketcherExport GeoElementId +GeoListModel::getGeoElementIdFromVertexId(int); +template SketcherExport Base::Vector3d +GeoListModel::getPoint(int geoId, Sketcher::PointPos pos) const; +template SketcherExport Base::Vector3d +GeoListModel::getPoint(const GeoElementId&) const; +template SketcherExport GeoListModel +GeoListModel::getGeoListModel( + std::vector&& geometrylist, int intgeocount, bool ownerT); #endif -} // namespace Sketcher +}// namespace Sketcher -GeoListFacade Sketcher::getGeoListFacade(const GeoList & geolist) +GeoListFacade Sketcher::getGeoListFacade(const GeoList& geolist) { std::vector> facade; - facade.reserve( geolist.geomlist.size()); + facade.reserve(geolist.geomlist.size()); - for(auto geo : geolist.geomlist) + for (auto geo : geolist.geomlist) facade.push_back(GeometryFacade::getFacade(geo)); - auto geolistfacade = GeoListFacade::getGeoListModel(std::move(facade), geolist.getInternalCount()); + auto geolistfacade = + GeoListFacade::getGeoListModel(std::move(facade), geolist.getInternalCount()); return geolistfacade; } diff --git a/src/Mod/Sketcher/App/GeoList.h b/src/Mod/Sketcher/App/GeoList.h index 3f662bd7f4..74b8aa6525 100644 --- a/src/Mod/Sketcher/App/GeoList.h +++ b/src/Mod/Sketcher/App/GeoList.h @@ -30,19 +30,23 @@ #include "GeometryFacade.h" -namespace Base { - template< typename T > - class Vector3; +namespace Base +{ +template +class Vector3; } -namespace Part { - class Geometry; +namespace Part +{ +class Geometry; } -namespace Sketcher { +namespace Sketcher +{ } -namespace Sketcher { +namespace Sketcher +{ /** @brief Class for managing internal and external geometry as a single object * @details @@ -66,107 +70,126 @@ namespace Sketcher { * N.B.: Note that the index of the geomlist (all layers) and the GeoId can be converted * from each other as needed using the member functions (and sometimes the static functions). */ -template -class GeoListModel { +template +class GeoListModel +{ using Vector3d = Base::Vector3; protected: /** @brief - * Constructors are protected, use static methods getGeoListModel() to construct the objects instead. + * Constructors are protected, use static methods getGeoListModel() to construct the objects + * instead. * * Constructs the object from a list of geometry in geomlist format and the number of internal * geometries (non external) present in the list. * - * @param geometrylist: the geometry in geomlist format (external after internal in a single vector). + * @param geometrylist: the geometry in geomlist format (external after internal in a single + * vector). * @param intgeocount: the number of internal geometries (non external) in the list. - * @param ownerT: indicates whether the GeoListModel takes ownership of the elements of the std::vector (for pointers) + * @param ownerT: indicates whether the GeoListModel takes ownership of the elements of the + * std::vector (for pointers) */ - explicit GeoListModel(std::vector && geometrylist, int intgeocount, bool ownerT = false); + explicit GeoListModel(std::vector&& geometrylist, int intgeocount, bool ownerT = false); - explicit GeoListModel(const std::vector & geometrylist, int intgeocount); + explicit GeoListModel(const std::vector& geometrylist, int intgeocount); public: /** @brief Destructor having type dependent behaviour * * @warning - * For GeoList, the destructor will destruct the Part::Geometry pointers * only * if it was constructed with ownerT = true. + * For GeoList, the destructor will destruct the Part::Geometry pointers * only * if it was + * constructed with ownerT = true. * - * For GeoListFacade, the smart pointers will be deleted. However, a GeometryFacade does * not * delete the underlying naked pointers - * by default (which is mostly the desired behaviour as the ownership of the pointers belongs to sketchObject). If GeometryFacade is - * to delete the underlying naked pointers (because it is a temporal deep copy), then the GeometryFacade needs to get ownership (see - * setOwner method). + * For GeoListFacade, the smart pointers will be deleted. However, a GeometryFacade does * not * + * delete the underlying naked pointers by default (which is mostly the desired behaviour as the + * ownership of the pointers belongs to sketchObject). If GeometryFacade is to delete the + * underlying naked pointers (because it is a temporal deep copy), then the GeometryFacade needs + * to get ownership (see setOwner method). * */ ~GeoListModel(); // Explicit deletion to show intent (not that it is needed). This is a move only type. - GeoListModel(const GeoListModel &) = delete; + GeoListModel(const GeoListModel&) = delete; GeoListModel& operator=(const GeoListModel&) = delete; // enable move constructor and move assignment. This is a move only type. - GeoListModel(GeoListModel &&) = default; + GeoListModel(GeoListModel&&) = default; GeoListModel& operator=(GeoListModel&&) = default; /** @brief - * GeoListModel manages the lifetime of its internal std::vector. This means that while the actual ownership - * of the T parameter needs to be specified or separately handled. In the absence of that, a new vector will - * be created and the T elements shallow copied to the internal vector. + * GeoListModel manages the lifetime of its internal std::vector. This means that while the + * actual ownership of the T parameter needs to be specified or separately handled. In the + * absence of that, a new vector will be created and the T elements shallow copied to the + * internal vector. * - * The constness of the GeoListModel is tied to the constness of the std::vector from which it is constructed. + * The constness of the GeoListModel is tied to the constness of the std::vector from which it + * is constructed. * * @warning - * For GeoListFacade ownership at GeoListModel level cannot be taken (ownerT cannot be true). An assertion is raised - * if this happens. The ownership needs to be specified on the GeoListFacade objects themselves (setOwner method). + * For GeoListFacade ownership at GeoListModel level cannot be taken (ownerT cannot be true). An + * assertion is raised if this happens. The ownership needs to be specified on the GeoListFacade + * objects themselves (setOwner method). */ - static GeoListModel getGeoListModel(std::vector && geometrylist, int intgeocount, bool ownerT = false); - static const GeoListModel getGeoListModel(const std::vector & geometrylist, int intgeocount); + static GeoListModel getGeoListModel(std::vector&& geometrylist, int intgeocount, + bool ownerT = false); + static const GeoListModel getGeoListModel(const std::vector& geometrylist, + int intgeocount); /** @brief - * returns the geometry given by the GeoId - */ - const Part::Geometry * getGeometryFromGeoId(int geoId) const; + * returns the geometry given by the GeoId + */ + const Part::Geometry* getGeometryFromGeoId(int geoId) const; /** @brief returns a geometryfacade - * @warning If the underlying model of the list is a naked pointed (Part::Geometry *), i.e. a GeoList instantiation, the - * client (the user) bears responsibility for releasing the GeometryFacade pointer!! + * @warning If the underlying model of the list is a naked pointed (Part::Geometry *), i.e. a + * GeoList instantiation, the client (the user) bears responsibility for releasing the + * GeometryFacade pointer!! * - * This is not a problem when the model of the list is a std::unique_ptr, because the lifetime is tied to - * the GeometryFacade. It will destruct the pointer if it is the owner. + * This is not a problem when the model of the list is a + * std::unique_ptr, because the lifetime is tied to the + * GeometryFacade. It will destruct the pointer if it is the owner. */ - const Sketcher::GeometryFacade * getGeometryFacadeFromGeoId(int geoId) const; + const Sketcher::GeometryFacade* getGeometryFacadeFromGeoId(int geoId) const; /** @brief - * returns the GeoId index from the index in the geometry in geomlist format with which it was constructed. - * - * @param index: the index of the list of geometry in geomlist format. - */ + * returns the GeoId index from the index in the geometry in geomlist format with which it was + * constructed. + * + * @param index: the index of the list of geometry in geomlist format. + */ int getGeoIdFromGeomListIndex(int index) const; /** @brief - * returns the geometry given by the GeoId in the geometrylist in geomlist format provided as a parameter. - * - * @param geometrylist: the geometry in geomlist format (external after internal in a single vector). - * - * @param index: the index of the list of geometry in geomlist format. - */ - static const Part::Geometry * getGeometryFromGeoId(const std::vector & geometrylist, int geoId); + * returns the geometry given by the GeoId in the geometrylist in geomlist format provided as a + * parameter. + * + * @param geometrylist: the geometry in geomlist format (external after internal in a single + * vector). + * + * @param index: the index of the list of geometry in geomlist format. + */ + static const Part::Geometry* getGeometryFromGeoId(const std::vector& geometrylist, + int geoId); /** @brief returns a geometry facade - * @warning If the underlying model of the list is a naked pointed (Part::Geometry *), the client (the user) bears responsibility - * for releasing the GeometryFacade pointer!! + * @warning If the underlying model of the list is a naked pointed (Part::Geometry *), the + * client (the user) bears responsibility for releasing the GeometryFacade pointer!! * - * This is not a problem when the model of the list is a std::unique_ptr, because the lifetime is tied to - * the model itself. + * This is not a problem when the model of the list is a + * std::unique_ptr, because the lifetime is tied to the model itself. */ - static const Sketcher::GeometryFacade * getGeometryFacadeFromGeoId(const std::vector & geometrylist, int geoId); + static const Sketcher::GeometryFacade* + getGeometryFacadeFromGeoId(const std::vector& geometrylist, int geoId); /** @brief * Obtain a GeoElementId class {GeoId, Pos} given a VertexId. * - * A vertexId is a positive index of the vertex, where indices of external geometry taken higher positive values than normal geometry. - * It is the same format of vertex numbering used in the Sketcher, Sketch.cpp, and ViewProviderSketch. + * A vertexId is a positive index of the vertex, where indices of external geometry taken higher + * positive values than normal geometry. It is the same format of vertex numbering used in the + * Sketcher, Sketch.cpp, and ViewProviderSketch. * */ Sketcher::GeoElementId getGeoElementIdFromVertexId(int vertexId); @@ -175,31 +198,38 @@ public: /** @brief * Given an GeoElementId {GeoId, Pos}, it returns the index of the vertex in VertexId format. * - * A vertexId is a positive index of the vertex, where indices of external geometry taken higher positive values than normal geometry. - * It is the same format of vertex numbering used in the Sketcher, Sketch.cpp, and ViewProviderSketch. + * A vertexId is a positive index of the vertex, where indices of external geometry taken higher + * positive values than normal geometry. It is the same format of vertex numbering used in the + * Sketcher, Sketch.cpp, and ViewProviderSketch. * */ - int getVertexIdFromGeoElementId(const Sketcher::GeoElementId & geoelementId) const; + int getVertexIdFromGeoElementId(const Sketcher::GeoElementId& geoelementId) const; /** @brief * Returns a point coordinates given {GeoId, Pos}. */ Vector3d getPoint(int geoId, Sketcher::PointPos pos) const; - /** @brief + /** @brief * Returns a point coordinates given GeoElementId {GeoId, Pos}. */ - Vector3d getPoint(const GeoElementId & geid) const; + Vector3d getPoint(const GeoElementId& geid) const; /** @brief - * returns the amount of internal (normal, non-external) geometry objects. - */ - int getInternalCount() const { return intGeoCount;} + * returns the amount of internal (normal, non-external) geometry objects. + */ + int getInternalCount() const + { + return intGeoCount; + } /** @brief - * returns the amount of external geometry objects. - */ - int getExternalCount() const { return int(geomlist.size()) - intGeoCount;} + * returns the amount of external geometry objects. + */ + int getExternalCount() const + { + return int(geomlist.size()) - intGeoCount; + } /** @brief * return a reference to the internal geometry list vector. @@ -207,13 +237,16 @@ public: * @warning { It returns a reference to the internal list vector. The validity of the * reference depends on the lifetime of the GeoListModel object.} */ - std::vector & geometryList() { return const_cast &>(geomlist);} + std::vector& geometryList() + { + return const_cast&>(geomlist); + } public: std::vector geomlist; private: - Vector3d getPoint(const Part::Geometry * geo, Sketcher::PointPos pos) const; + Vector3d getPoint(const Part::Geometry* geo, Sketcher::PointPos pos) const; void rebuildVertexIndex() const; @@ -221,20 +254,20 @@ private: int intGeoCount; bool OwnerT; mutable bool indexInit; - mutable std::vector VertexId2GeoElementId; // these maps a lazy initialised on first demand. + mutable std::vector + VertexId2GeoElementId;// these maps a lazy initialised on first demand. mutable std::map GeoElementId2VertexId; }; -using GeometryPtr = Part::Geometry *; +using GeometryPtr = Part::Geometry*; using GeometryFacadeUniquePtr = std::unique_ptr; using GeoList = GeoListModel; using GeoListFacade = GeoListModel; -GeoListFacade getGeoListFacade(const GeoList & geolist); +GeoListFacade getGeoListFacade(const GeoList& geolist); -} // namespace Sketcher +}// namespace Sketcher -#endif // SKETCHER_GeoList_H - +#endif// SKETCHER_GeoList_H diff --git a/src/Mod/Sketcher/App/GeometryFacade.cpp b/src/Mod/Sketcher/App/GeometryFacade.cpp index d1f30bc9bf..f8c770d8f0 100644 --- a/src/Mod/Sketcher/App/GeometryFacade.cpp +++ b/src/Mod/Sketcher/App/GeometryFacade.cpp @@ -22,7 +22,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include "GeometryFacade.h" @@ -31,17 +31,19 @@ using namespace Sketcher; -TYPESYSTEM_SOURCE(Sketcher::GeometryFacade,Base::BaseClass) +TYPESYSTEM_SOURCE(Sketcher::GeometryFacade, Base::BaseClass) -GeometryFacade::GeometryFacade(): Geo(nullptr), OwnerGeo(false), SketchGeoExtension(nullptr) +GeometryFacade::GeometryFacade() + : Geo(nullptr), + OwnerGeo(false), + SketchGeoExtension(nullptr) +{} + +GeometryFacade::GeometryFacade(const Part::Geometry* geometry, bool owner) + : Geo(geometry), + OwnerGeo(owner) { - -} - -GeometryFacade::GeometryFacade(const Part::Geometry * geometry, bool owner) -: Geo(geometry), OwnerGeo(owner) -{ - assert(geometry); // This should never be nullptr, as this constructor is protected + assert(geometry);// This should never be nullptr, as this constructor is protected initExtension(); } @@ -52,29 +54,31 @@ GeometryFacade::~GeometryFacade() delete Geo; } -std::unique_ptr GeometryFacade::getFacade(Part::Geometry * geometry, bool owner) +std::unique_ptr GeometryFacade::getFacade(Part::Geometry* geometry, bool owner) { - if(geometry) + if (geometry) return std::unique_ptr(new GeometryFacade(geometry, owner)); else return std::unique_ptr(nullptr); - //return std::make_unique(geometry); // make_unique has no access to private constructor + // make_unique has no access to private constructor + // return std::make_unique(geometry); } -std::unique_ptr GeometryFacade::getFacade(const Part::Geometry * geometry) +std::unique_ptr GeometryFacade::getFacade(const Part::Geometry* geometry) { - if(geometry) + if (geometry) return std::unique_ptr(new GeometryFacade(geometry)); - else + else return std::unique_ptr(nullptr); - //return std::make_unique(geometry); // make_unique has no access to private constructor + // make_unique has no access to private constructor + // return std::make_unique(geometry); } -void GeometryFacade::setGeometry(Part::Geometry *geometry) +void GeometryFacade::setGeometry(Part::Geometry* geometry) { Geo = geometry; - if(geometry) + if (geometry) initExtension(); else THROWM(Base::ValueError, "GeometryFacade initialized with Geometry null pointer"); @@ -82,46 +86,48 @@ void GeometryFacade::setGeometry(Part::Geometry *geometry) void GeometryFacade::initExtension() { - if(!Geo->hasExtension(SketchGeometryExtension::getClassTypeId())) { + if (!Geo->hasExtension(SketchGeometryExtension::getClassTypeId())) { - getGeo()->setExtension(std::make_unique()); // Create getExtension + getGeo()->setExtension(std::make_unique());// Create getExtension - //Base::Console().Warning("%s\nSketcher Geometry without Extension: %s \n", boost::uuids::to_string(Geo->getTag()).c_str()); + // Base::Console().Warning("%s\nSketcher Geometry without Extension: %s \n", + // boost::uuids::to_string(Geo->getTag()).c_str()); } - SketchGeoExtension = - std::static_pointer_cast( - (Geo->getExtension(SketchGeometryExtension::getClassTypeId())).lock() - ); + SketchGeoExtension = std::static_pointer_cast( + (Geo->getExtension(SketchGeometryExtension::getClassTypeId())).lock()); } void GeometryFacade::initExtension() const { // const Geometry without SketchGeometryExtension cannot initialise a GeometryFacade - if(!Geo->hasExtension(SketchGeometryExtension::getClassTypeId())) - THROWM(Base::ValueError, "Cannot create a GeometryFacade out of a const Geometry pointer not having a SketchGeometryExtension!"); + if (!Geo->hasExtension(SketchGeometryExtension::getClassTypeId())) + THROWM(Base::ValueError, + "Cannot create a GeometryFacade out of a const Geometry pointer not having a " + "SketchGeometryExtension!"); - auto ext = std::static_pointer_cast(Geo->getExtension(SketchGeometryExtension::getClassTypeId()).lock()); + auto ext = std::static_pointer_cast( + Geo->getExtension(SketchGeometryExtension::getClassTypeId()).lock()); - const_cast(this)->SketchGeoExtension = ext; + const_cast(this)->SketchGeoExtension = ext; } -void GeometryFacade::throwOnNullPtr(const Part::Geometry * geo) +void GeometryFacade::throwOnNullPtr(const Part::Geometry* geo) { - if(!geo) + if (!geo) THROWM(Base::ValueError, "Geometry is nullptr!"); } -void GeometryFacade::ensureSketchGeometryExtension(Part::Geometry * geometry) +void GeometryFacade::ensureSketchGeometryExtension(Part::Geometry* geometry) { throwOnNullPtr(geometry); - if(!geometry->hasExtension(SketchGeometryExtension::getClassTypeId())) { - geometry->setExtension(std::make_unique()); // Create getExtension + if (!geometry->hasExtension(SketchGeometryExtension::getClassTypeId())) { + geometry->setExtension(std::make_unique());// Create getExtension } } -void GeometryFacade::copyId(const Part::Geometry * src, Part::Geometry * dst) +void GeometryFacade::copyId(const Part::Geometry* src, Part::Geometry* dst) { throwOnNullPtr(src); throwOnNullPtr(dst); @@ -131,7 +137,7 @@ void GeometryFacade::copyId(const Part::Geometry * src, Part::Geometry * dst) gfdst->setId(gfsrc->getId()); } -bool GeometryFacade::getConstruction(const Part::Geometry * geometry) +bool GeometryFacade::getConstruction(const Part::Geometry* geometry) { throwOnNullPtr(geometry); @@ -139,7 +145,7 @@ bool GeometryFacade::getConstruction(const Part::Geometry * geometry) return gf->getConstruction(); } -void GeometryFacade::setConstruction(Part::Geometry * geometry, bool construction) +void GeometryFacade::setConstruction(Part::Geometry* geometry, bool construction) { throwOnNullPtr(geometry); @@ -147,7 +153,7 @@ void GeometryFacade::setConstruction(Part::Geometry * geometry, bool constructio return gf->setConstruction(construction); } -bool GeometryFacade::isInternalType(const Part::Geometry * geometry, InternalType::InternalType type) +bool GeometryFacade::isInternalType(const Part::Geometry* geometry, InternalType::InternalType type) { throwOnNullPtr(geometry); @@ -155,7 +161,7 @@ bool GeometryFacade::isInternalType(const Part::Geometry * geometry, InternalTyp return gf->getInternalType() == type; } -bool GeometryFacade::isInternalAligned(const Part::Geometry * geometry) +bool GeometryFacade::isInternalAligned(const Part::Geometry* geometry) { throwOnNullPtr(geometry); @@ -163,7 +169,7 @@ bool GeometryFacade::isInternalAligned(const Part::Geometry * geometry) return gf->isInternalAligned(); } -bool GeometryFacade::getBlocked(const Part::Geometry * geometry) +bool GeometryFacade::getBlocked(const Part::Geometry* geometry) { throwOnNullPtr(geometry); @@ -171,7 +177,7 @@ bool GeometryFacade::getBlocked(const Part::Geometry * geometry) return gf->getBlocked(); } -PyObject * GeometryFacade::getPyObject() +PyObject* GeometryFacade::getPyObject() { return new GeometryFacadePy(new GeometryFacade(this->Geo)); } diff --git a/src/Mod/Sketcher/App/GeometryFacade.h b/src/Mod/Sketcher/App/GeometryFacade.h index fbad3e111b..4291ee6cd3 100644 --- a/src/Mod/Sketcher/App/GeometryFacade.h +++ b/src/Mod/Sketcher/App/GeometryFacade.h @@ -34,29 +34,34 @@ namespace Sketcher { class GeometryFacadePy; -/** @brief This class is a Facade to handle geometry and sketcher geometry extensions with a single sketcher specific interface +/** @brief This class is a Facade to handle geometry and sketcher geometry extensions with a single + * sketcher specific interface * * @details - * The facade privately inherits from a common interface it shares with the extension thereby implementing a compiler enforced - * same interface as the extension. It does not inherit from Part::Geometry and thus is intended to provide, in part a convenience - * subset of the interface of Part::Geometry, in part a different interface. + * The facade privately inherits from a common interface it shares with the extension thereby + * implementing a compiler enforced same interface as the extension. It does not inherit from + * Part::Geometry and thus is intended to provide, in part a convenience subset of the interface of + * Part::Geometry, in part a different interface. * - * GeometryFacade has private constructors and objects may only be created using the getFacade factory methods. + * GeometryFacade has private constructors and objects may only be created using the getFacade + * factory methods. * - * There is a version of getFacade taking a const Part::Geometry and producing a const GeometryFacade, and a non-const - * version producing a non-const GeometryFacade. So constness of the Part::Geometry object is preserved by the GeometryFacade - * container. + * There is a version of getFacade taking a const Part::Geometry and producing a const + * GeometryFacade, and a non-const version producing a non-const GeometryFacade. So constness of the + * Part::Geometry object is preserved by the GeometryFacade container. * - * There are some static convenience utility functions to simplify common operations such as ID copy or to ensure that a geometry - * object has the extension (creating the extension if not existing). + * There are some static convenience utility functions to simplify common operations such as ID copy + * or to ensure that a geometry object has the extension (creating the extension if not existing). * * @warning - * The const factory method will throw if the geometry does not have a SketchGeometryExtension (being const, it commits not to - * create one and modify the const Part::Geometry object). The non-const factory method will create the extension if not existing. + * The const factory method will throw if the geometry does not have a SketchGeometryExtension + * (being const, it commits not to create one and modify the const Part::Geometry object). The + * non-const factory method will create the extension if not existing. * * @warning - * If the Geometry Pointer fed into the factory method is a nullptr, a nullptr GeometryFacade is created. It should not be possible - * to create a GeometryFacade having a Part::Geometry * being a nullptr. + * If the Geometry Pointer fed into the factory method is a nullptr, a nullptr GeometryFacade is + * created. It should not be possible to create a GeometryFacade having a Part::Geometry * being a + * nullptr. * * A simple usage example: * @@ -86,43 +91,44 @@ class GeometryFacadePy; * GeometryFacade::setConstruction(copy, construction); * } * - * Note: The standard GeometryFacade stores Part::Geometry derived classes as a Part::Geometry *, while - * it has the ability to return a dynamic_cast-ed version to a provided type as follows: + * Note: The standard GeometryFacade stores Part::Geometry derived classes as a Part::Geometry *, + * while it has the ability to return a dynamic_cast-ed version to a provided type as follows: * * HLine->getGeometry(); * - * If for seamless operation it is convenient to have a given derived class of Part::Geometry, it is possible - * to use GeometryTypedFacade (see below). + * If for seamless operation it is convenient to have a given derived class of Part::Geometry, it is + * possible to use GeometryTypedFacade (see below). * * @remarks * Summary Remarks: * It is intended to have a separate type (not being a Geometry type). * it is intended to have the relevant interface in full for the sketcher extension only - * It is intended to work on borrowed memory allocation. But the getFacade has an owner parameter to take ownership of the - * geometry pointer if that is intended (this can also be achieved via the setOwner method once created). + * It is intended to work on borrowed memory allocation. But the getFacade has an owner parameter to + * take ownership of the geometry pointer if that is intended (this can also be achieved via the + * setOwner method once created). */ -class SketcherExport GeometryFacade : public Base::BaseClass, private ISketchGeometryExtension +class SketcherExport GeometryFacade: public Base::BaseClass, private ISketchGeometryExtension { -TYPESYSTEM_HEADER_WITH_OVERRIDE(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); protected: - explicit GeometryFacade(const Part::Geometry * geometry, bool owner = false); - GeometryFacade(); // As TYPESYSTEM requirement + explicit GeometryFacade(const Part::Geometry* geometry, bool owner = false); + GeometryFacade();// As TYPESYSTEM requirement friend class GeometryFacadePy; -public: // Factory methods - static std::unique_ptr getFacade(Part::Geometry * geometry, bool owner = false); - static std::unique_ptr getFacade(const Part::Geometry * geometry); +public:// Factory methods + static std::unique_ptr getFacade(Part::Geometry* geometry, bool owner = false); + static std::unique_ptr getFacade(const Part::Geometry* geometry); -public: // Utility methods - static void ensureSketchGeometryExtension(Part::Geometry * geometry); - static void copyId(const Part::Geometry * src, Part::Geometry * dst); - static bool getConstruction(const Part::Geometry * geometry); - static void setConstruction(Part::Geometry * geometry, bool construction); - static bool isInternalType(const Part::Geometry * geometry, InternalType::InternalType type); +public:// Utility methods + static void ensureSketchGeometryExtension(Part::Geometry* geometry); + static void copyId(const Part::Geometry* src, Part::Geometry* dst); + static bool getConstruction(const Part::Geometry* geometry); + static void setConstruction(Part::Geometry* geometry, bool construction); + static bool isInternalType(const Part::Geometry* geometry, InternalType::InternalType type); static bool isInternalAligned(const Part::Geometry* geometry); - static bool getBlocked(const Part::Geometry * geometry); + static bool getBlocked(const Part::Geometry* geometry); public: // Explicit deletion to show intent (not that it is needed) @@ -133,108 +139,228 @@ public: GeometryFacade& operator=(GeometryFacade&&) = default; ~GeometryFacade() override; - void setGeometry(Part::Geometry *geometry); + void setGeometry(Part::Geometry* geometry); - void setOwner(bool owner) { + void setOwner(bool owner) + { OwnerGeo = owner; } // returns if the facade is the owner of the geometry pointer. - bool getOwner() const { + bool getOwner() const + { return OwnerGeo; } // Geometry Extension Interface - inline long getId() const override {return getGeoExt()->getId();} - void setId(long id) override {getGeoExt()->setId(id);} + inline long getId() const override + { + return getGeoExt()->getId(); + } + void setId(long id) override + { + getGeoExt()->setId(id); + } - InternalType::InternalType getInternalType() const override {return getGeoExt()->getInternalType();} - void setInternalType(InternalType::InternalType type) override {getGeoExt()->setInternalType(type);} + InternalType::InternalType getInternalType() const override + { + return getGeoExt()->getInternalType(); + } + void setInternalType(InternalType::InternalType type) override + { + getGeoExt()->setInternalType(type); + } - bool testGeometryMode(int flag) const override { return getGeoExt()->testGeometryMode(flag); } - void setGeometryMode(int flag, bool v=true) override { getGeoExt()->setGeometryMode(flag, v); } + bool testGeometryMode(int flag) const override + { + return getGeoExt()->testGeometryMode(flag); + } + void setGeometryMode(int flag, bool v = true) override + { + getGeoExt()->setGeometryMode(flag, v); + } - int getGeometryLayerId() const override { return getGeoExt()->getGeometryLayerId();} - void setGeometryLayerId(int geolayer) override { getGeoExt()->setGeometryLayerId(geolayer);} + int getGeometryLayerId() const override + { + return getGeoExt()->getGeometryLayerId(); + } + void setGeometryLayerId(int geolayer) override + { + getGeoExt()->setGeometryLayerId(geolayer); + } // Convenience accessor - bool getBlocked() const { return this->testGeometryMode(GeometryMode::Blocked);} - void setBlocked(bool status = true) {this->setGeometryMode(GeometryMode::Blocked, status);} + bool getBlocked() const + { + return this->testGeometryMode(GeometryMode::Blocked); + } + void setBlocked(bool status = true) + { + this->setGeometryMode(GeometryMode::Blocked, status); + } - inline bool getConstruction() const {return this->testGeometryMode(GeometryMode::Construction);} - inline void setConstruction(bool construction) {this->setGeometryMode(GeometryMode::Construction, construction);} + inline bool getConstruction() const + { + return this->testGeometryMode(GeometryMode::Construction); + } + inline void setConstruction(bool construction) + { + this->setGeometryMode(GeometryMode::Construction, construction); + } - bool isInternalAligned() const { return this->getInternalType() != InternalType::None; } + bool isInternalAligned() const + { + return this->getInternalType() != InternalType::None; + } - bool isInternalType(InternalType::InternalType type) const { return this->getInternalType() == type; } + bool isInternalType(InternalType::InternalType type) const + { + return this->getInternalType() == type; + } // Geometry Extension Information - inline const std::string &getExtensionName () const {return SketchGeoExtension->getName();} + inline const std::string& getExtensionName() const + { + return SketchGeoExtension->getName(); + } // Geometry Element - template < typename GeometryT = Part::Geometry, - typename = typename std::enable_if< - std::is_base_of::type>::value - >::type - > - GeometryT * getGeometry() {return dynamic_cast(const_cast(Geo));} + template::type>::value>::type> + GeometryT* getGeometry() + { + return dynamic_cast(const_cast(Geo)); + } // Geometry Element - template < typename GeometryT = Part::Geometry, - typename = typename std::enable_if< - std::is_base_of::type>::value - >::type - > - const GeometryT * getGeometry() const {return dynamic_cast(Geo);} + template::type>::value>::type> + const GeometryT* getGeometry() const + { + return dynamic_cast(Geo); + } - PyObject *getPyObject() override; + PyObject* getPyObject() override; // Geometry Interface - TopoDS_Shape toShape() const {return getGeo()->toShape();} - const Handle(Geom_Geometry)& handle() const {return getGeo()->handle();} - Part::Geometry *copy() const {return getGeo()->copy();} - Part::Geometry *clone() const {return getGeo()->clone();} - boost::uuids::uuid getTag() const {return getGeo()->getTag();} + TopoDS_Shape toShape() const + { + return getGeo()->toShape(); + } + const Handle(Geom_Geometry) & handle() const + { + return getGeo()->handle(); + } + Part::Geometry* copy() const + { + return getGeo()->copy(); + } + Part::Geometry* clone() const + { + return getGeo()->clone(); + } + boost::uuids::uuid getTag() const + { + return getGeo()->getTag(); + } - std::vector> getExtensions() const {return getGeo()->getExtensions();} - bool hasExtension(const Base::Type & type) const {return getGeo()->hasExtension(type);} - bool hasExtension(const std::string & name) const {return getGeo()->hasExtension(name);} - std::weak_ptr getExtension(const Base::Type & type) const {return getGeo()->getExtension(type);} - std::weak_ptr getExtension(const std::string & name) const {return getGeo()->getExtension(name);} - void setExtension(std::unique_ptr &&geo) {return getGeo()->setExtension(std::move(geo));} - void deleteExtension(const Base::Type & type) {return getGeo()->deleteExtension(type);} - void deleteExtension(const std::string & name) {return getGeo()->deleteExtension(name);} + std::vector> getExtensions() const + { + return getGeo()->getExtensions(); + } + bool hasExtension(const Base::Type& type) const + { + return getGeo()->hasExtension(type); + } + bool hasExtension(const std::string& name) const + { + return getGeo()->hasExtension(name); + } + std::weak_ptr getExtension(const Base::Type& type) const + { + return getGeo()->getExtension(type); + } + std::weak_ptr getExtension(const std::string& name) const + { + return getGeo()->getExtension(name); + } + void setExtension(std::unique_ptr&& geo) + { + return getGeo()->setExtension(std::move(geo)); + } + void deleteExtension(const Base::Type& type) + { + return getGeo()->deleteExtension(type); + } + void deleteExtension(const std::string& name) + { + return getGeo()->deleteExtension(name); + } - void mirror(const Base::Vector3d & point) {return getGeo()->mirror(point);} - void mirror(const Base::Vector3d & point, Base::Vector3d dir) {return getGeo()->mirror(point, dir);} - void rotate(const Base::Placement & plm) {return getGeo()->rotate(plm);} - void scale(const Base::Vector3d & vec, double scale) {return getGeo()->scale(vec, scale);} - void transform(const Base::Matrix4D & mat) {return getGeo()->transform(mat);} - void translate(const Base::Vector3d & vec) {return getGeo()->translate(vec);} + void mirror(const Base::Vector3d& point) + { + return getGeo()->mirror(point); + } + void mirror(const Base::Vector3d& point, Base::Vector3d dir) + { + return getGeo()->mirror(point, dir); + } + void rotate(const Base::Placement& plm) + { + return getGeo()->rotate(plm); + } + void scale(const Base::Vector3d& vec, double scale) + { + return getGeo()->scale(vec, scale); + } + void transform(const Base::Matrix4D& mat) + { + return getGeo()->transform(mat); + } + void translate(const Base::Vector3d& vec) + { + return getGeo()->translate(vec); + } // convenience GeometryFunctions - bool isGeoType(const Base::Type &type) const { return getGeo()->getTypeId() == type;} + bool isGeoType(const Base::Type& type) const + { + return getGeo()->getTypeId() == type; + } private: void initExtension(); void initExtension() const; - const Part::Geometry * getGeo() const {return Geo;} - Part::Geometry * getGeo() {return const_cast(Geo);} + const Part::Geometry* getGeo() const + { + return Geo; + } + Part::Geometry* getGeo() + { + return const_cast(Geo); + } - std::shared_ptr getGeoExt() const {return SketchGeoExtension;} - std::shared_ptr getGeoExt () {return std::const_pointer_cast(SketchGeoExtension);} + std::shared_ptr getGeoExt() const + { + return SketchGeoExtension; + } + std::shared_ptr getGeoExt() + { + return std::const_pointer_cast(SketchGeoExtension); + } - static void throwOnNullPtr(const Part::Geometry * geo); + static void throwOnNullPtr(const Part::Geometry* geo); private: - const Part::Geometry * Geo; + const Part::Geometry* Geo; bool OwnerGeo; std::shared_ptr SketchGeoExtension; }; - /////////////////////////////////////////////////////////////////////////////////////// // // GeometryTypedFacade @@ -251,8 +377,8 @@ private: * HLine->getTypedGeometry()->setPoints(Base::Vector3d(0,0,0),Base::Vector3d(1,0,0)); * * If a facade is requested without passing an Part::Geometry derived object, the constructor - * of the indicated geometry type is called with any parameter passed as argument (emplace style). In - * this case the facade takes ownership of the newly created Part::Geometry object. + * of the indicated geometry type is called with any parameter passed as argument (emplace style). + * In this case the facade takes ownership of the newly created Part::Geometry object. * * Example of seamless operation with a GeomLineSegment: * @@ -261,27 +387,39 @@ private: * HLine->setConstruction(true); * ExternalGeo.push_back(HLine->getGeometry()); */ -template < typename GeometryT > -class SketcherExport GeometryTypedFacade : public GeometryFacade +template +class SketcherExport GeometryTypedFacade: public GeometryFacade { - static_assert( std::is_base_of::type>::value && - !std::is_same::type>::value, "Only for classes derived from Geometry!"); - private: - explicit GeometryTypedFacade(const Part::Geometry * geometry, bool owner = false):GeometryFacade(geometry, owner) {} - GeometryTypedFacade():GeometryFacade() {} + static_assert(std::is_base_of::type>::value + && !std::is_same::type>::value, + "Only for classes derived from Geometry!"); -public: // Factory methods - static std::unique_ptr> getTypedFacade(GeometryT * geometry, bool owner = false) { - if(geometry) { - return std::unique_ptr>(new GeometryTypedFacade(geometry, owner)); +private: + explicit GeometryTypedFacade(const Part::Geometry* geometry, bool owner = false) + : GeometryFacade(geometry, owner) + {} + GeometryTypedFacade() + : GeometryFacade() + {} + +public:// Factory methods + static std::unique_ptr> getTypedFacade(GeometryT* geometry, + bool owner = false) + { + if (geometry) { + return std::unique_ptr>( + new GeometryTypedFacade(geometry, owner)); } else { return std::unique_ptr>(nullptr); } } - static std::unique_ptr> getTypedFacade(const GeometryT * geometry) { - if(geometry) { - return std::unique_ptr>(new GeometryTypedFacade(geometry)); + static std::unique_ptr> + getTypedFacade(const GeometryT* geometry) + { + if (geometry) { + return std::unique_ptr>( + new GeometryTypedFacade(geometry)); } else { return std::unique_ptr>(nullptr); @@ -289,23 +427,28 @@ public: // Factory methods } // This function takes direct ownership of the object it creates. - template < typename... Args > - static std::unique_ptr> getTypedFacade(Args&&... args) { - return GeometryTypedFacade::getTypedFacade(new GeometryT(std::forward(args)...), true); + template + static std::unique_ptr> getTypedFacade(Args&&... args) + { + return GeometryTypedFacade::getTypedFacade(new GeometryT(std::forward(args)...), + true); } // Geometry Element - GeometryT * getTypedGeometry() {return GeometryFacade::getGeometry();} + GeometryT* getTypedGeometry() + { + return GeometryFacade::getGeometry(); + } // Geometry Element - GeometryT * getTypedGeometry() const {return GeometryFacade::getGeometry();} + GeometryT* getTypedGeometry() const + { + return GeometryFacade::getGeometry(); + } }; +}// namespace Sketcher - -} //namespace Sketcher - - -#endif // SKETCHER_GEOMETRYFACADE_H +#endif// SKETCHER_GEOMETRYFACADE_H diff --git a/src/Mod/Sketcher/App/GeometryFacadePyImp.cpp b/src/Mod/Sketcher/App/GeometryFacadePyImp.cpp index 1c3590d904..19a6c53903 100644 --- a/src/Mod/Sketcher/App/GeometryFacadePyImp.cpp +++ b/src/Mod/Sketcher/App/GeometryFacadePyImp.cpp @@ -24,14 +24,15 @@ #include #include +#include #include #include -#include #include #include #include #include "GeometryFacadePy.h" + #include "GeometryFacadePy.cpp" @@ -47,7 +48,7 @@ std::string GeometryFacadePy::representation() const return str.str(); } -PyObject *GeometryFacadePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* GeometryFacadePy::PyMake(struct _typeobject*, PyObject*, PyObject*)// Python wrapper { // create a new instance of PointPy and the Twin object return new GeometryFacadePy(new GeometryFacade()); @@ -56,18 +57,18 @@ PyObject *GeometryFacadePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // constructor method int GeometryFacadePy::PyInit(PyObject* args, PyObject* /*kwd*/) { - PyObject *object; - if (PyArg_ParseTuple(args,"O!",&(Part::GeometryPy::Type), &object)) { - Part::Geometry * geo = static_cast(object)->getGeometryPtr(); + PyObject* object; + if (PyArg_ParseTuple(args, "O!", &(Part::GeometryPy::Type), &object)) { + Part::Geometry* geo = static_cast(object)->getGeometryPtr(); getGeometryFacadePtr()->setGeometry(geo->clone()); return 0; } - PyErr_SetString(PyExc_TypeError, "Sketcher::GeometryFacade constructor accepts:\n" - "-- Part.Geometry\n" - ); + PyErr_SetString(PyExc_TypeError, + "Sketcher::GeometryFacade constructor accepts:\n" + "-- Part.Geometry\n"); return -1; } @@ -85,12 +86,12 @@ Py::String GeometryFacadePy::getInternalType() const { int internaltypeindex = (int)this->getGeometryFacadePtr()->getInternalType(); - if(internaltypeindex >= InternalType::NumInternalGeometryType) + if (internaltypeindex >= InternalType::NumInternalGeometryType) throw Py::NotImplementedError("String name of enum not implemented"); std::string typestr = SketchGeometryExtension::internaltype2str[internaltypeindex]; - return Py::String(typestr); + return Py::String(typestr); } void GeometryFacadePy::setInternalType(Py::String arg) @@ -98,7 +99,7 @@ void GeometryFacadePy::setInternalType(Py::String arg) std::string argstr = arg; InternalType::InternalType type; - if(SketchGeometryExtension::getInternalTypeFromName(argstr, type)) { + if (SketchGeometryExtension::getInternalTypeFromName(argstr, type)) { this->getGeometryFacadePtr()->setInternalType(type); return; } @@ -116,14 +117,14 @@ void GeometryFacadePy::setBlocked(Py::Boolean arg) getGeometryFacadePtr()->setBlocked(arg); } -PyObject* GeometryFacadePy::testGeometryMode(PyObject *args) +PyObject* GeometryFacadePy::testGeometryMode(PyObject* args) { char* flag; - if (PyArg_ParseTuple(args, "s",&flag)) { + if (PyArg_ParseTuple(args, "s", &flag)) { GeometryMode::GeometryMode mode; - if(SketchGeometryExtension::getGeometryModeFromName(flag, mode)) + if (SketchGeometryExtension::getGeometryModeFromName(flag, mode)) return new_reference_to(Py::Boolean(getGeometryFacadePtr()->testGeometryMode(mode))); PyErr_SetString(PyExc_TypeError, "Flag string does not exist."); @@ -134,15 +135,15 @@ PyObject* GeometryFacadePy::testGeometryMode(PyObject *args) return nullptr; } -PyObject* GeometryFacadePy::setGeometryMode(PyObject *args) +PyObject* GeometryFacadePy::setGeometryMode(PyObject* args) { - char * flag; - PyObject * bflag = Py_True; + char* flag; + PyObject* bflag = Py_True; if (PyArg_ParseTuple(args, "s|O!", &flag, &PyBool_Type, &bflag)) { GeometryMode::GeometryMode mode; - if(SketchGeometryExtension::getGeometryModeFromName(flag, mode)) { + if (SketchGeometryExtension::getGeometryModeFromName(flag, mode)) { getGeometryFacadePtr()->setGeometryMode(mode, Base::asBoolean(bflag)); Py_Return; } @@ -156,10 +157,10 @@ PyObject* GeometryFacadePy::setGeometryMode(PyObject *args) } -PyObject* GeometryFacadePy::mirror(PyObject *args) +PyObject* GeometryFacadePy::mirror(PyObject* args) { PyObject* o; - if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type),&o)) { + if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &o)) { Base::Vector3d vec = static_cast(o)->value(); getGeometryFacadePtr()->mirror(vec); Py_Return; @@ -167,22 +168,23 @@ PyObject* GeometryFacadePy::mirror(PyObject *args) PyErr_Clear(); PyObject* axis; - if (PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type),&o, - &(Base::VectorPy::Type),&axis)) { + if (PyArg_ParseTuple( + args, "O!O!", &(Base::VectorPy::Type), &o, &(Base::VectorPy::Type), &axis)) { Base::Vector3d pnt = static_cast(o)->value(); Base::Vector3d dir = static_cast(axis)->value(); getGeometryFacadePtr()->mirror(pnt, dir); Py_Return; } - PyErr_SetString(Part::PartExceptionOCCError, "either a point (vector) or axis (vector, vector) must be given"); + PyErr_SetString(Part::PartExceptionOCCError, + "either a point (vector) or axis (vector, vector) must be given"); return nullptr; } -PyObject* GeometryFacadePy::rotate(PyObject *args) +PyObject* GeometryFacadePy::rotate(PyObject* args) { PyObject* o; - if (!PyArg_ParseTuple(args, "O!", &(Base::PlacementPy::Type),&o)) + if (!PyArg_ParseTuple(args, "O!", &(Base::PlacementPy::Type), &o)) return nullptr; Base::Placement* plm = static_cast(o)->getPlacementPtr(); @@ -190,19 +192,19 @@ PyObject* GeometryFacadePy::rotate(PyObject *args) Py_Return; } -PyObject* GeometryFacadePy::scale(PyObject *args) +PyObject* GeometryFacadePy::scale(PyObject* args) { PyObject* o; double scale; Base::Vector3d vec; - if (PyArg_ParseTuple(args, "O!d", &(Base::VectorPy::Type),&o, &scale)) { + if (PyArg_ParseTuple(args, "O!d", &(Base::VectorPy::Type), &o, &scale)) { vec = static_cast(o)->value(); getGeometryFacadePtr()->scale(vec, scale); Py_Return; } PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!d", &PyTuple_Type,&o, &scale)) { + if (PyArg_ParseTuple(args, "O!d", &PyTuple_Type, &o, &scale)) { vec = Base::getVectorFromTuple(o); getGeometryFacadePtr()->scale(vec, scale); Py_Return; @@ -212,28 +214,28 @@ PyObject* GeometryFacadePy::scale(PyObject *args) return nullptr; } -PyObject* GeometryFacadePy::transform(PyObject *args) +PyObject* GeometryFacadePy::transform(PyObject* args) { PyObject* o; - if (!PyArg_ParseTuple(args, "O!", &(Base::MatrixPy::Type),&o)) + if (!PyArg_ParseTuple(args, "O!", &(Base::MatrixPy::Type), &o)) return nullptr; Base::Matrix4D mat = static_cast(o)->value(); getGeometryFacadePtr()->transform(mat); Py_Return; } -PyObject* GeometryFacadePy::translate(PyObject *args) +PyObject* GeometryFacadePy::translate(PyObject* args) { PyObject* o; Base::Vector3d vec; - if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type),&o)) { + if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &o)) { vec = static_cast(o)->value(); getGeometryFacadePtr()->translate(vec); Py_Return; } PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!", &PyTuple_Type,&o)) { + if (PyArg_ParseTuple(args, "O!", &PyTuple_Type, &o)) { vec = Base::getVectorFromTuple(o); getGeometryFacadePtr()->translate(vec); Py_Return; @@ -243,12 +245,12 @@ PyObject* GeometryFacadePy::translate(PyObject *args) return nullptr; } -PyObject* GeometryFacadePy::setExtension(PyObject *args) +PyObject* GeometryFacadePy::setExtension(PyObject* args) { PyObject* o; - if (PyArg_ParseTuple(args, "O!", &(Part::GeometryExtensionPy::Type),&o)) { - Part::GeometryExtension * ext; - ext = static_cast(o)->getGeometryExtensionPtr(); + if (PyArg_ParseTuple(args, "O!", &(Part::GeometryExtensionPy::Type), &o)) { + Part::GeometryExtension* ext; + ext = static_cast(o)->getGeometryExtensionPtr(); // make copy of Python managed memory and wrap it in smart pointer auto cpy = ext->copy(); @@ -261,153 +263,159 @@ PyObject* GeometryFacadePy::setExtension(PyObject *args) return nullptr; } -PyObject* GeometryFacadePy::getExtensionOfType(PyObject *args) +PyObject* GeometryFacadePy::getExtensionOfType(PyObject* args) { char* o; if (PyArg_ParseTuple(args, "s", &o)) { Base::Type type = Base::Type::fromName(o); - if(type != Base::Type::badType()) { + if (type != Base::Type::badType()) { try { - std::shared_ptr ext(this->getGeometryFacadePtr()->getExtension(type)); + std::shared_ptr ext( + this->getGeometryFacadePtr()->getExtension(type)); - // we create a copy and transfer this copy's memory management responsibility to Python + // we create a copy and transfer this copy's memory management responsibility to + // Python PyObject* cpy = ext->copyPyObject(); return cpy; } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); return nullptr; } - catch(const std::bad_weak_ptr&) { - PyErr_SetString(Part::PartExceptionOCCError, "Geometry extension does not exist anymore."); + catch (const std::bad_weak_ptr&) { + PyErr_SetString(Part::PartExceptionOCCError, + "Geometry extension does not exist anymore."); return nullptr; } - catch(Base::NotImplementedError&) { - PyErr_SetString(Part::PartExceptionOCCError, "Geometry extension does not implement a Python counterpart."); + catch (Base::NotImplementedError&) { + PyErr_SetString(Part::PartExceptionOCCError, + "Geometry extension does not implement a Python counterpart."); return nullptr; } } - else - { + else { PyErr_SetString(Part::PartExceptionOCCError, "Exception type does not exist"); return nullptr; } - } - PyErr_SetString(Part::PartExceptionOCCError, "A string with the name of the geometry extension type was expected"); + PyErr_SetString(Part::PartExceptionOCCError, + "A string with the name of the geometry extension type was expected"); return nullptr; } -PyObject* GeometryFacadePy::getExtensionOfName(PyObject *args) +PyObject* GeometryFacadePy::getExtensionOfName(PyObject* args) { char* o; if (PyArg_ParseTuple(args, "s", &o)) { try { - std::shared_ptr ext(this->getGeometryFacadePtr()->getExtension(std::string(o))); + std::shared_ptr ext( + this->getGeometryFacadePtr()->getExtension(std::string(o))); // we create a copy and transfer this copy's memory management responsibility to Python PyObject* cpy = ext->copyPyObject(); return cpy; } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); return nullptr; } - catch(const std::bad_weak_ptr&) { - PyErr_SetString(Part::PartExceptionOCCError, "Geometry extension does not exist anymore."); + catch (const std::bad_weak_ptr&) { + PyErr_SetString(Part::PartExceptionOCCError, + "Geometry extension does not exist anymore."); return nullptr; } - catch(Base::NotImplementedError&) { - PyErr_SetString(Part::PartExceptionOCCError, "Geometry extension does not implement a Python counterpart."); + catch (Base::NotImplementedError&) { + PyErr_SetString(Part::PartExceptionOCCError, + "Geometry extension does not implement a Python counterpart."); return nullptr; } } - PyErr_SetString(Part::PartExceptionOCCError, "A string with the name of the geometry extension was expected"); + PyErr_SetString(Part::PartExceptionOCCError, + "A string with the name of the geometry extension was expected"); return nullptr; } -PyObject* GeometryFacadePy::hasExtensionOfType(PyObject *args) +PyObject* GeometryFacadePy::hasExtensionOfType(PyObject* args) { char* o; if (PyArg_ParseTuple(args, "s", &o)) { Base::Type type = Base::Type::fromName(o); - if(type != Base::Type::badType()) { + if (type != Base::Type::badType()) { try { - return Py::new_reference_to(Py::Boolean(this->getGeometryFacadePtr()->hasExtension(type))); + return Py::new_reference_to( + Py::Boolean(this->getGeometryFacadePtr()->hasExtension(type))); } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); return nullptr; } } - else - { + else { PyErr_SetString(Part::PartExceptionOCCError, "Exception type does not exist"); return nullptr; } - } - PyErr_SetString(Part::PartExceptionOCCError, "A string with the type of the geometry extension was expected"); + PyErr_SetString(Part::PartExceptionOCCError, + "A string with the type of the geometry extension was expected"); return nullptr; } -PyObject* GeometryFacadePy::hasExtensionOfName(PyObject *args) +PyObject* GeometryFacadePy::hasExtensionOfName(PyObject* args) { char* o; if (PyArg_ParseTuple(args, "s", &o)) { try { - return Py::new_reference_to(Py::Boolean(this->getGeometryFacadePtr()->hasExtension(std::string(o)))); + return Py::new_reference_to( + Py::Boolean(this->getGeometryFacadePtr()->hasExtension(std::string(o)))); } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); return nullptr; } - } - PyErr_SetString(Part::PartExceptionOCCError, "A string with the type of the geometry extension was expected"); + PyErr_SetString(Part::PartExceptionOCCError, + "A string with the type of the geometry extension was expected"); return nullptr; } -PyObject* GeometryFacadePy::deleteExtensionOfType(PyObject *args) +PyObject* GeometryFacadePy::deleteExtensionOfType(PyObject* args) { char* o; if (PyArg_ParseTuple(args, "s", &o)) { Base::Type type = Base::Type::fromName(o); - if(type != Base::Type::badType()) { + if (type != Base::Type::badType()) { try { this->getGeometryFacadePtr()->deleteExtension(type); Py_Return; } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); return nullptr; } } - else - { + else { PyErr_SetString(Part::PartExceptionOCCError, "Type does not exist"); return nullptr; } - } PyErr_SetString(Part::PartExceptionOCCError, "A string with a type object was expected"); return nullptr; } -PyObject* GeometryFacadePy::deleteExtensionOfName(PyObject *args) +PyObject* GeometryFacadePy::deleteExtensionOfName(PyObject* args) { char* o; if (PyArg_ParseTuple(args, "s", &o)) { @@ -416,38 +424,40 @@ PyObject* GeometryFacadePy::deleteExtensionOfName(PyObject *args) this->getGeometryFacadePtr()->deleteExtension(std::string(o)); Py_Return; } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); return nullptr; } } - PyErr_SetString(Part::PartExceptionOCCError, "A string with the name of the extension was expected"); + PyErr_SetString(Part::PartExceptionOCCError, + "A string with the name of the extension was expected"); return nullptr; } -PyObject* GeometryFacadePy::getExtensions(PyObject *args) +PyObject* GeometryFacadePy::getExtensions(PyObject* args) { - if (!PyArg_ParseTuple(args, "")){ + if (!PyArg_ParseTuple(args, "")) { PyErr_SetString(Part::PartExceptionOCCError, "No arguments were expected"); return nullptr; } try { - const std::vector> ext = this->getGeometryFacadePtr()->getExtensions(); + const std::vector> ext = + this->getGeometryFacadePtr()->getExtensions(); Py::List list; - for (std::size_t i=0; i p = ext[i].lock(); - if(p) { + if (p) { // we create a python copy and add it to the list try { list.append(Py::asObject(p->copyPyObject())); } - catch(Base::NotImplementedError&) { + catch (Base::NotImplementedError&) { // silently ignoring extensions not having a Python object } } @@ -455,11 +465,10 @@ PyObject* GeometryFacadePy::getExtensions(PyObject *args) return Py::new_reference_to(list); } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); return nullptr; } - } Py::Boolean GeometryFacadePy::getConstruction() const @@ -467,7 +476,7 @@ Py::Boolean GeometryFacadePy::getConstruction() const return Py::Boolean(getGeometryFacadePtr()->getConstruction()); } -void GeometryFacadePy::setConstruction(Py::Boolean arg) +void GeometryFacadePy::setConstruction(Py::Boolean arg) { getGeometryFacadePtr()->setConstruction(arg); } @@ -495,17 +504,17 @@ Py::Object GeometryFacadePy::getGeometry() const return Py::Object(geo->getPyObject(), true); } -void GeometryFacadePy::setGeometry(Py::Object arg) +void GeometryFacadePy::setGeometry(Py::Object arg) { if (PyObject_TypeCheck(arg.ptr(), &(Part::GeometryPy::Type))) { - Part::GeometryPy * gp = static_cast(arg.ptr()); + Part::GeometryPy* gp = static_cast(arg.ptr()); getGeometryFacadePtr()->setGeometry(gp->getGeometryPtr()->clone()); } } -PyObject *GeometryFacadePy::getCustomAttributes(const char* /*attr*/) const +PyObject* GeometryFacadePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Sketcher/App/PreCompiled.cpp b/src/Mod/Sketcher/App/PreCompiled.cpp index 1e5d389dd2..7cd1cae80f 100644 --- a/src/Mod/Sketcher/App/PreCompiled.cpp +++ b/src/Mod/Sketcher/App/PreCompiled.cpp @@ -21,4 +21,4 @@ ***************************************************************************/ -#include "PreCompiled.h" +#include "PreCompiled.h" diff --git a/src/Mod/Sketcher/App/PreCompiled.h b/src/Mod/Sketcher/App/PreCompiled.h index 3a5014fac5..c050ae091a 100644 --- a/src/Mod/Sketcher/App/PreCompiled.h +++ b/src/Mod/Sketcher/App/PreCompiled.h @@ -43,15 +43,17 @@ #include // OpenCasCade -#include -#include #include #include #include #include #include #include +#include +#include #include +#include +#include #include #include #include @@ -60,8 +62,19 @@ #include #include #include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include @@ -69,25 +82,12 @@ #include #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #elif defined(FC_OS_WIN32) #ifndef NOMINMAX -# define NOMINMAX +#define NOMINMAX #endif -# include -#endif // _PreComp_ +#include +#endif// _PreComp_ #endif diff --git a/src/Mod/Sketcher/App/PropertyConstraintList.cpp b/src/Mod/Sketcher/App/PropertyConstraintList.cpp index 244513f6cc..a532faa1b7 100644 --- a/src/Mod/Sketcher/App/PropertyConstraintList.cpp +++ b/src/Mod/Sketcher/App/PropertyConstraintList.cpp @@ -22,18 +22,18 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include #include #include #include -#include #include +#include -#include "PropertyConstraintList.h" #include "ConstraintPy.h" +#include "PropertyConstraintList.h" using namespace App; @@ -52,32 +52,32 @@ TYPESYSTEM_SOURCE(Sketcher::PropertyConstraintList, App::PropertyLists) PropertyConstraintList::PropertyConstraintList() - : validGeometryKeys(0) - , invalidGeometry(true) - , restoreFromTransaction(false) - , invalidIndices(false) -{ - -} + : validGeometryKeys(0), + invalidGeometry(true), + restoreFromTransaction(false), + invalidIndices(false) +{} PropertyConstraintList::~PropertyConstraintList() { for (std::vector::iterator it = _lValueList.begin(); it != _lValueList.end(); ++it) - if (*it) delete *it; + if (*it) + delete *it; } App::ObjectIdentifier PropertyConstraintList::makeArrayPath(int idx) { - return App::ObjectIdentifier(*this,idx); + return App::ObjectIdentifier(*this, idx); } -App::ObjectIdentifier PropertyConstraintList::makeSimplePath(const Constraint * c) +App::ObjectIdentifier PropertyConstraintList::makeSimplePath(const Constraint* c) { - return App::ObjectIdentifier(*this) << App::ObjectIdentifier::SimpleComponent( - App::ObjectIdentifier::String(c->Name, !ExpressionParser::isTokenAnIndentifier(c->Name))); + return App::ObjectIdentifier(*this) + << App::ObjectIdentifier::SimpleComponent(App::ObjectIdentifier::String( + c->Name, !ExpressionParser::isTokenAnIndentifier(c->Name))); } -App::ObjectIdentifier PropertyConstraintList::makePath(int idx, const Constraint * c) +App::ObjectIdentifier PropertyConstraintList::makePath(int idx, const Constraint* c) { return c->Name.empty() ? makeArrayPath(idx) : makeSimplePath(c); } @@ -176,13 +176,14 @@ void PropertyConstraintList::setValue(const Constraint* lValue) void PropertyConstraintList::setValues(const std::vector& lValue) { auto copy = lValue; - for(auto &cstr : copy) + for (auto& cstr : copy) cstr = cstr->clone(); setValues(std::move(copy)); } -void PropertyConstraintList::setValues(std::vector&& lValue) { +void PropertyConstraintList::setValues(std::vector&& lValue) +{ aboutToSetValue(); applyValues(std::move(lValue)); hasSetValue(); @@ -190,18 +191,19 @@ void PropertyConstraintList::setValues(std::vector&& lValue) { void PropertyConstraintList::applyValues(std::vector&& lValue) { - std::set oldVals(_lValueList.begin(),_lValueList.end()); + std::set oldVals(_lValueList.begin(), _lValueList.end()); std::map renamed; std::set removed; boost::unordered_map newValueMap; /* Check for renames */ for (unsigned int i = 0; i < lValue.size(); i++) { - boost::unordered_map::const_iterator j = valueMap.find(lValue[i]->tag); + boost::unordered_map::const_iterator j = + valueMap.find(lValue[i]->tag); if (j != valueMap.end()) { - if(i != j->second || _lValueList[j->second]->Name != lValue[i]->Name) { - App::ObjectIdentifier old_oid(makePath(j->second, _lValueList[j->second] )); + if (i != j->second || _lValueList[j->second]->Name != lValue[i]->Name) { + App::ObjectIdentifier old_oid(makePath(j->second, _lValueList[j->second])); App::ObjectIdentifier new_oid(makePath(i, lValue[i])); renamed[old_oid] = new_oid; } @@ -215,13 +217,14 @@ void PropertyConstraintList::applyValues(std::vector&& lValue) } /* Collect info about removed elements */ - for(auto &v : valueMap) - removed.insert(makePath(v.second,_lValueList[v.second])); + for (auto& v : valueMap) + removed.insert(makePath(v.second, _lValueList[v.second])); /* Update value map with new tags from new array */ valueMap = std::move(newValueMap); - /* Signal removes first, in case renamed values below have the same names as some of the removed ones. */ + /* Signal removes first, in case renamed values below have the same names as some of the removed + * ones. */ if (!removed.empty() && !restoreFromTransaction) signalConstraintsRemoved(removed); @@ -232,52 +235,54 @@ void PropertyConstraintList::applyValues(std::vector&& lValue) _lValueList = std::move(lValue); /* Clean-up; remove old values */ - for(auto &v : oldVals) + for (auto& v : oldVals) delete v; } -PyObject *PropertyConstraintList::getPyObject() +PyObject* PropertyConstraintList::getPyObject() { PyObject* list = PyList_New(getSize()); for (int i = 0; i < getSize(); i++) - PyList_SetItem( list, i, _lValueList[i]->getPyObject()); + PyList_SetItem(list, i, _lValueList[i]->getPyObject()); return list; } -bool PropertyConstraintList::getPyPathValue(const App::ObjectIdentifier &path, Py::Object &res) const { - if(path.numSubComponents()!=2 || path.getPropertyComponent(0).getName()!=getName()) +bool PropertyConstraintList::getPyPathValue(const App::ObjectIdentifier& path, + Py::Object& res) const +{ + if (path.numSubComponents() != 2 || path.getPropertyComponent(0).getName() != getName()) return false; - const ObjectIdentifier::Component & c1 = path.getPropertyComponent(1); + const ObjectIdentifier::Component& c1 = path.getPropertyComponent(1); - const Constraint *cstr = nullptr; + const Constraint* cstr = nullptr; if (c1.isArray()) cstr = _lValueList[c1.getIndex(_lValueList.size())]; else if (c1.isSimple()) { ObjectIdentifier::Component c1 = path.getPropertyComponent(1); - for(auto c : _lValueList) { - if(c->Name == c1.getName()) { + for (auto c : _lValueList) { + if (c->Name == c1.getName()) { cstr = c; break; } } } - if(!cstr) + if (!cstr) return false; Quantity q = cstr->getPresentationValue(); res = new Base::QuantityPy(new Base::Quantity(q)); return true; } -void PropertyConstraintList::setPyObject(PyObject *value) +void PropertyConstraintList::setPyObject(PyObject* value) { if (PyList_Check(value)) { Py_ssize_t nSize = PyList_Size(value); std::vector values; values.resize(nSize); - for (Py_ssize_t i=0; i < nSize; ++i) { + for (Py_ssize_t i = 0; i < nSize; ++i) { PyObject* item = PyList_GetItem(value, i); if (!PyObject_TypeCheck(item, &(ConstraintPy::Type))) { std::string error = std::string("types in list must be 'Constraint', not "); @@ -291,7 +296,7 @@ void PropertyConstraintList::setPyObject(PyObject *value) setValues(values); } else if (PyObject_TypeCheck(value, &(ConstraintPy::Type))) { - ConstraintPy *pcObject = static_cast(value); + ConstraintPy* pcObject = static_cast(value); setValue(pcObject->getConstraintPtr()); } else { @@ -301,17 +306,17 @@ void PropertyConstraintList::setPyObject(PyObject *value) } } -void PropertyConstraintList::Save(Writer &writer) const +void PropertyConstraintList::Save(Writer& writer) const { - writer.Stream() << writer.ind() << "" << endl; + writer.Stream() << writer.ind() << "" << endl; writer.incInd(); for (int i = 0; i < getSize(); i++) _lValueList[i]->Save(writer); writer.decInd(); - writer.Stream() << writer.ind() << "" << endl ; + writer.Stream() << writer.ind() << "" << endl; } -void PropertyConstraintList::Restore(Base::XMLReader &reader) +void PropertyConstraintList::Restore(Base::XMLReader& reader) { // read my element reader.readElement("ConstraintList"); @@ -321,7 +326,7 @@ void PropertyConstraintList::Restore(Base::XMLReader &reader) std::vector values; values.reserve(count); for (int i = 0; i < count; i++) { - Constraint *newC = new Constraint(); + Constraint* newC = new Constraint(); newC->Restore(reader); // To keep upward compatibility ignore unknown constraint types if (newC->Type < Sketcher::NumConstraintTypes) { @@ -339,15 +344,15 @@ void PropertyConstraintList::Restore(Base::XMLReader &reader) setValues(std::move(values)); } -Property *PropertyConstraintList::Copy() const +Property* PropertyConstraintList::Copy() const { - PropertyConstraintList *p = new PropertyConstraintList(); + PropertyConstraintList* p = new PropertyConstraintList(); p->applyValidGeometryKeys(validGeometryKeys); p->setValues(_lValueList); return p; } -void PropertyConstraintList::Paste(const Property &from) +void PropertyConstraintList::Paste(const Property& from) { Base::StateLocker lock(restoreFromTransaction, true); const PropertyConstraintList& FromList = dynamic_cast(from); @@ -362,7 +367,7 @@ unsigned int PropertyConstraintList::getMemSize() const return size; } -void PropertyConstraintList::acceptGeometry(const std::vector &GeoList) +void PropertyConstraintList::acceptGeometry(const std::vector& GeoList) { aboutToSetValue(); validGeometryKeys.clear(); @@ -373,21 +378,21 @@ void PropertyConstraintList::acceptGeometry(const std::vector hasSetValue(); } -void PropertyConstraintList::applyValidGeometryKeys(const std::vector &keys) +void PropertyConstraintList::applyValidGeometryKeys(const std::vector& keys) { validGeometryKeys = keys; } -bool PropertyConstraintList::checkGeometry(const std::vector &GeoList) +bool PropertyConstraintList::checkGeometry(const std::vector& GeoList) { if (!scanGeometry(GeoList)) { invalidGeometry = true; return invalidGeometry; } - //if we made it here, geometry is OK + // if we made it here, geometry is OK if (invalidGeometry) { - //geometry was bad, but now it became OK. + // geometry was bad, but now it became OK. invalidGeometry = false; touch(); } @@ -400,18 +405,18 @@ bool PropertyConstraintList::checkConstraintIndices(int geomax, int geomin) int mininternalgeoid = std::numeric_limits::max(); int maxinternalgeoid = GeoEnum::GeoUndef; - auto cmin = [] (int previousmin, int cindex) { - if( cindex == GeoEnum::GeoUndef ) + auto cmin = [](int previousmin, int cindex) { + if (cindex == GeoEnum::GeoUndef) return previousmin; - return ( cindex < previousmin )? cindex : previousmin; + return (cindex < previousmin) ? cindex : previousmin; }; - auto cmax = [] (int previousmax, int cindex) { - return ( cindex > previousmax )? cindex : previousmax; + auto cmax = [](int previousmax, int cindex) { + return (cindex > previousmax) ? cindex : previousmax; }; - for (const auto &v : _lValueList) { + for (const auto& v : _lValueList) { mininternalgeoid = cmin(mininternalgeoid, v->First); mininternalgeoid = cmin(mininternalgeoid, v->Second); @@ -422,7 +427,7 @@ bool PropertyConstraintList::checkConstraintIndices(int geomax, int geomin) maxinternalgeoid = cmax(maxinternalgeoid, v->Third); } - if(maxinternalgeoid > geomax || mininternalgeoid < geomin) + if (maxinternalgeoid > geomax || mininternalgeoid < geomin) invalidIndices = true; else invalidIndices = false; @@ -436,15 +441,15 @@ bool PropertyConstraintList::checkConstraintIndices(int geomax, int geomin) * \param GeoList - new geometry list to be checked * \return false, if the types have changed. */ -bool PropertyConstraintList::scanGeometry(const std::vector &GeoList) const +bool PropertyConstraintList::scanGeometry(const std::vector& GeoList) const { if (validGeometryKeys.size() != GeoList.size()) { return false; } - unsigned int i=0; - for (std::vector< Part::Geometry * >::const_iterator it=GeoList.begin(); - it != GeoList.end(); ++it, i++) { + unsigned int i = 0; + for (std::vector::const_iterator it = GeoList.begin(); it != GeoList.end(); + ++it, i++) { if (validGeometryKeys[i] != (*it)->getTypeId().getKey()) { return false; } @@ -453,7 +458,7 @@ bool PropertyConstraintList::scanGeometry(const std::vector &G return true; } -string PropertyConstraintList::getConstraintName(const std::string & name, int i) +string PropertyConstraintList::getConstraintName(const std::string& name, int i) { if (!name.empty()) return name; @@ -469,27 +474,27 @@ string PropertyConstraintList::getConstraintName(int i) return str.str(); } -bool PropertyConstraintList::validConstraintName(const std::string & name) +bool PropertyConstraintList::validConstraintName(const std::string& name) { return !name.empty(); } ObjectIdentifier PropertyConstraintList::createPath(int ConstrNbr) const { - return App::ObjectIdentifier(*this,ConstrNbr); + return App::ObjectIdentifier(*this, ConstrNbr); } -int PropertyConstraintList::getIndexFromConstraintName(const string &name) +int PropertyConstraintList::getIndexFromConstraintName(const string& name) { - return std::atoi(name.substr(10,4000).c_str()) - 1; + return std::atoi(name.substr(10, 4000).c_str()) - 1; } -void PropertyConstraintList::setPathValue(const ObjectIdentifier &path, const boost::any &value) +void PropertyConstraintList::setPathValue(const ObjectIdentifier& path, const boost::any& value) { - if(path.numSubComponents()!=2 || path.getPropertyComponent(0).getName()!=getName()) - FC_THROWM(Base::ValueError,"invalid constraint path " << path.toString()); + if (path.numSubComponents() != 2 || path.getPropertyComponent(0).getName() != getName()) + FC_THROWM(Base::ValueError, "invalid constraint path " << path.toString()); - const ObjectIdentifier::Component & c1 = path.getPropertyComponent(1); + const ObjectIdentifier::Component& c1 = path.getPropertyComponent(1); double dvalue; if (value.type() == typeid(double)) @@ -501,18 +506,18 @@ void PropertyConstraintList::setPathValue(const ObjectIdentifier &path, const bo else if (value.type() == typeid(int)) dvalue = App::any_cast(value); else if (value.type() == typeid(Quantity)) - dvalue = (App::any_cast(value)).getValue(); + dvalue = (App::any_cast(value)).getValue(); else throw std::bad_cast(); if (c1.isArray()) { size_t index = c1.getIndex(_lValueList.size()); switch (_lValueList[index]->Type) { - case Angle: - dvalue = Base::toRadians(dvalue); - break; - default: - break; + case Angle: + dvalue = Base::toRadians(dvalue); + break; + default: + break; } aboutToSetValue(); _lValueList[index]->setValue(dvalue); @@ -520,16 +525,18 @@ void PropertyConstraintList::setPathValue(const ObjectIdentifier &path, const bo return; } else if (c1.isSimple()) { - for (std::vector::const_iterator it = _lValueList.begin(); it != _lValueList.end(); ++it) { + for (std::vector::const_iterator it = _lValueList.begin(); + it != _lValueList.end(); + ++it) { int index = it - _lValueList.begin(); if ((*it)->Name == c1.getName()) { switch (_lValueList[index]->Type) { - case Angle: - dvalue = Base::toRadians(dvalue); - break; - default: - break; + case Angle: + dvalue = Base::toRadians(dvalue); + break; + default: + break; } aboutToSetValue(); _lValueList[index]->setValue(dvalue); @@ -538,15 +545,15 @@ void PropertyConstraintList::setPathValue(const ObjectIdentifier &path, const bo } } } - FC_THROWM(Base::ValueError,"invalid constraint path " << path.toString()); + FC_THROWM(Base::ValueError, "invalid constraint path " << path.toString()); } -const Constraint * PropertyConstraintList::getConstraint(const ObjectIdentifier &path) const +const Constraint* PropertyConstraintList::getConstraint(const ObjectIdentifier& path) const { - if(path.numSubComponents()!=2 || path.getPropertyComponent(0).getName()!=getName()) - FC_THROWM(Base::ValueError,"Invalid constraint path " << path.toString()); + if (path.numSubComponents() != 2 || path.getPropertyComponent(0).getName() != getName()) + FC_THROWM(Base::ValueError, "Invalid constraint path " << path.toString()); - const ObjectIdentifier::Component & c1 = path.getPropertyComponent(1); + const ObjectIdentifier::Component& c1 = path.getPropertyComponent(1); if (c1.isArray()) { return _lValueList[c1.getIndex(_lValueList.size())]; @@ -554,44 +561,49 @@ const Constraint * PropertyConstraintList::getConstraint(const ObjectIdentifier else if (c1.isSimple()) { ObjectIdentifier::Component c1 = path.getPropertyComponent(1); - for (std::vector::const_iterator it = _lValueList.begin(); it != _lValueList.end(); ++it) { + for (std::vector::const_iterator it = _lValueList.begin(); + it != _lValueList.end(); + ++it) { if ((*it)->Name == c1.getName()) return *it; } } - FC_THROWM(Base::ValueError,"Invalid constraint path " << path.toString()); + FC_THROWM(Base::ValueError, "Invalid constraint path " << path.toString()); } -const boost::any PropertyConstraintList::getPathValue(const ObjectIdentifier &path) const +const boost::any PropertyConstraintList::getPathValue(const ObjectIdentifier& path) const { return boost::any(getConstraint(path)->getPresentationValue()); } -ObjectIdentifier PropertyConstraintList::canonicalPath(const ObjectIdentifier &p) const +ObjectIdentifier PropertyConstraintList::canonicalPath(const ObjectIdentifier& p) const { - if(p.numSubComponents()!=2 || p.getPropertyComponent(0).getName()!=getName()) - FC_THROWM(Base::ValueError,"Invalid constraint path " << p.toString()); + if (p.numSubComponents() != 2 || p.getPropertyComponent(0).getName() != getName()) + FC_THROWM(Base::ValueError, "Invalid constraint path " << p.toString()); - const ObjectIdentifier::Component & c1 = p.getPropertyComponent(1); + const ObjectIdentifier::Component& c1 = p.getPropertyComponent(1); if (c1.isArray()) { size_t idx = c1.getIndex(); if (idx < _lValueList.size() && !_lValueList[idx]->Name.empty()) - return ObjectIdentifier(*this) << ObjectIdentifier::SimpleComponent(_lValueList[idx]->Name); + return ObjectIdentifier(*this) + << ObjectIdentifier::SimpleComponent(_lValueList[idx]->Name); return p; } else if (c1.isSimple()) { return p; } - FC_THROWM(Base::ValueError,"Invalid constraint path " << p.toString()); + FC_THROWM(Base::ValueError, "Invalid constraint path " << p.toString()); } -void PropertyConstraintList::getPaths(std::vector &paths) const +void PropertyConstraintList::getPaths(std::vector& paths) const { - for (std::vector::const_iterator it = _lValueList.begin(); it != _lValueList.end(); ++it) { + for (std::vector::const_iterator it = _lValueList.begin(); it != _lValueList.end(); + ++it) { if (!(*it)->Name.empty()) - paths.push_back(ObjectIdentifier(*this) << ObjectIdentifier::SimpleComponent((*it)->Name)); + paths.push_back(ObjectIdentifier(*this) + << ObjectIdentifier::SimpleComponent((*it)->Name)); } } -std::vector PropertyConstraintList::_emptyValueList(0); +std::vector PropertyConstraintList::_emptyValueList(0); diff --git a/src/Mod/Sketcher/App/PropertyConstraintList.h b/src/Mod/Sketcher/App/PropertyConstraintList.h index f8590940c0..e08bb85b27 100644 --- a/src/Mod/Sketcher/App/PropertyConstraintList.h +++ b/src/Mod/Sketcher/App/PropertyConstraintList.h @@ -26,8 +26,8 @@ #include #include -#include #include +#include #include #include @@ -35,7 +35,8 @@ #include "Constraint.h" -namespace Base { +namespace Base +{ class Writer; } @@ -43,7 +44,7 @@ namespace Sketcher { class Constraint; -class SketcherExport PropertyConstraintList : public App::PropertyLists +class SketcherExport PropertyConstraintList: public App::PropertyLists { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -63,7 +64,8 @@ public: void setSize(int newSize) override; int getSize() const override; - const char* getEditorName() const override { + const char* getEditorName() const override + { return "SketcherGui::PropertyConstraintListItem"; } @@ -98,67 +100,76 @@ public: \note If the geometry is invalid then the index operator returns null. This must be checked by the caller. */ - const Constraint *operator[] (const int idx) const { + const Constraint* operator[](const int idx) const + { return (invalidGeometry || invalidIndices) ? nullptr : _lValueList[idx]; } - const std::vector &getValues() const { + const std::vector& getValues() const + { return (invalidGeometry || invalidIndices) ? _emptyValueList : _lValueList; } - const std::vector &getValuesForce() const {//to suppress check for invalid geometry, to be used for sketch repairing. - return _lValueList; + + // to suppress check for invalid geometry, to be used for sketch repairing. + const std::vector& getValuesForce() const + { + return _lValueList; } - PyObject *getPyObject() override; - void setPyObject(PyObject *) override; + PyObject* getPyObject() override; + void setPyObject(PyObject*) override; - void Save(Base::Writer &writer) const override; - void Restore(Base::XMLReader &reader) override; + void Save(Base::Writer& writer) const override; + void Restore(Base::XMLReader& reader) override; - Property *Copy() const override; - void Paste(const App::Property &from) override; + Property* Copy() const override; + void Paste(const App::Property& from) override; unsigned int getMemSize() const override; - void acceptGeometry(const std::vector &GeoList); - bool checkGeometry(const std::vector &GeoList); - bool scanGeometry(const std::vector &GeoList) const; + void acceptGeometry(const std::vector& GeoList); + bool checkGeometry(const std::vector& GeoList); + bool scanGeometry(const std::vector& GeoList) const; bool checkConstraintIndices(int geomax, int geomin); /// Return status of geometry for better error reporting - bool hasInvalidGeometry() const { return invalidGeometry; } + bool hasInvalidGeometry() const + { + return invalidGeometry; + } - const Constraint *getConstraint(const App::ObjectIdentifier &path) const; - void setPathValue(const App::ObjectIdentifier & path, const boost::any & value) override; - const boost::any getPathValue(const App::ObjectIdentifier & path) const override; - App::ObjectIdentifier canonicalPath(const App::ObjectIdentifier & p) const override; - void getPaths(std::vector & paths) const override; + const Constraint* getConstraint(const App::ObjectIdentifier& path) const; + void setPathValue(const App::ObjectIdentifier& path, const boost::any& value) override; + const boost::any getPathValue(const App::ObjectIdentifier& path) const override; + App::ObjectIdentifier canonicalPath(const App::ObjectIdentifier& p) const override; + void getPaths(std::vector& paths) const override; - bool getPyPathValue(const App::ObjectIdentifier &path, Py::Object &res) const override; + bool getPyPathValue(const App::ObjectIdentifier& path, Py::Object& res) const override; - using ConstraintInfo = std::pair ; + using ConstraintInfo = std::pair; - boost::signals2::signal &)> signalConstraintsRenamed; - boost::signals2::signal &)> signalConstraintsRemoved; + boost::signals2::signal&)> + signalConstraintsRenamed; + boost::signals2::signal&)> signalConstraintsRemoved; - static std::string getConstraintName(const std::string &name, int i); + static std::string getConstraintName(const std::string& name, int i); static std::string getConstraintName(int i); - static int getIndexFromConstraintName(const std::string & name); + static int getIndexFromConstraintName(const std::string& name); - static bool validConstraintName(const std::string &name); + static bool validConstraintName(const std::string& name); App::ObjectIdentifier createPath(int ConstrNbr) const; private: App::ObjectIdentifier makeArrayPath(int idx); - App::ObjectIdentifier makeSimplePath(const Constraint *c); - App::ObjectIdentifier makePath(int idx, const Constraint *c); + App::ObjectIdentifier makeSimplePath(const Constraint* c); + App::ObjectIdentifier makePath(int idx, const Constraint* c); - std::vector _lValueList; + std::vector _lValueList; boost::unordered_map valueMap; std::vector validGeometryKeys; @@ -167,12 +178,12 @@ private: bool invalidIndices; void applyValues(std::vector&&); - void applyValidGeometryKeys(const std::vector &keys); + void applyValidGeometryKeys(const std::vector& keys); - static std::vector _emptyValueList; + static std::vector _emptyValueList; }; -} // namespace Sketcher +}// namespace Sketcher -#endif // APP_PropertyConstraintList_H +#endif// APP_PropertyConstraintList_H diff --git a/src/Mod/Sketcher/App/PythonConverter.cpp b/src/Mod/Sketcher/App/PythonConverter.cpp index e97d3c0203..a4cdb59f26 100644 --- a/src/Mod/Sketcher/App/PythonConverter.cpp +++ b/src/Mod/Sketcher/App/PythonConverter.cpp @@ -22,8 +22,8 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -#endif // #ifndef _PreComp_ +#include +#endif// #ifndef _PreComp_ #include #include @@ -34,20 +34,20 @@ using namespace Sketcher; -std::string PythonConverter::convert(const Part::Geometry * geo) +std::string PythonConverter::convert(const Part::Geometry* geo) { // "addGeometry(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)),%s)" std::string command; auto sg = process(geo); - command = boost::str(boost::format("addGeometry(%s,%s)\n") % - sg.creation % (sg.construction ? "True":"False")); + command = boost::str(boost::format("addGeometry(%s,%s)\n") % sg.creation + % (sg.construction ? "True" : "False")); return command; } -std::string PythonConverter::convert(const Sketcher::Constraint * constraint) +std::string PythonConverter::convert(const Sketcher::Constraint* constraint) { // addConstraint(Sketcher.Constraint('Distance',%d,%f)) std::string command; @@ -58,41 +58,42 @@ std::string PythonConverter::convert(const Sketcher::Constraint * constraint) return command; } -std::string PythonConverter::convert(const std::string & doc, const std::vector & geos) +std::string PythonConverter::convert(const std::string& doc, + const std::vector& geos) { std::string geolist = "geoList = []\n"; std::string constrgeolist = "constrGeoList = []\n"; int ngeo = 0, nconstr = 0; - for(auto geo : geos) { + for (auto geo : geos) { auto sg = process(geo); if (sg.construction) { - constrgeolist = boost::str(boost::format("%s\nconstrGeoList.append(%s)\n") % - constrgeolist % sg.creation); + constrgeolist = boost::str(boost::format("%s\nconstrGeoList.append(%s)\n") + % constrgeolist % sg.creation); nconstr++; } else { - geolist = boost::str(boost::format("%s\ngeoList.append(%s)\n") % - geolist % sg.creation); + geolist = boost::str(boost::format("%s\ngeoList.append(%s)\n") % geolist % sg.creation); ngeo++; } } - if(ngeo > 0) { - geolist = boost::str(boost::format("%s\n%s.addGeometry(geoList,%s)\ndel geoList\n") % - geolist % doc % "False"); + if (ngeo > 0) { + geolist = boost::str(boost::format("%s\n%s.addGeometry(geoList,%s)\ndel geoList\n") + % geolist % doc % "False"); } - if(nconstr > 0) { - constrgeolist = boost::str(boost::format("%s\n%s.addGeometry(constrGeoList,%s)\ndel constrGeoList") % - constrgeolist % doc % "True"); + if (nconstr > 0) { + constrgeolist = + boost::str(boost::format("%s\n%s.addGeometry(constrGeoList,%s)\ndel constrGeoList") + % constrgeolist % doc % "True"); } std::string command; - if(ngeo > 0 && nconstr > 0) + if (ngeo > 0 && nconstr > 0) command = geolist + constrgeolist; else if (ngeo > 0) command = std::move(geolist); @@ -102,95 +103,107 @@ std::string PythonConverter::convert(const std::string & doc, const std::vector< return command; } -std::string PythonConverter::convert(const std::string & doc, const std::vector & constraints) +std::string PythonConverter::convert(const std::string& doc, + const std::vector& constraints) { - if(constraints.size() == 1) { + if (constraints.size() == 1) { auto cg = convert(constraints[0]); - return boost::str(boost::format("%s.%s\n") % - doc % cg); + return boost::str(boost::format("%s.%s\n") % doc % cg); } std::string constraintlist = "constraintList = []"; - for(auto constraint : constraints) { + for (auto constraint : constraints) { auto cg = process(constraint); - constraintlist = boost::str(boost::format("%s\nconstraintList.append(%s)") % - constraintlist % cg); + constraintlist = + boost::str(boost::format("%s\nconstraintList.append(%s)") % constraintlist % cg); } - if(!constraints.empty()) { - constraintlist = boost::str(boost::format("%s\n%s.addConstraint(constraintList)\ndel constraintList\n") % - constraintlist % doc); + if (!constraints.empty()) { + constraintlist = + boost::str(boost::format("%s\n%s.addConstraint(constraintList)\ndel constraintList\n") + % constraintlist % doc); } return constraintlist; } -PythonConverter::SingleGeometry PythonConverter::process(const Part::Geometry * geo) +PythonConverter::SingleGeometry PythonConverter::process(const Part::Geometry* geo) { - static std::map> converterMap = { - { Part::GeomLineSegment::getClassTypeId(), - [](const Part::Geometry * geo){ - auto sgeo = static_cast(geo); - SingleGeometry sg; - sg.creation = boost::str(boost::format("Part.LineSegment(App.Vector(%f,%f,%f),App.Vector(%f,%f,%f))") % - sgeo->getStartPoint().x % sgeo->getStartPoint().y % sgeo->getStartPoint().z % - sgeo->getEndPoint().x % sgeo->getEndPoint().y % sgeo->getEndPoint().z); - sg.construction = Sketcher::GeometryFacade::getConstruction(geo); - return sg; - }}, - { Part::GeomArcOfCircle::getClassTypeId(), - [](const Part::Geometry * geo){ - auto arc = static_cast(geo); - SingleGeometry sg; - sg.creation = boost::str(boost::format("Part.ArcOfCircle(Part.Circle(App.Vector(%f, %f, %f), App.Vector(%f, %f, %f), %f), %f, %f)") % - arc->getCenter().x % arc->getCenter().y % arc->getCenter().z % - arc->getAxisDirection().x % arc->getAxisDirection().y % arc->getAxisDirection().z % - arc->getRadius() % arc->getFirstParameter() % arc->getLastParameter()); - sg.construction = Sketcher::GeometryFacade::getConstruction(geo); - return sg; - }}, - { Part::GeomPoint::getClassTypeId(), - [](const Part::Geometry* geo) { - auto sgeo = static_cast(geo); - SingleGeometry sg; - sg.creation = boost::str(boost::format("Part.Point(App.Vector(%f,%f,%f))") % - sgeo->getPoint().x % sgeo->getPoint().y % sgeo->getPoint().z); - sg.construction = Sketcher::GeometryFacade::getConstruction(geo); - return sg; - }}, - { Part::GeomEllipse::getClassTypeId(), - [](const Part::Geometry * geo){ - auto ellipse = static_cast(geo); - SingleGeometry sg; - auto periapsis = ellipse->getCenter() + ellipse->getMajorAxisDir() * ellipse->getMajorRadius(); - auto positiveB = ellipse->getCenter() + ellipse->getMinorAxisDir() * ellipse->getMinorRadius(); - auto center = ellipse->getCenter(); - sg.creation = boost::str(boost::format("Part.Ellipse(App.Vector(%f, %f, %f), App.Vector(%f, %f, %f), App.Vector(%f, %f, %f))") % - periapsis.x % periapsis.y % periapsis.z % - positiveB.x % positiveB.y % positiveB.z % - center.x % center.y % center.z); - sg.construction = Sketcher::GeometryFacade::getConstruction(geo); - return sg; - }}, - { Part::GeomCircle::getClassTypeId(), - [](const Part::Geometry * geo){ - auto circle = static_cast(geo); - SingleGeometry sg; - sg.creation = boost::str(boost::format("Part.Circle(App.Vector(%f, %f, %f), App.Vector(%f, %f, %f), %f)") % - circle->getCenter().x % circle->getCenter().y % circle->getCenter().z % - circle->getAxisDirection().x % circle->getAxisDirection().y % circle->getAxisDirection().z % - circle->getRadius()); - sg.construction = Sketcher::GeometryFacade::getConstruction(geo); - return sg; - }}, - }; + static std::map> + converterMap = { + {Part::GeomLineSegment::getClassTypeId(), + [](const Part::Geometry* geo) { + auto sgeo = static_cast(geo); + SingleGeometry sg; + sg.creation = boost::str( + boost::format("Part.LineSegment(App.Vector(%f,%f,%f),App.Vector(%f,%f,%f))") + % sgeo->getStartPoint().x % sgeo->getStartPoint().y % sgeo->getStartPoint().z + % sgeo->getEndPoint().x % sgeo->getEndPoint().y % sgeo->getEndPoint().z); + sg.construction = Sketcher::GeometryFacade::getConstruction(geo); + return sg; + }}, + {Part::GeomArcOfCircle::getClassTypeId(), + [](const Part::Geometry* geo) { + auto arc = static_cast(geo); + SingleGeometry sg; + sg.creation = + boost::str(boost::format("Part.ArcOfCircle(Part.Circle(App.Vector(%f, %f, " + "%f), App.Vector(%f, %f, %f), %f), %f, %f)") + % arc->getCenter().x % arc->getCenter().y % arc->getCenter().z + % arc->getAxisDirection().x % arc->getAxisDirection().y + % arc->getAxisDirection().z % arc->getRadius() + % arc->getFirstParameter() % arc->getLastParameter()); + sg.construction = Sketcher::GeometryFacade::getConstruction(geo); + return sg; + }}, + {Part::GeomPoint::getClassTypeId(), + [](const Part::Geometry* geo) { + auto sgeo = static_cast(geo); + SingleGeometry sg; + sg.creation = + boost::str(boost::format("Part.Point(App.Vector(%f,%f,%f))") + % sgeo->getPoint().x % sgeo->getPoint().y % sgeo->getPoint().z); + sg.construction = Sketcher::GeometryFacade::getConstruction(geo); + return sg; + }}, + {Part::GeomEllipse::getClassTypeId(), + [](const Part::Geometry* geo) { + auto ellipse = static_cast(geo); + SingleGeometry sg; + auto periapsis = + ellipse->getCenter() + ellipse->getMajorAxisDir() * ellipse->getMajorRadius(); + auto positiveB = + ellipse->getCenter() + ellipse->getMinorAxisDir() * ellipse->getMinorRadius(); + auto center = ellipse->getCenter(); + sg.creation = + boost::str(boost::format("Part.Ellipse(App.Vector(%f, %f, %f), App.Vector(%f, " + "%f, %f), App.Vector(%f, %f, %f))") + % periapsis.x % periapsis.y % periapsis.z % positiveB.x + % positiveB.y % positiveB.z % center.x % center.y % center.z); + sg.construction = Sketcher::GeometryFacade::getConstruction(geo); + return sg; + }}, + {Part::GeomCircle::getClassTypeId(), + [](const Part::Geometry* geo) { + auto circle = static_cast(geo); + SingleGeometry sg; + sg.creation = boost::str( + boost::format( + "Part.Circle(App.Vector(%f, %f, %f), App.Vector(%f, %f, %f), %f)") + % circle->getCenter().x % circle->getCenter().y % circle->getCenter().z + % circle->getAxisDirection().x % circle->getAxisDirection().y + % circle->getAxisDirection().z % circle->getRadius()); + sg.construction = Sketcher::GeometryFacade::getConstruction(geo); + return sg; + }}, + }; auto result = converterMap.find(geo->getTypeId()); - if( result == converterMap.end()) + if (result == converterMap.end()) THROWM(Base::ValueError, "PythonConverter: Geometry Type not supported") auto creator = result->second; @@ -198,210 +211,248 @@ PythonConverter::SingleGeometry PythonConverter::process(const Part::Geometry * return creator(geo); } -std::string PythonConverter::process(const Sketcher::Constraint * constraint) +std::string PythonConverter::process(const Sketcher::Constraint* constraint) { - static std::map> converterMap = { - { Sketcher::Coincident, - [](const Sketcher::Constraint * constr){ - return boost::str(boost::format("Sketcher.Constraint('Coincident', %i, %i, %i, %i)") % - constr->First % static_cast(constr->FirstPos) % constr->Second % static_cast(constr->SecondPos)); - }}, - { Sketcher::Horizontal, - [](const Sketcher::Constraint * constr){ - if(constr->Second == GeoEnum::GeoUndef) { - return boost::str(boost::format("Sketcher.Constraint('Horizontal', %i)") % constr->First); - } - else { - return boost::str(boost::format("Sketcher.Constraint('Horizontal', %i, %i, %i, %i)") % - constr->First % static_cast(constr->FirstPos) % constr->Second % static_cast(constr->SecondPos)); - } - }}, - { Sketcher::Vertical, - [](const Sketcher::Constraint * constr){ - if(constr->Second == GeoEnum::GeoUndef) { - return boost::str(boost::format("Sketcher.Constraint('Vertical', %i)") % constr->First); - } - else { - return boost::str(boost::format("Sketcher.Constraint('Vertical', %i, %i, %i, %i)") % - constr->First % static_cast(constr->FirstPos) % constr->Second % static_cast(constr->SecondPos)); - } - }}, - { Sketcher::Block, - [](const Sketcher::Constraint * constr){ - return boost::str(boost::format("Sketcher.Constraint('Block', %i)") % constr->First); - }}, - { Sketcher::Tangent, - [](const Sketcher::Constraint * constr){ - if(constr->FirstPos == Sketcher::PointPos::none) { - return boost::str(boost::format("Sketcher.Constraint('Tangent', %i, %i)") % - constr->First % constr->Second); - } - else if(constr->SecondPos == Sketcher::PointPos::none){ - return boost::str(boost::format("Sketcher.Constraint('Tangent', %i, %i, %i)") % - constr->First % static_cast(constr->FirstPos) % constr->Second); - } - else { - return boost::str(boost::format("Sketcher.Constraint('Tangent', %i, %i, %i, %i)") % - constr->First % static_cast(constr->FirstPos) % constr->Second % static_cast(constr->SecondPos)); - } - }}, - { Sketcher::Parallel, - [](const Sketcher::Constraint * constr){ - return boost::str(boost::format("Sketcher.Constraint('Parallel', %i, %i)") % - constr->First % constr->Second); - }}, - { Sketcher::Perpendicular, - [](const Sketcher::Constraint * constr){ - if(constr->FirstPos == Sketcher::PointPos::none) { - return boost::str(boost::format("Sketcher.Constraint('Perpendicular', %i, %i)") % - constr->First % constr->Second); - } - else if(constr->SecondPos == Sketcher::PointPos::none){ - return boost::str(boost::format("Sketcher.Constraint('Perpendicular', %i, %i, %i)") % - constr->First % static_cast(constr->FirstPos) % constr->Second); - } - else { - return boost::str(boost::format("Sketcher.Constraint('Perpendicular', %i, %i, %i, %i)") % - constr->First % static_cast(constr->FirstPos) % constr->Second % static_cast(constr->SecondPos)); - } - }}, - { Sketcher::Equal, - [](const Sketcher::Constraint * constr){ - return boost::str(boost::format("Sketcher.Constraint('Equal', %i, %i)") % - constr->First % constr->Second); - }}, - { Sketcher::InternalAlignment, - [](const Sketcher::Constraint * constr){ - if(constr->InternalAlignmentIndex == EllipseMajorDiameter || - constr->InternalAlignmentIndex == EllipseMinorDiameter) { - return boost::str(boost::format("Sketcher.Constraint('InternalAlignment:%s', %i, %i)") % - constr->internalAlignmentTypeToString() % constr->First % constr->Second); - } - else if(constr->InternalAlignmentIndex == EllipseFocus1 || - constr->InternalAlignmentIndex == EllipseFocus2) { - return boost::str(boost::format("Sketcher.Constraint('InternalAlignment:%s', %i, %i, %i)") % - constr->internalAlignmentTypeToString() % constr->First % static_cast(constr->FirstPos) % constr->Second); - } - else if(constr->InternalAlignmentIndex == BSplineControlPoint) { - return boost::str(boost::format("Sketcher.Constraint('InternalAlignment:%s', %i, %i, %i, %i)") % - constr->internalAlignmentTypeToString() % constr->First % static_cast(constr->FirstPos) % - constr->Second % constr->InternalAlignmentIndex); - } + static std::map> + converterMap = { + {Sketcher::Coincident, + [](const Sketcher::Constraint* constr) { + return boost::str( + boost::format("Sketcher.Constraint('Coincident', %i, %i, %i, %i)") + % constr->First % static_cast(constr->FirstPos) % constr->Second + % static_cast(constr->SecondPos)); + }}, + {Sketcher::Horizontal, + [](const Sketcher::Constraint* constr) { + if (constr->Second == GeoEnum::GeoUndef) { + return boost::str(boost::format("Sketcher.Constraint('Horizontal', %i)") + % constr->First); + } + else { + return boost::str( + boost::format("Sketcher.Constraint('Horizontal', %i, %i, %i, %i)") + % constr->First % static_cast(constr->FirstPos) % constr->Second + % static_cast(constr->SecondPos)); + } + }}, + {Sketcher::Vertical, + [](const Sketcher::Constraint* constr) { + if (constr->Second == GeoEnum::GeoUndef) { + return boost::str(boost::format("Sketcher.Constraint('Vertical', %i)") + % constr->First); + } + else { + return boost::str( + boost::format("Sketcher.Constraint('Vertical', %i, %i, %i, %i)") + % constr->First % static_cast(constr->FirstPos) % constr->Second + % static_cast(constr->SecondPos)); + } + }}, + {Sketcher::Block, + [](const Sketcher::Constraint* constr) { + return boost::str(boost::format("Sketcher.Constraint('Block', %i)") + % constr->First); + }}, + {Sketcher::Tangent, + [](const Sketcher::Constraint* constr) { + if (constr->FirstPos == Sketcher::PointPos::none) { + return boost::str(boost::format("Sketcher.Constraint('Tangent', %i, %i)") + % constr->First % constr->Second); + } + else if (constr->SecondPos == Sketcher::PointPos::none) { + return boost::str(boost::format("Sketcher.Constraint('Tangent', %i, %i, %i)") + % constr->First % static_cast(constr->FirstPos) + % constr->Second); + } + else { + return boost::str( + boost::format("Sketcher.Constraint('Tangent', %i, %i, %i, %i)") + % constr->First % static_cast(constr->FirstPos) % constr->Second + % static_cast(constr->SecondPos)); + } + }}, + {Sketcher::Parallel, + [](const Sketcher::Constraint* constr) { + return boost::str(boost::format("Sketcher.Constraint('Parallel', %i, %i)") + % constr->First % constr->Second); + }}, + {Sketcher::Perpendicular, + [](const Sketcher::Constraint* constr) { + if (constr->FirstPos == Sketcher::PointPos::none) { + return boost::str(boost::format("Sketcher.Constraint('Perpendicular', %i, %i)") + % constr->First % constr->Second); + } + else if (constr->SecondPos == Sketcher::PointPos::none) { + return boost::str( + boost::format("Sketcher.Constraint('Perpendicular', %i, %i, %i)") + % constr->First % static_cast(constr->FirstPos) % constr->Second); + } + else { + return boost::str( + boost::format("Sketcher.Constraint('Perpendicular', %i, %i, %i, %i)") + % constr->First % static_cast(constr->FirstPos) % constr->Second + % static_cast(constr->SecondPos)); + } + }}, + {Sketcher::Equal, + [](const Sketcher::Constraint* constr) { + return boost::str(boost::format("Sketcher.Constraint('Equal', %i, %i)") + % constr->First % constr->Second); + }}, + {Sketcher::InternalAlignment, + [](const Sketcher::Constraint* constr) { + if (constr->InternalAlignmentIndex == EllipseMajorDiameter + || constr->InternalAlignmentIndex == EllipseMinorDiameter) { + return boost::str( + boost::format("Sketcher.Constraint('InternalAlignment:%s', %i, %i)") + % constr->internalAlignmentTypeToString() % constr->First + % constr->Second); + } + else if (constr->InternalAlignmentIndex == EllipseFocus1 + || constr->InternalAlignmentIndex == EllipseFocus2) { + return boost::str( + boost::format("Sketcher.Constraint('InternalAlignment:%s', %i, %i, %i)") + % constr->internalAlignmentTypeToString() % constr->First + % static_cast(constr->FirstPos) % constr->Second); + } + else if (constr->InternalAlignmentIndex == BSplineControlPoint) { + return boost::str( + boost::format( + "Sketcher.Constraint('InternalAlignment:%s', %i, %i, %i, %i)") + % constr->internalAlignmentTypeToString() % constr->First + % static_cast(constr->FirstPos) % constr->Second + % constr->InternalAlignmentIndex); + } - THROWM(Base::ValueError, "PythonConverter: Constraint Alignment Type not supported") - }}, - { Sketcher::Distance, - [](const Sketcher::Constraint * constr){ - if(constr->Second == GeoEnum::GeoUndef){ - return boost::str(boost::format("Sketcher.Constraint('Distance', %i, %f)") % - constr->First % constr->getValue()); - } - else if(constr->FirstPos == Sketcher::PointPos::none){ - return boost::str(boost::format("Sketcher.Constraint('Distance', %i, %i, %f)") % - constr->First % constr->Second % constr->getValue()); - } - else if(constr->SecondPos == Sketcher::PointPos::none){ - return boost::str(boost::format("Sketcher.Constraint('Distance', %i, %i, %i, %f)") % - constr->First % static_cast(constr->FirstPos) % constr->Second % constr->getValue()); - } - else { - return boost::str(boost::format("Sketcher.Constraint('Distance', %i, %i, %i, %i, %f)") % - constr->First % static_cast(constr->FirstPos) % constr->Second % - static_cast(constr->SecondPos) % constr->getValue()); - } - }}, - { Sketcher::Angle, - [](const Sketcher::Constraint * constr){ - if(constr->Second == GeoEnum::GeoUndef) { - return boost::str(boost::format("Sketcher.Constraint('Angle', %i, %f)") % - constr->First % constr->getValue()); - } - else if(constr->SecondPos == Sketcher::PointPos::none){ - return boost::str(boost::format("Sketcher.Constraint('Angle', %i, %i, %f)") % - constr->First % constr->Second % constr->getValue()); - } - else { - return boost::str(boost::format("Sketcher.Constraint('Angle', %i, %i, %i, %i, %f)") % - constr->First % static_cast(constr->FirstPos) % constr->Second % - static_cast(constr->SecondPos) % constr->getValue()); - } - }}, - { Sketcher::DistanceX, - [](const Sketcher::Constraint * constr){ - if(constr->Second == GeoEnum::GeoUndef) { - return boost::str(boost::format("Sketcher.Constraint('DistanceX', %i, %f)") % - constr->First % constr->getValue()); - } - else if(constr->SecondPos == Sketcher::PointPos::none){ - return boost::str(boost::format("Sketcher.Constraint('DistanceX', %i, %i, %f)") % - constr->First % static_cast(constr->FirstPos) % constr->getValue()); - } - else { - return boost::str(boost::format("Sketcher.Constraint('DistanceX', %i, %i, %i, %i, %f)") % - constr->First % static_cast(constr->FirstPos) % constr->Second % - static_cast(constr->SecondPos) % constr->getValue()); - } - }}, - { Sketcher::DistanceY, - [](const Sketcher::Constraint * constr){ - if(constr->Second == GeoEnum::GeoUndef) { - return boost::str(boost::format("Sketcher.Constraint('DistanceY', %i, %f)") % - constr->First % constr->getValue()); - } - else if(constr->SecondPos == Sketcher::PointPos::none){ - return boost::str(boost::format("Sketcher.Constraint('DistanceY', %i, %i, %f)") % - constr->First % static_cast(constr->FirstPos) % constr->getValue()); - } - else { - return boost::str(boost::format("Sketcher.Constraint('DistanceY', %i, %i, %i, %i, %f)") % - constr->First % static_cast(constr->FirstPos) % constr->Second % - static_cast(constr->SecondPos) % constr->getValue()); - } - }}, - { Sketcher::Radius, - [](const Sketcher::Constraint * constr){ - return boost::str(boost::format("Sketcher.Constraint('Radius', %i, %f)") % - constr->First % constr->getValue()); - }}, - { Sketcher::Diameter, - [](const Sketcher::Constraint * constr){ - return boost::str(boost::format("Sketcher.Constraint('Diameter', %i, %f)") % - constr->First % constr->getValue()); - }}, - { Sketcher::Weight, - [](const Sketcher::Constraint * constr){ - return boost::str(boost::format("Sketcher.Constraint('Weight', %i, %f)") % - constr->First % constr->getValue()); - }}, - { Sketcher::PointOnObject, - [](const Sketcher::Constraint * constr){ - return boost::str(boost::format("Sketcher.Constraint('PointOnObject', %i, %i, %i)") % - constr->First % static_cast(constr->FirstPos) % constr->Second); - }}, - { Sketcher::Symmetric, - [](const Sketcher::Constraint * constr){ - if(constr->ThirdPos==Sketcher::PointPos::none) { - return boost::str(boost::format("Sketcher.Constraint('Symmetric', %i, %i, %i, %i, %i)") % - constr->First % static_cast(constr->FirstPos) % constr->Second % static_cast(constr->SecondPos) % - constr->Third); - } - else { - return boost::str(boost::format("Sketcher.Constraint('Symmetric', %i, %i, %i, %i, %i, %i)") % - constr->First % static_cast(constr->FirstPos) % constr->Second % static_cast(constr->SecondPos) % - constr->Third % static_cast(constr->ThirdPos)); - } - }}, - { Sketcher::SnellsLaw, - [](const Sketcher::Constraint * constr){ - return boost::str(boost::format("Sketcher.Constraint('SnellsLaw', %i, %i, %i, %i, %i, %f)") % - constr->First % static_cast(constr->FirstPos) % constr->Second % static_cast(constr->SecondPos) % - constr->Third % constr->getValue()); - }}, - }; + THROWM(Base::ValueError, + "PythonConverter: Constraint Alignment Type not supported") + }}, + {Sketcher::Distance, + [](const Sketcher::Constraint* constr) { + if (constr->Second == GeoEnum::GeoUndef) { + return boost::str(boost::format("Sketcher.Constraint('Distance', %i, %f)") + % constr->First % constr->getValue()); + } + else if (constr->FirstPos == Sketcher::PointPos::none) { + return boost::str(boost::format("Sketcher.Constraint('Distance', %i, %i, %f)") + % constr->First % constr->Second % constr->getValue()); + } + else if (constr->SecondPos == Sketcher::PointPos::none) { + return boost::str( + boost::format("Sketcher.Constraint('Distance', %i, %i, %i, %f)") + % constr->First % static_cast(constr->FirstPos) % constr->Second + % constr->getValue()); + } + else { + return boost::str( + boost::format("Sketcher.Constraint('Distance', %i, %i, %i, %i, %f)") + % constr->First % static_cast(constr->FirstPos) % constr->Second + % static_cast(constr->SecondPos) % constr->getValue()); + } + }}, + {Sketcher::Angle, + [](const Sketcher::Constraint* constr) { + if (constr->Second == GeoEnum::GeoUndef) { + return boost::str(boost::format("Sketcher.Constraint('Angle', %i, %f)") + % constr->First % constr->getValue()); + } + else if (constr->SecondPos == Sketcher::PointPos::none) { + return boost::str(boost::format("Sketcher.Constraint('Angle', %i, %i, %f)") + % constr->First % constr->Second % constr->getValue()); + } + else { + return boost::str( + boost::format("Sketcher.Constraint('Angle', %i, %i, %i, %i, %f)") + % constr->First % static_cast(constr->FirstPos) % constr->Second + % static_cast(constr->SecondPos) % constr->getValue()); + } + }}, + {Sketcher::DistanceX, + [](const Sketcher::Constraint* constr) { + if (constr->Second == GeoEnum::GeoUndef) { + return boost::str(boost::format("Sketcher.Constraint('DistanceX', %i, %f)") + % constr->First % constr->getValue()); + } + else if (constr->SecondPos == Sketcher::PointPos::none) { + return boost::str(boost::format("Sketcher.Constraint('DistanceX', %i, %i, %f)") + % constr->First % static_cast(constr->FirstPos) + % constr->getValue()); + } + else { + return boost::str( + boost::format("Sketcher.Constraint('DistanceX', %i, %i, %i, %i, %f)") + % constr->First % static_cast(constr->FirstPos) % constr->Second + % static_cast(constr->SecondPos) % constr->getValue()); + } + }}, + {Sketcher::DistanceY, + [](const Sketcher::Constraint* constr) { + if (constr->Second == GeoEnum::GeoUndef) { + return boost::str(boost::format("Sketcher.Constraint('DistanceY', %i, %f)") + % constr->First % constr->getValue()); + } + else if (constr->SecondPos == Sketcher::PointPos::none) { + return boost::str(boost::format("Sketcher.Constraint('DistanceY', %i, %i, %f)") + % constr->First % static_cast(constr->FirstPos) + % constr->getValue()); + } + else { + return boost::str( + boost::format("Sketcher.Constraint('DistanceY', %i, %i, %i, %i, %f)") + % constr->First % static_cast(constr->FirstPos) % constr->Second + % static_cast(constr->SecondPos) % constr->getValue()); + } + }}, + {Sketcher::Radius, + [](const Sketcher::Constraint* constr) { + return boost::str(boost::format("Sketcher.Constraint('Radius', %i, %f)") + % constr->First % constr->getValue()); + }}, + {Sketcher::Diameter, + [](const Sketcher::Constraint* constr) { + return boost::str(boost::format("Sketcher.Constraint('Diameter', %i, %f)") + % constr->First % constr->getValue()); + }}, + {Sketcher::Weight, + [](const Sketcher::Constraint* constr) { + return boost::str(boost::format("Sketcher.Constraint('Weight', %i, %f)") + % constr->First % constr->getValue()); + }}, + {Sketcher::PointOnObject, + [](const Sketcher::Constraint* constr) { + return boost::str(boost::format("Sketcher.Constraint('PointOnObject', %i, %i, %i)") + % constr->First % static_cast(constr->FirstPos) + % constr->Second); + }}, + {Sketcher::Symmetric, + [](const Sketcher::Constraint* constr) { + if (constr->ThirdPos == Sketcher::PointPos::none) { + return boost::str( + boost::format("Sketcher.Constraint('Symmetric', %i, %i, %i, %i, %i)") + % constr->First % static_cast(constr->FirstPos) % constr->Second + % static_cast(constr->SecondPos) % constr->Third); + } + else { + return boost::str( + boost::format("Sketcher.Constraint('Symmetric', %i, %i, %i, %i, %i, %i)") + % constr->First % static_cast(constr->FirstPos) % constr->Second + % static_cast(constr->SecondPos) % constr->Third + % static_cast(constr->ThirdPos)); + } + }}, + {Sketcher::SnellsLaw, + [](const Sketcher::Constraint* constr) { + return boost::str( + boost::format("Sketcher.Constraint('SnellsLaw', %i, %i, %i, %i, %i, %f)") + % constr->First % static_cast(constr->FirstPos) % constr->Second + % static_cast(constr->SecondPos) % constr->Third % constr->getValue()); + }}, + }; auto result = converterMap.find(constraint->Type); - if( result == converterMap.end()) + if (result == converterMap.end()) THROWM(Base::ValueError, "PythonConverter: Constraint Type not supported") auto creator = result->second; diff --git a/src/Mod/Sketcher/App/PythonConverter.h b/src/Mod/Sketcher/App/PythonConverter.h index 16c9edb4d0..de1247ad12 100644 --- a/src/Mod/Sketcher/App/PythonConverter.h +++ b/src/Mod/Sketcher/App/PythonConverter.h @@ -24,12 +24,14 @@ #ifndef SKETCHER_PythonConverter_H #define SKETCHER_PythonConverter_H -namespace Part { - class Geometry; +namespace Part +{ +class Geometry; } -namespace Sketcher { - class Constraint; +namespace Sketcher +{ +class Constraint; /** @brief Class for generating python code * @details @@ -37,38 +39,38 @@ namespace Sketcher { * create such objects. */ -class SketcherExport PythonConverter { +class SketcherExport PythonConverter +{ - class SingleGeometry { + class SingleGeometry + { public: std::string creation; bool construction; }; public: - explicit PythonConverter() = delete; ~PythonConverter() = delete; /// Convert a geometry into the string representing the command creating it - static std::string convert(const Part::Geometry * geo); + static std::string convert(const Part::Geometry* geo); /// Convert a vector of geometries into the string representing the command creating them - static std::string convert(const std::string & doc, const std::vector & geos); + static std::string convert(const std::string& doc, const std::vector& geos); - static std::string convert(const Sketcher::Constraint * constraint); + static std::string convert(const Sketcher::Constraint* constraint); - static std::string convert(const std::string & doc, const std::vector & constraints); + static std::string convert(const std::string& doc, + const std::vector& constraints); private: - static SingleGeometry process(const Part::Geometry * geo); - - static std::string process(const Sketcher::Constraint * constraint); + static SingleGeometry process(const Part::Geometry* geo); + static std::string process(const Sketcher::Constraint* constraint); }; -} // namespace Sketcher +}// namespace Sketcher -#endif // SKETCHER_PythonConverter_H - +#endif// SKETCHER_PythonConverter_H diff --git a/src/Mod/Sketcher/App/Sketch.cpp b/src/Mod/Sketcher/App/Sketch.cpp index ee16c80229..8c3cd564dc 100644 --- a/src/Mod/Sketcher/App/Sketch.cpp +++ b/src/Mod/Sketcher/App/Sketch.cpp @@ -22,25 +22,25 @@ #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 #endif #include #include #include #include -#include #include +#include #include #include #include @@ -52,13 +52,13 @@ #include #include -#include "Sketch.h" #include "Constraint.h" #include "GeometryFacade.h" +#include "Sketch.h" #include "SolverGeometryExtension.h" -//#define DEBUG_BLOCK_CONSTRAINT +// #define DEBUG_BLOCK_CONSTRAINT #undef DEBUG_BLOCK_CONSTRAINT using namespace Sketcher; @@ -68,16 +68,18 @@ using namespace Part; TYPESYSTEM_SOURCE(Sketcher::Sketch, Base::Persistence) Sketch::Sketch() - : SolveTime(0) - , RecalculateInitialSolutionWhileMovingPoint(false) - , resolveAfterGeometryUpdated(false) - , GCSsys(), ConstraintsCounter(0) - , isInitMove(false), isFine(true), moveStep(0) - , defaultSolver(GCS::DogLeg) - , defaultSolverRedundant(GCS::DogLeg) - , debugMode(GCS::Minimal) -{ -} + : SolveTime(0), + RecalculateInitialSolutionWhileMovingPoint(false), + resolveAfterGeometryUpdated(false), + GCSsys(), + ConstraintsCounter(0), + isInitMove(false), + isFine(true), + moveStep(0), + defaultSolver(GCS::DogLeg), + defaultSolverRedundant(GCS::DogLeg), + debugMode(GCS::Minimal) +{} Sketch::~Sketch() { @@ -100,11 +102,13 @@ void Sketch::clear() // deleting the doubles allocated with new for (std::vector::iterator it = Parameters.begin(); it != Parameters.end(); ++it) - if (*it) delete *it; + if (*it) + delete *it; Parameters.clear(); DrivenParameters.clear(); for (std::vector::iterator it = FixParameters.begin(); it != FixParameters.end(); ++it) - if (*it) delete *it; + if (*it) + delete *it; FixParameters.clear(); param2geoelement.clear(); @@ -115,11 +119,13 @@ void Sketch::clear() // deleting the geometry copied into this sketch for (std::vector::iterator it = Geoms.begin(); it != Geoms.end(); ++it) - if (it->geo) delete it->geo; + if (it->geo) + delete it->geo; Geoms.clear(); // deleting the non-Driving constraints copied into this sketch - //for (std::vector::iterator it = NonDrivingConstraints.begin(); it != NonDrivingConstraints.end(); ++it) + // for (std::vector::iterator it = NonDrivingConstraints.begin(); it != + // NonDrivingConstraints.end(); ++it) // if (*it) delete *it; Constrs.clear(); @@ -132,10 +138,10 @@ void Sketch::clear() MalformedConstraints.clear(); } -bool Sketch::analyseBlockedGeometry( const std::vector &internalGeoList, - const std::vector &constraintList, - std::vector &onlyblockedGeometry, - std::vector &blockedGeoIds) const +bool Sketch::analyseBlockedGeometry(const std::vector& internalGeoList, + const std::vector& constraintList, + std::vector& onlyblockedGeometry, + std::vector& blockedGeoIds) const { // To understand this function read the documentation in Sketch.h // It is important that "onlyblockedGeometry" ONLY identifies blocked geometry @@ -143,25 +149,26 @@ bool Sketch::analyseBlockedGeometry( const std::vector &intern bool doesBlockAffectOtherConstraints = false; int geoindex = 0; - for(auto g : internalGeoList) { - if(GeometryFacade::getBlocked(g)) { - // is it only affected by one constraint, the block constraint (and this is driving), or by any other driving constraint ? + for (auto g : internalGeoList) { + if (GeometryFacade::getBlocked(g)) { + // is it only affected by one constraint, the block constraint (and this is driving), or + // by any other driving constraint ? bool blockOnly = true; bool blockisDriving = false; - for(auto c : constraintList) { + for (auto c : constraintList) { // is block driving - if( c->Type == Sketcher::Block && c->isDriving && c->First == geoindex) + if (c->Type == Sketcher::Block && c->isDriving && c->First == geoindex) blockisDriving = true; // We have another driving constraint (which may be InternalAlignment) - if( c->Type != Sketcher::Block && c->isDriving && - (c->First == geoindex || c->Second == geoindex || c->Third == geoindex) ) + if (c->Type != Sketcher::Block && c->isDriving + && (c->First == geoindex || c->Second == geoindex || c->Third == geoindex)) blockOnly = false; } - if(blockisDriving) { - if(blockOnly) { - onlyblockedGeometry[geoindex] = true; // we pre-fix this geometry + if (blockisDriving) { + if (blockOnly) { + onlyblockedGeometry[geoindex] = true;// we pre-fix this geometry } else { // we will have to pos-analyse the first diagnose result for these geometries @@ -170,7 +177,6 @@ bool Sketch::analyseBlockedGeometry( const std::vector &intern blockedGeoIds.push_back(geoindex); } } - } geoindex++; } @@ -178,72 +184,72 @@ bool Sketch::analyseBlockedGeometry( const std::vector &intern return doesBlockAffectOtherConstraints; } -int Sketch::setUpSketch(const std::vector &GeoList, - const std::vector &ConstraintList, - int extGeoCount) +int Sketch::setUpSketch(const std::vector& GeoList, + const std::vector& ConstraintList, int extGeoCount) { Base::TimeInfo start_time; clear(); - std::vector intGeoList, extGeoList; - for (int i=0; i < int(GeoList.size())-extGeoCount; i++) + std::vector intGeoList, extGeoList; + for (int i = 0; i < int(GeoList.size()) - extGeoCount; i++) intGeoList.push_back(GeoList[i]); - for (int i=int(GeoList.size())-extGeoCount; i < int(GeoList.size()); i++) + for (int i = int(GeoList.size()) - extGeoCount; i < int(GeoList.size()); i++) extGeoList.push_back(GeoList[i]); - std::vector onlyBlockedGeometry(intGeoList.size(),false); // these geometries are blocked, frozen and sent as fixed parameters to the solver - std::vector unenforceableConstraints(ConstraintList.size(),false); // these constraints are unenforceable due to a Blocked constraint + // these geometries are blocked, frozen and sent as fixed parameters to the solver + std::vector onlyBlockedGeometry(intGeoList.size(), false); + // these constraints are unenforceable due to a Blocked constraint + std::vector unenforceableConstraints(ConstraintList.size(), false); - /* This implements the old block constraint. I have decided not to remove it at this time while the new is tested, just in case the change - * needs to be reverted */ + /* This implements the old block constraint. I have decided not to remove it at this time while + * the new is tested, just in case the change needs to be reverted */ /*if(!intGeoList.empty()) getBlockedGeometry(blockedGeometry, unenforceableConstraints, ConstraintList);*/ - // Pre-analysis of blocked geometry (new block constraint) to fix geometry only affected by a block constraint (see comment in Sketch.h) + // Pre-analysis of blocked geometry (new block constraint) to fix geometry only affected by a + // block constraint (see comment in Sketch.h) std::vector blockedGeoIds; - bool doesBlockAffectOtherConstraints = analyseBlockedGeometry( intGeoList, - ConstraintList, - onlyBlockedGeometry, - blockedGeoIds); + bool doesBlockAffectOtherConstraints = + analyseBlockedGeometry(intGeoList, ConstraintList, onlyBlockedGeometry, blockedGeoIds); #ifdef DEBUG_BLOCK_CONSTRAINT - if(doesBlockAffectOtherConstraints) + if (doesBlockAffectOtherConstraints) Base::Console().Log("\n Block interferes with other constraints: Post-analysis required"); Base::Console().Log("\nOnlyBlocked GeoIds:"); size_t i = 0; bool found = false; - for(; i < onlyBlockedGeometry.size(); i++) { - if(onlyBlockedGeometry[i]) { + for (; i < onlyBlockedGeometry.size(); i++) { + if (onlyBlockedGeometry[i]) { Base::Console().Log("\n GeoId=%d", i); found = true; } } - if(found) + if (found) Base::Console().Log("\n None"); Base::Console().Log("\nNotOnlyBlocked GeoIds:"); i = 0; - for(; i < blockedGeoIds.size(); i++) + for (; i < blockedGeoIds.size(); i++) Base::Console().Log("\n GeoId=%d", blockedGeoIds[i]); - if(i == 0) + if (i == 0) Base::Console().Log("\n None"); Base::Console().Log("\n"); -#endif //DEBUG_BLOCK_CONSTRAINT +#endif// DEBUG_BLOCK_CONSTRAINT buildInternalAlignmentGeometryMap(ConstraintList); - addGeometry(intGeoList,onlyBlockedGeometry); - int extStart=Geoms.size(); + addGeometry(intGeoList, onlyBlockedGeometry); + int extStart = Geoms.size(); addGeometry(extGeoList, true); - int extEnd=Geoms.size()-1; - for (int i=extStart; i <= extEnd; i++) + int extEnd = Geoms.size() - 1; + for (int i = extStart; i <= extEnd; i++) Geoms[i].external = true; // The Geoms list might be empty after an undo/redo if (!Geoms.empty()) { - addConstraints(ConstraintList,unenforceableConstraints); + addConstraints(ConstraintList, unenforceableConstraints); } clearTemporaryConstraints(); GCSsys.declareUnknowns(Parameters); @@ -251,89 +257,95 @@ int Sketch::setUpSketch(const std::vector &GeoList, GCSsys.initSolution(defaultSolverRedundant); // Post-analysis - // Now that we have all the parameters information, we deal properly with the block constraints if necessary - if(doesBlockAffectOtherConstraints) { + // Now that we have all the parameters information, we deal properly with the block constraints + // if necessary + if (doesBlockAffectOtherConstraints) { - std::vector params_to_block; + std::vector params_to_block; - bool unsatisfied_groups = analyseBlockedConstraintDependentParameters(blockedGeoIds, params_to_block); + bool unsatisfied_groups = + analyseBlockedConstraintDependentParameters(blockedGeoIds, params_to_block); // I am unsure if more than one QR iterations are needed with the current implementation. // - // With previous implementations mostly one QR iteration was enough, but if block constraint is abused, more - // iterations were needed. + // With previous implementations mostly one QR iteration was enough, but if block constraint + // is abused, more iterations were needed. int index = 0; - while(unsatisfied_groups) { + while (unsatisfied_groups) { // We tried hard not to arrive to an unsatisfied group, so we try harder // This loop has the advantage that the user will notice increased effort to solve, - // so they may understand that they are abusing the block constraint, while guaranteeing that wrong - // behaviour of the block constraint is not undetected. + // so they may understand that they are abusing the block constraint, while guaranteeing + // that wrong behaviour of the block constraint is not undetected. // Another QR iteration fixParametersAndDiagnose(params_to_block); - unsatisfied_groups = analyseBlockedConstraintDependentParameters(blockedGeoIds,params_to_block); + unsatisfied_groups = + analyseBlockedConstraintDependentParameters(blockedGeoIds, params_to_block); - if (debugMode==GCS::IterationLevel) { - Base::Console().Log("Sketcher::setUpSketch()-BlockConstraint-PostAnalysis:%d\n",index); + if (debugMode == GCS::IterationLevel) { + Base::Console().Log("Sketcher::setUpSketch()-BlockConstraint-PostAnalysis:%d\n", + index); } index++; } // 2. If something needs blocking, block-it - fixParametersAndDiagnose(params_to_block); + fixParametersAndDiagnose(params_to_block); #ifdef DEBUG_BLOCK_CONSTRAINT - if(params_to_block.size() > 0) { - std::vector < std::vector < double*>> groups; + if (params_to_block.size() > 0) { + std::vector> groups; GCSsys.getDependentParamsGroups(groups); // Debug code block - for(size_t i = 0; i < groups.size(); i++) { - Base::Console().Log("\nDepParams: Group %d:",i); - for(size_t j = 0; j < groups[i].size(); j++) - Base::Console().Log("\n Param=%x ,GeoId=%d, GeoPos=%d", - param2geoelement.find(*std::next(groups[i].begin(), j))->first, - param2geoelement.find(*std::next(groups[i].begin(), j))->second.first, - param2geoelement.find(*std::next(groups[i].begin(), j))->second.second); + for (size_t i = 0; i < groups.size(); i++) { + Base::Console().Log("\nDepParams: Group %d:", i); + for (size_t j = 0; j < groups[i].size(); j++) + Base::Console().Log( + "\n Param=%x ,GeoId=%d, GeoPos=%d", + param2geoelement.find(*std::next(groups[i].begin(), j))->first, + param2geoelement.find(*std::next(groups[i].begin(), j))->second.first, + param2geoelement.find(*std::next(groups[i].begin(), j))->second.second); } } -#endif //DEBUG_BLOCK_CONSTRAINT +#endif// DEBUG_BLOCK_CONSTRAINT } // Now we set the Sketch status with the latest solver information GCSsys.getConflicting(Conflicting); GCSsys.getRedundant(Redundant); - GCSsys.getPartiallyRedundant (PartiallyRedundant); + GCSsys.getPartiallyRedundant(PartiallyRedundant); GCSsys.getDependentParams(pDependentParametersList); calculateDependentParametersElements(); - if (debugMode==GCS::Minimal || debugMode==GCS::IterationLevel) { + if (debugMode == GCS::Minimal || debugMode == GCS::IterationLevel) { Base::TimeInfo end_time; - Base::Console().Log("Sketcher::setUpSketch()-T:%s\n",Base::TimeInfo::diffTime(start_time,end_time).c_str()); + Base::Console().Log("Sketcher::setUpSketch()-T:%s\n", + Base::TimeInfo::diffTime(start_time, end_time).c_str()); } return GCSsys.dofsNumber(); } -void Sketch::buildInternalAlignmentGeometryMap(const std::vector &constraintList) +void Sketch::buildInternalAlignmentGeometryMap(const std::vector& constraintList) { - for(auto* c : constraintList) { - if(c->Type==InternalAlignment){ - internalAlignmentGeometryMap[c->First]=c->Second; + for (auto* c : constraintList) { + if (c->Type == InternalAlignment) { + internalAlignmentGeometryMap[c->First] = c->Second; } } } -void Sketch::fixParametersAndDiagnose(std::vector ¶ms_to_block) +void Sketch::fixParametersAndDiagnose(std::vector& params_to_block) { - if(!params_to_block.empty()) { // only there are parameters to fix - for( auto p : params_to_block ) { - auto findparam = std::find(Parameters.begin(),Parameters.end(), p); + if (!params_to_block.empty()) {// only there are parameters to fix + for (auto p : params_to_block) { + auto findparam = std::find(Parameters.begin(), Parameters.end(), p); - if(findparam != Parameters.end()) { + if (findparam != Parameters.end()) { FixParameters.push_back(*findparam); Parameters.erase(findparam); } @@ -354,63 +366,69 @@ void Sketch::fixParametersAndDiagnose(std::vector ¶ms_to_block) } } -bool Sketch::analyseBlockedConstraintDependentParameters(std::vector &blockedGeoIds, std::vector ¶ms_to_block) const +bool Sketch::analyseBlockedConstraintDependentParameters( + std::vector& blockedGeoIds, std::vector& params_to_block) const { // 1. Retrieve solver information - std::vector < std::vector < double*>> groups; + std::vector> groups; GCSsys.getDependentParamsGroups(groups); // 2. Determine blockable parameters for each group (see documentation in header file). - struct group { - std::vector blockable_params_in_group; - double * blocking_param_in_group = nullptr; + struct group + { + std::vector blockable_params_in_group; + double* blocking_param_in_group = nullptr; }; std::vector prop_groups(groups.size()); #ifdef DEBUG_BLOCK_CONSTRAINT - for(size_t i = 0; i < groups.size(); i++) { - Base::Console().Log("\nDepParams: Group %d:",i); - for(size_t j = 0; j < groups[i].size(); j++) - Base::Console().Log("\n Param=%x ,GeoId=%d, GeoPos=%d", - param2geoelement.find(*std::next(groups[i].begin(), j))->first, - param2geoelement.find(*std::next(groups[i].begin(), j))->second.first, - param2geoelement.find(*std::next(groups[i].begin(), j))->second.second); + for (size_t i = 0; i < groups.size(); i++) { + Base::Console().Log("\nDepParams: Group %d:", i); + for (size_t j = 0; j < groups[i].size(); j++) + Base::Console().Log( + "\n Param=%x ,GeoId=%d, GeoPos=%d", + param2geoelement.find(*std::next(groups[i].begin(), j))->first, + param2geoelement.find(*std::next(groups[i].begin(), j))->second.first, + param2geoelement.find(*std::next(groups[i].begin(), j))->second.second); } -#endif //DEBUG_BLOCK_CONSTRAINT +#endif// DEBUG_BLOCK_CONSTRAINT - for(size_t i = 0; i < groups.size(); i++) { - for(size_t j = 0; j < groups[i].size(); j++) { + for (size_t i = 0; i < groups.size(); i++) { + for (size_t j = 0; j < groups[i].size(); j++) { - double * thisparam = *std::next(groups[i].begin(), j); + double* thisparam = *std::next(groups[i].begin(), j); auto element = param2geoelement.find(thisparam); if (element != param2geoelement.end()) { - auto blockable = std::find(blockedGeoIds.begin(),blockedGeoIds.end(),std::get<0>(element->second)); + auto blockable = std::find( + blockedGeoIds.begin(), blockedGeoIds.end(), std::get<0>(element->second)); - if( blockable != blockedGeoIds.end()) { - // This dependent parameter group contains at least one parameter that should be blocked, so added to the blockable list. + if (blockable != blockedGeoIds.end()) { + // This dependent parameter group contains at least one parameter that should be + // blocked, so added to the blockable list. prop_groups[i].blockable_params_in_group.push_back(thisparam); } } } } - // 3. Apply heuristic - pick the last blockable param available to block the group, starting from the last group - for(size_t i = prop_groups.size(); i--> 0;) { - for(size_t j = prop_groups[i].blockable_params_in_group.size(); j-->0; ) { + // 3. Apply heuristic - pick the last blockable param available to block the group, starting + // from the last group + for (size_t i = prop_groups.size(); i-- > 0;) { + for (size_t j = prop_groups[i].blockable_params_in_group.size(); j-- > 0;) { // check if parameter is already satisfying one group - double * thisparam = prop_groups[i].blockable_params_in_group[j]; + double* thisparam = prop_groups[i].blockable_params_in_group[j]; auto pos = std::find(params_to_block.begin(), params_to_block.end(), thisparam); - if( pos == params_to_block.end()) { // not found, so add + if (pos == params_to_block.end()) {// not found, so add params_to_block.push_back(thisparam); prop_groups[i].blocking_param_in_group = thisparam; #ifdef DEBUG_BLOCK_CONSTRAINT Base::Console().Log("\nTentatively blocking group %d, with param=%x", i, thisparam); -#endif //DEBUG_BLOCK_CONSTRAINT +#endif// DEBUG_BLOCK_CONSTRAINT break; } } @@ -418,14 +436,15 @@ bool Sketch::analyseBlockedConstraintDependentParameters(std::vector &block // 4. Check if groups are satisfied or are licitly unsatisfiable and thus deemed as satisfied bool unsatisfied_groups = false; - for(size_t i = 0; i < prop_groups.size(); i++) { + for (size_t i = 0; i < prop_groups.size(); i++) { // 4.1. unsatisfiable group - if(prop_groups[i].blockable_params_in_group.empty()) { - // this group does not contain any blockable parameter, so it is by definition satisfied (or impossible to satisfy by block constraints) + if (prop_groups[i].blockable_params_in_group.empty()) { + // this group does not contain any blockable parameter, so it is by definition satisfied + // (or impossible to satisfy by block constraints) continue; } // 4.2. satisfiable and not satisfied - if(!prop_groups[i].blocking_param_in_group) { + if (!prop_groups[i].blocking_param_in_group) { unsatisfied_groups = true; } } @@ -445,15 +464,15 @@ void Sketch::calculateDependentParametersElements() solverExtensions.resize(Geoms.size()); int i = 0; - for(auto geo : Geoms) { + for (auto geo : Geoms) { - if(!geo.geo->hasExtension(Sketcher::SolverGeometryExtension::getClassTypeId())) + if (!geo.geo->hasExtension(Sketcher::SolverGeometryExtension::getClassTypeId())) geo.geo->setExtension(std::make_unique()); auto solvext = std::static_pointer_cast( - geo.geo->getExtension(Sketcher::SolverGeometryExtension::getClassTypeId()).lock()); + geo.geo->getExtension(Sketcher::SolverGeometryExtension::getClassTypeId()).lock()); - if(GCSsys.isEmptyDiagnoseMatrix()) + if (GCSsys.isEmptyDiagnoseMatrix()) solvext->init(SolverGeometryExtension::Dependent); else solvext->init(SolverGeometryExtension::Independent); @@ -462,37 +481,39 @@ void Sketch::calculateDependentParametersElements() i++; } - for(auto param : pDependentParametersList) { + for (auto param : pDependentParametersList) { - //auto element = param2geoelement.at(param); + // auto element = param2geoelement.at(param); auto element = param2geoelement.find(param); if (element != param2geoelement.end()) { auto geoid = std::get<0>(element->second); auto geopos = std::get<1>(element->second); auto solvext = std::static_pointer_cast( - Geoms[geoid].geo->getExtension(Sketcher::SolverGeometryExtension::getClassTypeId()).lock()); + Geoms[geoid] + .geo->getExtension(Sketcher::SolverGeometryExtension::getClassTypeId()) + .lock()); auto index = std::get<2>(element->second); - switch(geopos) { + switch (geopos) { case PointPos::none: solvext->setEdge(index, SolverGeometryExtension::Dependent); break; case PointPos::start: - if(index == 0) + if (index == 0) solvext->setStartx(SolverGeometryExtension::Dependent); else solvext->setStarty(SolverGeometryExtension::Dependent); break; case PointPos::end: - if(index == 0) + if (index == 0) solvext->setEndx(SolverGeometryExtension::Dependent); else solvext->setEndy(SolverGeometryExtension::Dependent); break; case PointPos::mid: - if(index == 0) + if (index == 0) solvext->setMidx(SolverGeometryExtension::Dependent); else solvext->setMidy(SolverGeometryExtension::Dependent); @@ -501,29 +522,29 @@ void Sketch::calculateDependentParametersElements() } } - std::vector < std::vector < double*>> groups; + std::vector> groups; GCSsys.getDependentParamsGroups(groups); pDependencyGroups.resize(groups.size()); // translate parameters into elements (Geoid, PointPos) - for(size_t i = 0; i < groups.size(); i++) { - for(size_t j = 0; j < groups[i].size(); j++) { + for (size_t i = 0; i < groups.size(); i++) { + for (size_t j = 0; j < groups[i].size(); j++) { auto element = param2geoelement.find(groups[i][j]); if (element != param2geoelement.end()) { - pDependencyGroups[i].insert(std::pair(std::get<0>(element->second),std::get<1>(element->second))); + pDependencyGroups[i].insert( + std::pair(std::get<0>(element->second), std::get<1>(element->second))); } } } // check if groups have a common element, if yes merge the groups - auto havecommonelement = [] ( std::set < std::pair< int, Sketcher::PointPos>>::iterator begin1, - std::set < std::pair< int, Sketcher::PointPos>>::iterator end1, - std::set < std::pair< int, Sketcher::PointPos>>::iterator begin2, - std::set < std::pair< int, Sketcher::PointPos>>::iterator end2) { - + auto havecommonelement = [](std::set>::iterator begin1, + std::set>::iterator end1, + std::set>::iterator begin2, + std::set>::iterator end2) { while (begin1 != end1 && begin2 != end2) { if (*begin1 < *begin2) ++begin1; @@ -536,28 +557,33 @@ void Sketch::calculateDependentParametersElements() return false; }; - if(pDependencyGroups.size() > 1) { // only if there is more than 1 group - size_t endcount = pDependencyGroups.size()-1; + if (pDependencyGroups.size() > 1) {// only if there is more than 1 group + size_t endcount = pDependencyGroups.size() - 1; - for(size_t i=0; i < endcount; i++) { - if(havecommonelement(pDependencyGroups[i].begin(), pDependencyGroups[i].end(), pDependencyGroups[i+1].begin(), pDependencyGroups[i+1].end())){ - pDependencyGroups[i].insert(pDependencyGroups[i+1].begin(), pDependencyGroups[i+1].end()); - pDependencyGroups.erase(pDependencyGroups.begin()+i+1); + for (size_t i = 0; i < endcount; i++) { + if (havecommonelement(pDependencyGroups[i].begin(), + pDependencyGroups[i].end(), + pDependencyGroups[i + 1].begin(), + pDependencyGroups[i + 1].end())) { + pDependencyGroups[i].insert(pDependencyGroups[i + 1].begin(), + pDependencyGroups[i + 1].end()); + pDependencyGroups.erase(pDependencyGroups.begin() + i + 1); endcount--; } } } } -std::set < std::pair< int, Sketcher::PointPos>> Sketch::getDependencyGroup(int geoId, PointPos pos) const +std::set> Sketch::getDependencyGroup(int geoId, + PointPos pos) const { geoId = checkGeoId(geoId); - std::set < std::pair< int, Sketcher::PointPos>> group; + std::set> group; auto key = std::make_pair(geoId, pos); - for( auto & set : pDependencyGroups) { + for (auto& set : pDependencyGroups) { if (set.find(key) != set.end()) { group = set; break; @@ -569,7 +595,7 @@ std::set < std::pair< int, Sketcher::PointPos>> Sketch::getDependencyGroup(int g std::shared_ptr Sketch::getSolverExtension(int geoId) const { - if(geoId >= 0 && geoId < int(solverExtensions.size())) + if (geoId >= 0 && geoId < int(solverExtensions.size())) return solverExtensions[geoId]; return nullptr; @@ -583,7 +609,7 @@ int Sketch::resetSolver() GCSsys.initSolution(defaultSolverRedundant); GCSsys.getConflicting(Conflicting); GCSsys.getRedundant(Redundant); - GCSsys.getPartiallyRedundant (PartiallyRedundant); + GCSsys.getPartiallyRedundant(PartiallyRedundant); GCSsys.getDependentParams(pDependentParametersList); calculateDependentParametersElements(); @@ -594,119 +620,123 @@ int Sketch::resetSolver() const char* nameByType(Sketch::GeoType type) { switch (type) { - case Sketch::Point: - return "point"; - case Sketch::Line: - return "line"; - case Sketch::Arc: - return "arc"; - case Sketch::Circle: - return "circle"; - case Sketch::Ellipse: - return "ellipse"; - case Sketch::ArcOfEllipse: - return "arcofellipse"; - case Sketch::ArcOfHyperbola: - return "arcofhyperbola"; - case Sketch::ArcOfParabola: - return "arcofparabola"; - case Sketch::BSpline: - return "bspline"; - case Sketch::None: - default: - return "unknown"; + case Sketch::Point: + return "point"; + case Sketch::Line: + return "line"; + case Sketch::Arc: + return "arc"; + case Sketch::Circle: + return "circle"; + case Sketch::Ellipse: + return "ellipse"; + case Sketch::ArcOfEllipse: + return "arcofellipse"; + case Sketch::ArcOfHyperbola: + return "arcofhyperbola"; + case Sketch::ArcOfParabola: + return "arcofparabola"; + case Sketch::BSpline: + return "bspline"; + case Sketch::None: + default: + return "unknown"; } } // Geometry adding ========================================================== -int Sketch::addGeometry(const Part::Geometry *geo, bool fixed) +int Sketch::addGeometry(const Part::Geometry* geo, bool fixed) { - if (geo->getTypeId() == GeomPoint::getClassTypeId()) { // add a point - const GeomPoint *point = static_cast(geo); + if (geo->getTypeId() == GeomPoint::getClassTypeId()) {// add a point + const GeomPoint* point = static_cast(geo); auto pointf = GeometryFacade::getFacade(point); // create the definition struct for that geom return addPoint(*point, fixed); } - else if (geo->getTypeId() == GeomLineSegment::getClassTypeId()) { // add a line - const GeomLineSegment *lineSeg = static_cast(geo); + else if (geo->getTypeId() == GeomLineSegment::getClassTypeId()) {// add a line + const GeomLineSegment* lineSeg = static_cast(geo); // create the definition struct for that geom return addLineSegment(*lineSeg, fixed); } - else if (geo->getTypeId() == GeomCircle::getClassTypeId()) { // add a circle - const GeomCircle *circle = static_cast(geo); + else if (geo->getTypeId() == GeomCircle::getClassTypeId()) {// add a circle + const GeomCircle* circle = static_cast(geo); // create the definition struct for that geom return addCircle(*circle, fixed); } - else if (geo->getTypeId() == GeomEllipse::getClassTypeId()) { // add a ellipse - const GeomEllipse *ellipse = static_cast(geo); + else if (geo->getTypeId() == GeomEllipse::getClassTypeId()) {// add a ellipse + const GeomEllipse* ellipse = static_cast(geo); // create the definition struct for that geom return addEllipse(*ellipse, fixed); } - else if (geo->getTypeId() == GeomArcOfCircle::getClassTypeId()) { // add an arc - const GeomArcOfCircle *aoc = static_cast(geo); + else if (geo->getTypeId() == GeomArcOfCircle::getClassTypeId()) {// add an arc + const GeomArcOfCircle* aoc = static_cast(geo); // create the definition struct for that geom return addArc(*aoc, fixed); } - else if (geo->getTypeId() == GeomArcOfEllipse::getClassTypeId()) { // add an arc - const GeomArcOfEllipse *aoe = static_cast(geo); + else if (geo->getTypeId() == GeomArcOfEllipse::getClassTypeId()) {// add an arc + const GeomArcOfEllipse* aoe = static_cast(geo); // create the definition struct for that geom return addArcOfEllipse(*aoe, fixed); } - else if (geo->getTypeId() == GeomArcOfHyperbola::getClassTypeId()) { // add an arc of hyperbola - const GeomArcOfHyperbola *aoh = static_cast(geo); + else if (geo->getTypeId() == GeomArcOfHyperbola::getClassTypeId()) {// add an arc of hyperbola + const GeomArcOfHyperbola* aoh = static_cast(geo); // create the definition struct for that geom return addArcOfHyperbola(*aoh, fixed); } - else if (geo->getTypeId() == GeomArcOfParabola::getClassTypeId()) { // add an arc of parabola - const GeomArcOfParabola *aop = static_cast(geo); + else if (geo->getTypeId() == GeomArcOfParabola::getClassTypeId()) {// add an arc of parabola + const GeomArcOfParabola* aop = static_cast(geo); // create the definition struct for that geom return addArcOfParabola(*aop, fixed); } - else if (geo->getTypeId() == GeomBSplineCurve::getClassTypeId()) { // add a bspline - const GeomBSplineCurve *bsp = static_cast(geo); + else if (geo->getTypeId() == GeomBSplineCurve::getClassTypeId()) {// add a bspline + const GeomBSplineCurve* bsp = static_cast(geo); // Current B-Spline implementation relies on OCCT calculations, so a second solve - // is necessary to update actual solver implementation to account for changes in B-Spline geometry + // is necessary to update actual solver implementation to account for changes in B-Spline + // geometry resolveAfterGeometryUpdated = true; return addBSpline(*bsp, fixed); } else { - throw Base::TypeError("Sketch::addGeometry(): Unknown or unsupported type added to a sketch"); + throw Base::TypeError( + "Sketch::addGeometry(): Unknown or unsupported type added to a sketch"); } } -int Sketch::addGeometry(const std::vector &geo, bool fixed) +int Sketch::addGeometry(const std::vector& geo, bool fixed) { int ret = -1; - for (std::vector::const_iterator it=geo.begin(); it != geo.end(); ++it) + for (std::vector::const_iterator it = geo.begin(); it != geo.end(); ++it) ret = addGeometry(*it, fixed); return ret; } -int Sketch::addGeometry(const std::vector &geo, - const std::vector &blockedGeometry) +int Sketch::addGeometry(const std::vector& geo, + const std::vector& blockedGeometry) { assert(geo.size() == blockedGeometry.size()); int ret = -1; - std::vector::const_iterator it; + std::vector::const_iterator it; std::vector::const_iterator bit; - for (it=geo.begin(),bit=blockedGeometry.begin(); it != geo.end() && bit !=blockedGeometry.end(); ++it,++bit) + for (it = geo.begin(), bit = blockedGeometry.begin(); + it != geo.end() && bit != blockedGeometry.end(); + ++it, ++bit) ret = addGeometry(*it, *bit); return ret; } -int Sketch::addPoint(const Part::GeomPoint &point, bool fixed) +int Sketch::addPoint(const Part::GeomPoint& point, bool fixed) { - std::vector ¶ms = fixed ? FixParameters : Parameters; + std::vector& params = fixed ? FixParameters : Parameters; // create our own copy - GeomPoint *p = static_cast(point.clone()); + GeomPoint* p = static_cast(point.clone()); // create the definition struct for that geom GeoDef def; - def.geo = p; + def.geo = p; def.type = Point; // set the parameter for the solver @@ -715,8 +745,8 @@ int Sketch::addPoint(const Part::GeomPoint &point, bool fixed) // set the points for later constraints GCS::Point p1; - p1.x = params[params.size()-2]; - p1.y = params[params.size()-1]; + p1.x = params[params.size() - 2]; + p1.y = params[params.size() - 1]; def.startPointId = Points.size(); def.endPointId = Points.size(); def.midPointId = Points.size(); @@ -725,52 +755,58 @@ int Sketch::addPoint(const Part::GeomPoint &point, bool fixed) // store complete set Geoms.push_back(def); - if(!fixed) { - param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::start, 0)); - param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::start, 1)); + if (!fixed) { + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p1.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p1.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1)); } // return the position of the newly added geometry - return Geoms.size()-1; + return Geoms.size() - 1; } -int Sketch::addLine(const Part::GeomLineSegment & /*line*/, bool /*fixed*/) +int Sketch::addLine(const Part::GeomLineSegment& /*line*/, bool /*fixed*/) { // return the position of the newly added geometry - return Geoms.size()-1; + return Geoms.size() - 1; } -int Sketch::addLineSegment(const Part::GeomLineSegment &lineSegment, bool fixed) +int Sketch::addLineSegment(const Part::GeomLineSegment& lineSegment, bool fixed) { - std::vector ¶ms = fixed ? FixParameters : Parameters; + std::vector& params = fixed ? FixParameters : Parameters; // create our own copy - GeomLineSegment *lineSeg = static_cast(lineSegment.clone()); + GeomLineSegment* lineSeg = static_cast(lineSegment.clone()); // create the definition struct for that geom GeoDef def; - def.geo = lineSeg; + def.geo = lineSeg; def.type = Line; // get the points from the line Base::Vector3d start = lineSeg->getStartPoint(); - Base::Vector3d end = lineSeg->getEndPoint(); + Base::Vector3d end = lineSeg->getEndPoint(); // the points for later constraints GCS::Point p1, p2; params.push_back(new double(start.x)); params.push_back(new double(start.y)); - p1.x = params[params.size()-2]; - p1.y = params[params.size()-1]; + p1.x = params[params.size() - 2]; + p1.y = params[params.size() - 1]; params.push_back(new double(end.x)); params.push_back(new double(end.y)); - p2.x = params[params.size()-2]; - p2.y = params[params.size()-1]; + p2.x = params[params.size() - 2]; + p2.y = params[params.size() - 1]; // add the points def.startPointId = Points.size(); - def.endPointId = Points.size()+1; + def.endPointId = Points.size() + 1; Points.push_back(p1); Points.push_back(p2); @@ -784,32 +820,44 @@ int Sketch::addLineSegment(const Part::GeomLineSegment &lineSegment, bool fixed) // store complete set Geoms.push_back(def); - if(!fixed) { - param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::start,0)); - param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::start,1)); - param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p2.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::end,0)); - param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p2.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::end,1)); + if (!fixed) { + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p1.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p1.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p2.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p2.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1)); } // return the position of the newly added geometry - return Geoms.size()-1; + return Geoms.size() - 1; } -int Sketch::addArc(const Part::GeomArcOfCircle &circleSegment, bool fixed) +int Sketch::addArc(const Part::GeomArcOfCircle& circleSegment, bool fixed) { - std::vector ¶ms = fixed ? FixParameters : Parameters; + std::vector& params = fixed ? FixParameters : Parameters; // create our own copy - GeomArcOfCircle *aoc = static_cast(circleSegment.clone()); + GeomArcOfCircle* aoc = static_cast(circleSegment.clone()); // create the definition struct for that geom GeoDef def; - def.geo = aoc; + def.geo = aoc; def.type = Arc; - Base::Vector3d center = aoc->getCenter(); + Base::Vector3d center = aoc->getCenter(); Base::Vector3d startPnt = aoc->getStartPoint(/*emulateCCW=*/true); - Base::Vector3d endPnt = aoc->getEndPoint(/*emulateCCW=*/true); - double radius = aoc->getRadius(); + Base::Vector3d endPnt = aoc->getEndPoint(/*emulateCCW=*/true); + double radius = aoc->getRadius(); double startAngle, endAngle; aoc->getRange(startAngle, endAngle, /*emulateCCW=*/true); @@ -817,18 +865,18 @@ int Sketch::addArc(const Part::GeomArcOfCircle &circleSegment, bool fixed) params.push_back(new double(startPnt.x)); params.push_back(new double(startPnt.y)); - p1.x = params[params.size()-2]; - p1.y = params[params.size()-1]; + p1.x = params[params.size() - 2]; + p1.y = params[params.size() - 1]; params.push_back(new double(endPnt.x)); params.push_back(new double(endPnt.y)); - p2.x = params[params.size()-2]; - p2.y = params[params.size()-1]; + p2.x = params[params.size() - 2]; + p2.y = params[params.size() - 1]; params.push_back(new double(center.x)); params.push_back(new double(center.y)); - p3.x = params[params.size()-2]; - p3.y = params[params.size()-1]; + p3.x = params[params.size() - 2]; + p3.y = params[params.size() - 1]; def.startPointId = Points.size(); Points.push_back(p1); @@ -838,20 +886,20 @@ int Sketch::addArc(const Part::GeomArcOfCircle &circleSegment, bool fixed) Points.push_back(p3); params.push_back(new double(radius)); - double *r = params[params.size()-1]; + double* r = params[params.size() - 1]; params.push_back(new double(startAngle)); - double *a1 = params[params.size()-1]; + double* a1 = params[params.size() - 1]; params.push_back(new double(endAngle)); - double *a2 = params[params.size()-1]; + double* a2 = params[params.size() - 1]; // set the arc for later constraints GCS::Arc a; - a.start = p1; - a.end = p2; - a.center = p3; - a.rad = r; + a.start = p1; + a.end = p2; + a.center = p3; + a.rad = r; a.startAngle = a1; - a.endAngle = a2; + a.endAngle = a2; def.index = Arcs.size(); Arcs.push_back(a); @@ -862,43 +910,70 @@ int Sketch::addArc(const Part::GeomArcOfCircle &circleSegment, bool fixed) if (!fixed) GCSsys.addConstraintArcRules(a); - if(!fixed) { - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p1.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::start,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p1.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::start,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p2.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::end,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p2.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::end,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p3.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::mid,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p3.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::mid,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(r), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(a1), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(a2), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,2)); + if (!fixed) { + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p1.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p1.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p2.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p2.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p3.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p3.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(r), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(a1), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(a2), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 2)); } // return the position of the newly added geometry - return Geoms.size()-1; + return Geoms.size() - 1; } -int Sketch::addArcOfEllipse(const Part::GeomArcOfEllipse &ellipseSegment, bool fixed) +int Sketch::addArcOfEllipse(const Part::GeomArcOfEllipse& ellipseSegment, bool fixed) { - std::vector ¶ms = fixed ? FixParameters : Parameters; + std::vector& params = fixed ? FixParameters : Parameters; // create our own copy - GeomArcOfEllipse *aoe = static_cast(ellipseSegment.clone()); + GeomArcOfEllipse* aoe = static_cast(ellipseSegment.clone()); // create the definition struct for that geom GeoDef def; - def.geo = aoe; + def.geo = aoe; def.type = ArcOfEllipse; - Base::Vector3d center = aoe->getCenter(); + Base::Vector3d center = aoe->getCenter(); Base::Vector3d startPnt = aoe->getStartPoint(/*emulateCCW=*/true); - Base::Vector3d endPnt = aoe->getEndPoint(/*emulateCCW=*/true); - double radmaj = aoe->getMajorRadius(); - double radmin = aoe->getMinorRadius(); + Base::Vector3d endPnt = aoe->getEndPoint(/*emulateCCW=*/true); + double radmaj = aoe->getMajorRadius(); + double radmin = aoe->getMinorRadius(); Base::Vector3d radmajdir = aoe->getMajorAxisDir(); - double dist_C_F = sqrt(radmaj*radmaj-radmin*radmin); + double dist_C_F = sqrt(radmaj * radmaj - radmin * radmin); // solver parameters - Base::Vector3d focus1 = center + dist_C_F*radmajdir; + Base::Vector3d focus1 = center + dist_C_F * radmajdir; double startAngle, endAngle; aoe->getRange(startAngle, endAngle, /*emulateCCW=*/true); @@ -907,23 +982,23 @@ int Sketch::addArcOfEllipse(const Part::GeomArcOfEllipse &ellipseSegment, bool f params.push_back(new double(startPnt.x)); params.push_back(new double(startPnt.y)); - p1.x = params[params.size()-2]; - p1.y = params[params.size()-1]; + p1.x = params[params.size() - 2]; + p1.y = params[params.size() - 1]; params.push_back(new double(endPnt.x)); params.push_back(new double(endPnt.y)); - p2.x = params[params.size()-2]; - p2.y = params[params.size()-1]; + p2.x = params[params.size() - 2]; + p2.y = params[params.size() - 1]; params.push_back(new double(center.x)); params.push_back(new double(center.y)); - p3.x = params[params.size()-2]; - p3.y = params[params.size()-1]; + p3.x = params[params.size() - 2]; + p3.y = params[params.size() - 1]; params.push_back(new double(focus1.x)); params.push_back(new double(focus1.y)); - double *f1X = params[params.size()-2]; - double *f1Y = params[params.size()-1]; + double* f1X = params[params.size() - 2]; + double* f1Y = params[params.size() - 1]; def.startPointId = Points.size(); Points.push_back(p1); @@ -932,26 +1007,26 @@ int Sketch::addArcOfEllipse(const Part::GeomArcOfEllipse &ellipseSegment, bool f def.midPointId = Points.size(); Points.push_back(p3); - //Points.push_back(f1); + // Points.push_back(f1); // add the radius parameters params.push_back(new double(radmin)); - double *rmin = params[params.size()-1]; + double* rmin = params[params.size() - 1]; params.push_back(new double(startAngle)); - double *a1 = params[params.size()-1]; + double* a1 = params[params.size() - 1]; params.push_back(new double(endAngle)); - double *a2 = params[params.size()-1]; + double* a2 = params[params.size() - 1]; // set the arc for later constraints GCS::ArcOfEllipse a; - a.start = p1; - a.end = p2; - a.center = p3; - a.focus1.x = f1X; - a.focus1.y = f1Y; - a.radmin = rmin; + a.start = p1; + a.end = p2; + a.center = p3; + a.focus1.x = f1X; + a.focus1.y = f1Y; + a.radmin = rmin; a.startAngle = a1; - a.endAngle = a2; + a.endAngle = a2; def.index = ArcsOfEllipse.size(); ArcsOfEllipse.push_back(a); @@ -962,70 +1037,103 @@ int Sketch::addArcOfEllipse(const Part::GeomArcOfEllipse &ellipseSegment, bool f if (!fixed) GCSsys.addConstraintArcOfEllipseRules(a); - if(!fixed) { - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p1.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::start,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p1.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::start,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p2.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::end,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p2.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::end,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p3.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::mid,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p3.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::mid,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(f1X), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(f1Y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(rmin), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,2)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(a1), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,3)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(a2), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,4)); + if (!fixed) { + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p1.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p1.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p2.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p2.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p3.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p3.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(f1X), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(f1Y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(rmin), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 2)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(a1), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 3)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(a2), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 4)); } // return the position of the newly added geometry - return Geoms.size()-1; + return Geoms.size() - 1; } -int Sketch::addArcOfHyperbola(const Part::GeomArcOfHyperbola &hyperbolaSegment, bool fixed) +int Sketch::addArcOfHyperbola(const Part::GeomArcOfHyperbola& hyperbolaSegment, bool fixed) { - std::vector ¶ms = fixed ? FixParameters : Parameters; + std::vector& params = fixed ? FixParameters : Parameters; // create our own copy - GeomArcOfHyperbola *aoh = static_cast(hyperbolaSegment.clone()); + GeomArcOfHyperbola* aoh = static_cast(hyperbolaSegment.clone()); // create the definition struct for that geom GeoDef def; - def.geo = aoh; + def.geo = aoh; def.type = ArcOfHyperbola; - Base::Vector3d center = aoh->getCenter(); + Base::Vector3d center = aoh->getCenter(); Base::Vector3d startPnt = aoh->getStartPoint(); - Base::Vector3d endPnt = aoh->getEndPoint(); - double radmaj = aoh->getMajorRadius(); - double radmin = aoh->getMinorRadius(); + Base::Vector3d endPnt = aoh->getEndPoint(); + double radmaj = aoh->getMajorRadius(); + double radmin = aoh->getMinorRadius(); Base::Vector3d radmajdir = aoh->getMajorAxisDir(); - double dist_C_F = sqrt(radmaj*radmaj+radmin*radmin); + double dist_C_F = sqrt(radmaj * radmaj + radmin * radmin); // solver parameters - Base::Vector3d focus1 = center+dist_C_F*radmajdir; //+x + Base::Vector3d focus1 = center + dist_C_F * radmajdir;//+x double startAngle, endAngle; - aoh->getRange(startAngle, endAngle,/*emulateCCW=*/true); + aoh->getRange(startAngle, endAngle, /*emulateCCW=*/true); GCS::Point p1, p2, p3; params.push_back(new double(startPnt.x)); params.push_back(new double(startPnt.y)); - p1.x = params[params.size()-2]; - p1.y = params[params.size()-1]; + p1.x = params[params.size() - 2]; + p1.y = params[params.size() - 1]; params.push_back(new double(endPnt.x)); params.push_back(new double(endPnt.y)); - p2.x = params[params.size()-2]; - p2.y = params[params.size()-1]; + p2.x = params[params.size() - 2]; + p2.y = params[params.size() - 1]; params.push_back(new double(center.x)); params.push_back(new double(center.y)); - p3.x = params[params.size()-2]; - p3.y = params[params.size()-1]; + p3.x = params[params.size() - 2]; + p3.y = params[params.size() - 1]; params.push_back(new double(focus1.x)); params.push_back(new double(focus1.y)); - double *f1X = params[params.size()-2]; - double *f1Y = params[params.size()-1]; + double* f1X = params[params.size() - 2]; + double* f1Y = params[params.size() - 1]; def.startPointId = Points.size(); Points.push_back(p1); @@ -1036,22 +1144,22 @@ int Sketch::addArcOfHyperbola(const Part::GeomArcOfHyperbola &hyperbolaSegment, // add the radius parameters params.push_back(new double(radmin)); - double *rmin = params[params.size()-1]; + double* rmin = params[params.size() - 1]; params.push_back(new double(startAngle)); - double *a1 = params[params.size()-1]; + double* a1 = params[params.size() - 1]; params.push_back(new double(endAngle)); - double *a2 = params[params.size()-1]; + double* a2 = params[params.size() - 1]; // set the arc for later constraints GCS::ArcOfHyperbola a; - a.start = p1; - a.end = p2; - a.center = p3; - a.focus1.x = f1X; - a.focus1.y = f1Y; - a.radmin = rmin; + a.start = p1; + a.end = p2; + a.center = p3; + a.focus1.x = f1X; + a.focus1.y = f1Y; + a.radmin = rmin; a.startAngle = a1; - a.endAngle = a2; + a.endAngle = a2; def.index = ArcsOfHyperbola.size(); ArcsOfHyperbola.push_back(a); @@ -1062,65 +1170,98 @@ int Sketch::addArcOfHyperbola(const Part::GeomArcOfHyperbola &hyperbolaSegment, if (!fixed) GCSsys.addConstraintArcOfHyperbolaRules(a); - if(!fixed) { - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p1.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::start,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p1.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::start,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p2.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::end,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p2.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::end,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p3.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::mid,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p3.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::mid,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(f1X), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(f1Y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(rmin), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,2)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(a1), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,3)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(a2), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,4)); + if (!fixed) { + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p1.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p1.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p2.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p2.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p3.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p3.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(f1X), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(f1Y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(rmin), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 2)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(a1), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 3)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(a2), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 4)); } // return the position of the newly added geometry - return Geoms.size()-1; + return Geoms.size() - 1; } -int Sketch::addArcOfParabola(const Part::GeomArcOfParabola ¶bolaSegment, bool fixed) +int Sketch::addArcOfParabola(const Part::GeomArcOfParabola& parabolaSegment, bool fixed) { - std::vector ¶ms = fixed ? FixParameters : Parameters; + std::vector& params = fixed ? FixParameters : Parameters; // create our own copy - GeomArcOfParabola *aop = static_cast(parabolaSegment.clone()); + GeomArcOfParabola* aop = static_cast(parabolaSegment.clone()); // create the definition struct for that geom GeoDef def; - def.geo = aop; + def.geo = aop; def.type = ArcOfParabola; - Base::Vector3d vertex = aop->getCenter(); + Base::Vector3d vertex = aop->getCenter(); Base::Vector3d startPnt = aop->getStartPoint(); - Base::Vector3d endPnt = aop->getEndPoint(); - Base::Vector3d focus = aop->getFocus(); + Base::Vector3d endPnt = aop->getEndPoint(); + Base::Vector3d focus = aop->getFocus(); double startAngle, endAngle; - aop->getRange(startAngle, endAngle,/*emulateCCW=*/true); + aop->getRange(startAngle, endAngle, /*emulateCCW=*/true); GCS::Point p1, p2, p3, p4; params.push_back(new double(startPnt.x)); params.push_back(new double(startPnt.y)); - p1.x = params[params.size()-2]; - p1.y = params[params.size()-1]; + p1.x = params[params.size() - 2]; + p1.y = params[params.size() - 1]; params.push_back(new double(endPnt.x)); params.push_back(new double(endPnt.y)); - p2.x = params[params.size()-2]; - p2.y = params[params.size()-1]; + p2.x = params[params.size() - 2]; + p2.y = params[params.size() - 1]; params.push_back(new double(vertex.x)); params.push_back(new double(vertex.y)); - p3.x = params[params.size()-2]; - p3.y = params[params.size()-1]; + p3.x = params[params.size() - 2]; + p3.y = params[params.size() - 1]; params.push_back(new double(focus.x)); params.push_back(new double(focus.y)); - p4.x = params[params.size()-2]; - p4.y = params[params.size()-1]; + p4.x = params[params.size() - 2]; + p4.y = params[params.size() - 1]; def.startPointId = Points.size(); Points.push_back(p1); @@ -1131,18 +1272,18 @@ int Sketch::addArcOfParabola(const Part::GeomArcOfParabola ¶bolaSegment, boo // add the radius parameters params.push_back(new double(startAngle)); - double *a1 = params[params.size()-1]; + double* a1 = params[params.size() - 1]; params.push_back(new double(endAngle)); - double *a2 = params[params.size()-1]; + double* a2 = params[params.size() - 1]; // set the arc for later constraints GCS::ArcOfParabola a; - a.start = p1; - a.end = p2; - a.vertex = p3; - a.focus1 = p4; + a.start = p1; + a.end = p2; + a.vertex = p3; + a.focus1 = p4; a.startAngle = a1; - a.endAngle = a2; + a.endAngle = a2; def.index = ArcsOfParabola.size(); ArcsOfParabola.push_back(a); @@ -1153,32 +1294,62 @@ int Sketch::addArcOfParabola(const Part::GeomArcOfParabola ¶bolaSegment, boo if (!fixed) GCSsys.addConstraintArcOfParabolaRules(a); - if(!fixed) { - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p1.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::start,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p1.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::start,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p2.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::end,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p2.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::end,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p3.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::mid,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p3.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::mid,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p4.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p4.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(a1), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,2)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(a2), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,3)); + if (!fixed) { + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p1.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p1.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p2.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p2.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p3.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p3.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p4.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p4.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(a1), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 2)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(a2), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 3)); } // return the position of the newly added geometry - return Geoms.size()-1; + return Geoms.size() - 1; } -int Sketch::addBSpline(const Part::GeomBSplineCurve &bspline, bool fixed) +int Sketch::addBSpline(const Part::GeomBSplineCurve& bspline, bool fixed) { - std::vector ¶ms = fixed ? FixParameters : Parameters; + std::vector& params = fixed ? FixParameters : Parameters; // create our own copy - GeomBSplineCurve *bsp = static_cast(bspline.clone()); + GeomBSplineCurve* bsp = static_cast(bspline.clone()); // create the definition struct for that geom GeoDef def; - def.geo = bsp; + def.geo = bsp; def.type = BSpline; std::vector poles = bsp->getPoles(); @@ -1190,20 +1361,22 @@ int Sketch::addBSpline(const Part::GeomBSplineCurve &bspline, bool fixed) // OCC hack // c means there is a constraint on that weight, nc no constraint - // OCC provides normalized weights when polynomic [1 1 1] [c c c] and unnormalized weights when rational [5 1 5] [c nc c] - // then when changing from polynomic to rational, after the first solve any not-constrained pole circle gets normalized to 1. - // This only happens when changing from polynomic to rational, any subsequent change remains unnormalized [5 1 5] [c nc nc] - // This creates a visual problem that one of the poles shrinks to 1 mm when deleting an equality constraint. + // OCC provides normalized weights when polynomic [1 1 1] [c c c] and unnormalized weights when + // rational [5 1 5] [c nc c] then when changing from polynomic to rational, after the first + // solve any not-constrained pole circle gets normalized to 1. This only happens when changing + // from polynomic to rational, any subsequent change remains unnormalized [5 1 5] [c nc nc] This + // creates a visual problem that one of the poles shrinks to 1 mm when deleting an equality + // constraint. int lastoneindex = -1; int countones = 0; double lastnotone = 1.0; - for(size_t i = 0; i < weights.size(); i++) { - if(weights[i] != 1.0) { + for (size_t i = 0; i < weights.size(); i++) { + if (weights[i] != 1.0) { lastnotone = weights[i]; } - else { // is 1.0 + else {// is 1.0 lastoneindex = i; countones++; } @@ -1215,65 +1388,78 @@ int Sketch::addBSpline(const Part::GeomBSplineCurve &bspline, bool fixed) // end hack Base::Vector3d startPnt = bsp->getStartPoint(); - Base::Vector3d endPnt = bsp->getEndPoint(); + Base::Vector3d endPnt = bsp->getEndPoint(); std::vector spoles; - int i=0; - for(std::vector::const_iterator it = poles.begin(); it != poles.end(); ++it){ - params.push_back(new double( (*it).x )); - params.push_back(new double( (*it).y )); + int i = 0; + for (std::vector::const_iterator it = poles.begin(); it != poles.end(); ++it) { + params.push_back(new double((*it).x)); + params.push_back(new double((*it).y)); GCS::Point p; - p.x = params[params.size()-2]; - p.y = params[params.size()-1]; + p.x = params[params.size() - 2]; + p.y = params[params.size() - 1]; spoles.push_back(p); - if(!fixed) { - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p.x), std::forward_as_tuple(Geoms.size(), Sketcher::PointPos::none,i++)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p.y), std::forward_as_tuple(Geoms.size(), Sketcher::PointPos::none,i++)); + if (!fixed) { + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p.x), + std::forward_as_tuple(Geoms.size(), Sketcher::PointPos::none, i++)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p.y), + std::forward_as_tuple(Geoms.size(), Sketcher::PointPos::none, i++)); } } - std::vector sweights; + std::vector sweights; - for(std::vector::const_iterator it = weights.begin(); it != weights.end(); ++it) { - auto r = new double( (*it) ); + for (std::vector::const_iterator it = weights.begin(); it != weights.end(); ++it) { + auto r = new double((*it)); params.push_back(r); - sweights.push_back(params[params.size()-1]); + sweights.push_back(params[params.size() - 1]); - if(!fixed) { - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(r), std::forward_as_tuple(Geoms.size(), Sketcher::PointPos::none,i++)); + if (!fixed) { + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(r), + std::forward_as_tuple(Geoms.size(), Sketcher::PointPos::none, i++)); } } - std::vector sknots; + std::vector sknots; - for(std::vector::const_iterator it = knots.begin(); it != knots.end(); ++it) { - double * knot = new double( (*it) ); - //params.push_back(knot); + for (std::vector::const_iterator it = knots.begin(); it != knots.end(); ++it) { + double* knot = new double((*it)); + // params.push_back(knot); sknots.push_back(knot); } GCS::Point p1, p2; - double * p1x = new double(startPnt.x); - double * p1y = new double(startPnt.y); + double* p1x = new double(startPnt.x); + double* p1y = new double(startPnt.y); - // If periodic, startpoint and endpoint do not play a role in the solver, this can remove unnecessary DoF of determining where in the curve - // the start and the stop should be. However, since start and end points are placed above knots, removing them leads to that knot being unusable. + // If periodic, startpoint and endpoint do not play a role in the solver, this can remove + // unnecessary DoF of determining where in the curve the start and the stop should be. However, + // since start and end points are placed above knots, removing them leads to that knot being + // unusable. params.push_back(p1x); params.push_back(p1y); p1.x = p1x; p1.y = p1y; - double * p2x = new double(endPnt.x); - double * p2y = new double(endPnt.y); + double* p2x = new double(endPnt.x); + double* p2y = new double(endPnt.y); - // If periodic, startpoint and endpoint do not play a role in the solver, this can remove unnecessary DoF of determining where in the curve - // the start and the stop should be. However, since start and end points are placed above knots, removing them leads to that knot being unusable. + // If periodic, startpoint and endpoint do not play a role in the solver, this can remove + // unnecessary DoF of determining where in the curve the start and the stop should be. However, + // since start and end points are placed above knots, removing them leads to that knot being + // unusable. params.push_back(p2x); params.push_back(p2y); @@ -1286,20 +1472,22 @@ int Sketch::addBSpline(const Part::GeomBSplineCurve &bspline, bool fixed) Points.push_back(p2); GCS::BSpline bs; - bs.start = p1; - bs.end = p2; - bs.poles = spoles; - bs.weights = sweights; - bs.knots = sknots; - bs.mult = mult; - bs.degree = degree; - bs.periodic = periodic; - def.index = BSplines.size(); + bs.start = p1; + bs.end = p2; + bs.poles = spoles; + bs.weights = sweights; + bs.knots = sknots; + bs.mult = mult; + bs.degree = degree; + bs.periodic = periodic; + def.index = BSplines.size(); - // non-solver related, just to enable initialization of knotspoints which is not a parameter of the solver + // non-solver related, just to enable initialization of knotspoints which is not a parameter of + // the solver bs.knotpointGeoids.resize(knots.size()); - for(std::vector::iterator it = bs.knotpointGeoids.begin(); it != bs.knotpointGeoids.end(); ++it) { + for (std::vector::iterator it = bs.knotpointGeoids.begin(); it != bs.knotpointGeoids.end(); + ++it) { (*it) = GeoEnum::GeoUndef; } @@ -1309,50 +1497,62 @@ int Sketch::addBSpline(const Part::GeomBSplineCurve &bspline, bool fixed) Geoms.push_back(def); // WARNING: This is only valid where the multiplicity of the endpoints conforms with a BSpline - // only then the startpoint is the first control point and the endpoint is the last control point - // accordingly, it is never the case for a periodic BSpline. - // NOTE: For an external B-spline (i.e. fixed=true) we must not set the coincident constraints - // as the points are not movable anyway. - // See #issue 0003176: Sketcher: always over-constrained when referencing external B-Spline + // only then the startpoint is the first control point and the endpoint is the last control + // point accordingly, it is never the case for a periodic BSpline. NOTE: For an external + // B-spline (i.e. fixed=true) we must not set the coincident constraints as the points are not + // movable anyway. See #issue 0003176: Sketcher: always over-constrained when referencing + // external B-Spline if (!fixed && !bs.periodic) { if (bs.mult[0] > bs.degree) - GCSsys.addConstraintP2PCoincident(*(bs.poles.begin()),bs.start); - if (bs.mult[mult.size()-1] > bs.degree) - GCSsys.addConstraintP2PCoincident(*(bs.poles.end()-1),bs.end); + GCSsys.addConstraintP2PCoincident(*(bs.poles.begin()), bs.start); + if (bs.mult[mult.size() - 1] > bs.degree) + GCSsys.addConstraintP2PCoincident(*(bs.poles.end() - 1), bs.end); } - if(!fixed) { + if (!fixed) { // Note: Poles and weight parameters are emplaced above - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p1.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::start,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p1.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::start,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p2.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::end,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p2.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::end,1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p1.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p1.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p2.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p2.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1)); } // return the position of the newly added geometry - return Geoms.size()-1; + return Geoms.size() - 1; } -int Sketch::addCircle(const Part::GeomCircle &cir, bool fixed) +int Sketch::addCircle(const Part::GeomCircle& cir, bool fixed) { - std::vector ¶ms = fixed ? FixParameters : Parameters; + std::vector& params = fixed ? FixParameters : Parameters; // create our own copy - GeomCircle *circ = static_cast(cir.clone()); + GeomCircle* circ = static_cast(cir.clone()); // create the definition struct for that geom GeoDef def; - def.geo = circ; + def.geo = circ; def.type = Circle; Base::Vector3d center = circ->getCenter(); - double radius = circ->getRadius(); + double radius = circ->getRadius(); GCS::Point p1; params.push_back(new double(center.x)); params.push_back(new double(center.y)); - p1.x = params[params.size()-2]; - p1.y = params[params.size()-1]; + p1.x = params[params.size() - 2]; + p1.y = params[params.size() - 1]; params.push_back(new double(radius)); @@ -1360,75 +1560,84 @@ int Sketch::addCircle(const Part::GeomCircle &cir, bool fixed) Points.push_back(p1); // add the radius parameter - double *r = params[params.size()-1]; + double* r = params[params.size() - 1]; // set the circle for later constraints GCS::Circle c; c.center = p1; - c.rad = r; + c.rad = r; def.index = Circles.size(); Circles.push_back(c); // store complete set Geoms.push_back(def); - if(!fixed) { - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p1.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::mid,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(p1.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::mid,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(r), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,0)); + if (!fixed) { + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p1.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(p1.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(r), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0)); } // return the position of the newly added geometry - return Geoms.size()-1; + return Geoms.size() - 1; } -int Sketch::addEllipse(const Part::GeomEllipse &elip, bool fixed) +int Sketch::addEllipse(const Part::GeomEllipse& elip, bool fixed) { - std::vector ¶ms = fixed ? FixParameters : Parameters; + std::vector& params = fixed ? FixParameters : Parameters; // create our own copy - GeomEllipse *elips = static_cast(elip.clone()); + GeomEllipse* elips = static_cast(elip.clone()); // create the definition struct for that geom GeoDef def; - def.geo = elips; + def.geo = elips; def.type = Ellipse; Base::Vector3d center = elips->getCenter(); - double radmaj = elips->getMajorRadius(); - double radmin = elips->getMinorRadius(); + double radmaj = elips->getMajorRadius(); + double radmin = elips->getMinorRadius(); Base::Vector3d radmajdir = elips->getMajorAxisDir(); - double dist_C_F = sqrt(radmaj*radmaj-radmin*radmin); + double dist_C_F = sqrt(radmaj * radmaj - radmin * radmin); // solver parameters - Base::Vector3d focus1 = center + dist_C_F*radmajdir; //+x - //double *radmin; + Base::Vector3d focus1 = center + dist_C_F * radmajdir;//+x + // double *radmin; GCS::Point c; params.push_back(new double(center.x)); params.push_back(new double(center.y)); - c.x = params[params.size()-2]; - c.y = params[params.size()-1]; + c.x = params[params.size() - 2]; + c.y = params[params.size() - 1]; - def.midPointId = Points.size(); // this takes midPointId+1 + def.midPointId = Points.size();// this takes midPointId+1 Points.push_back(c); params.push_back(new double(focus1.x)); params.push_back(new double(focus1.y)); - double *f1X = params[params.size()-2]; - double *f1Y = params[params.size()-1]; + double* f1X = params[params.size() - 2]; + double* f1Y = params[params.size() - 1]; // add the radius parameters params.push_back(new double(radmin)); - double *rmin = params[params.size()-1]; + double* rmin = params[params.size() - 1]; // set the ellipse for later constraints GCS::Ellipse e; - e.focus1.x = f1X; - e.focus1.y = f1Y; - e.center = c; - e.radmin = rmin; + e.focus1.x = f1X; + e.focus1.y = f1Y; + e.center = c; + e.radmin = rmin; def.index = Ellipses.size(); Ellipses.push_back(e); @@ -1436,26 +1645,42 @@ int Sketch::addEllipse(const Part::GeomEllipse &elip, bool fixed) // store complete set Geoms.push_back(def); - if(!fixed) { - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(c.x), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::mid,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(c.y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::mid,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(f1X), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,0)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(f1Y), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,1)); - param2geoelement.emplace(std::piecewise_construct, std::forward_as_tuple(rmin), std::forward_as_tuple(Geoms.size()-1, Sketcher::PointPos::none,2)); + if (!fixed) { + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(c.x), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(c.y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(f1X), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(f1Y), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 1)); + param2geoelement.emplace( + std::piecewise_construct, + std::forward_as_tuple(rmin), + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 2)); } // return the position of the newly added geometry - return Geoms.size()-1; + return Geoms.size() - 1; } -std::vector Sketch::extractGeometry(bool withConstructionElements, - bool withExternalElements) const +std::vector Sketch::extractGeometry(bool withConstructionElements, + bool withExternalElements) const { - std::vector temp; + std::vector temp; temp.reserve(Geoms.size()); - for (std::vector::const_iterator it=Geoms.begin(); it != Geoms.end(); ++it) { + for (std::vector::const_iterator it = Geoms.begin(); it != Geoms.end(); ++it) { auto gf = GeometryFacade::getFacade(it->geo); - if ((!it->external || withExternalElements) && (!gf->getConstruction() || withConstructionElements)) + if ((!it->external || withExternalElements) + && (!gf->getConstruction() || withConstructionElements)) temp.push_back(it->geo->clone()); } @@ -1467,9 +1692,10 @@ GeoListFacade Sketch::extractGeoListFacade() const std::vector temp; temp.reserve(Geoms.size()); int internalGeometryCount = 0; - for (std::vector::const_iterator it=Geoms.begin(); it != Geoms.end(); ++it) { - auto gf = GeometryFacade::getFacade(it->geo->clone(), true); // GeometryFacade is the owner of this allocation - if(!it->external) + for (std::vector::const_iterator it = Geoms.begin(); it != Geoms.end(); ++it) { + // GeometryFacade is the owner of this allocation + auto gf = GeometryFacade::getFacade(it->geo->clone(), true); + if (!it->external) internalGeometryCount++; temp.push_back(std::move(gf)); @@ -1478,53 +1704,52 @@ GeoListFacade Sketch::extractGeoListFacade() const return GeoListFacade::getGeoListModel(std::move(temp), internalGeometryCount); } -void Sketch::updateExtension(int geoId, std::unique_ptr && ext) +void Sketch::updateExtension(int geoId, std::unique_ptr&& ext) { geoId = checkGeoId(geoId); Geoms[geoId].geo->setExtension(std::move(ext)); - } Py::Tuple Sketch::getPyGeometry() const { Py::Tuple tuple(Geoms.size()); - int i=0; - for (std::vector::const_iterator it=Geoms.begin(); it != Geoms.end(); ++it, i++) { + int i = 0; + for (std::vector::const_iterator it = Geoms.begin(); it != Geoms.end(); ++it, i++) { if (it->type == Point) { - Base::Vector3d temp(*(Points[it->startPointId].x),*(Points[it->startPointId].y),0); + Base::Vector3d temp(*(Points[it->startPointId].x), *(Points[it->startPointId].y), 0); tuple[i] = Py::asObject(new VectorPy(temp)); } else if (it->type == Line) { - GeomLineSegment *lineSeg = static_cast(it->geo->clone()); + GeomLineSegment* lineSeg = static_cast(it->geo->clone()); tuple[i] = Py::asObject(new LineSegmentPy(lineSeg)); } else if (it->type == Arc) { - GeomArcOfCircle *aoc = static_cast(it->geo->clone()); + GeomArcOfCircle* aoc = static_cast(it->geo->clone()); tuple[i] = Py::asObject(new ArcOfCirclePy(aoc)); } else if (it->type == Circle) { - GeomCircle *circle = static_cast(it->geo->clone()); + GeomCircle* circle = static_cast(it->geo->clone()); tuple[i] = Py::asObject(new CirclePy(circle)); } else if (it->type == Ellipse) { - GeomEllipse *ellipse = static_cast(it->geo->clone()); + GeomEllipse* ellipse = static_cast(it->geo->clone()); tuple[i] = Py::asObject(new EllipsePy(ellipse)); } else if (it->type == ArcOfEllipse) { - GeomArcOfEllipse *ellipse = static_cast(it->geo->clone()); + GeomArcOfEllipse* ellipse = static_cast(it->geo->clone()); tuple[i] = Py::asObject(new ArcOfEllipsePy(ellipse)); } else if (it->type == ArcOfHyperbola) { - GeomArcOfHyperbola *aoh = static_cast(it->geo->clone()); + GeomArcOfHyperbola* aoh = static_cast(it->geo->clone()); tuple[i] = Py::asObject(new ArcOfHyperbolaPy(aoh)); } else if (it->type == ArcOfParabola) { - GeomArcOfParabola *aop = static_cast(it->geo->clone()); + GeomArcOfParabola* aop = static_cast(it->geo->clone()); tuple[i] = Py::asObject(new ArcOfParabolaPy(aop)); } else if (it->type == BSpline) { - GeomBSplineCurve *bsp = static_cast(it->geo->clone()); + GeomBSplineCurve* bsp = static_cast(it->geo->clone()); tuple[i] = Py::asObject(new BSplineCurvePy(bsp)); } else { @@ -1537,8 +1762,8 @@ Py::Tuple Sketch::getPyGeometry() const int Sketch::checkGeoId(int geoId) const { if (geoId < 0) - geoId += Geoms.size();//convert negative external-geometry index to index into Geoms - if(!( geoId >= 0 && geoId < int(Geoms.size()) )) + geoId += Geoms.size();// convert negative external-geometry index to index into Geoms + if (!(geoId >= 0 && geoId < int(Geoms.size()))) throw Base::IndexError("Sketch::checkGeoId. GeoId index out range."); return geoId; } @@ -1549,19 +1774,19 @@ GCS::Curve* Sketch::getGCSCurveByGeoId(int geoId) switch (Geoms[geoId].type) { case Line: return &Lines[Geoms[geoId].index]; - break; + break; case Circle: return &Circles[Geoms[geoId].index]; - break; + break; case Arc: return &Arcs[Geoms[geoId].index]; - break; + break; case Ellipse: return &Ellipses[Geoms[geoId].index]; - break; + break; case ArcOfEllipse: return &ArcsOfEllipse[Geoms[geoId].index]; - break; + break; case ArcOfHyperbola: return &ArcsOfHyperbola[Geoms[geoId].index]; break; @@ -1580,408 +1805,460 @@ const GCS::Curve* Sketch::getGCSCurveByGeoId(int geoId) const { // I hereby guarantee that if I modify the non-const version, I will still // never modify (this). I return const copy to enforce on my users. - return const_cast(this)->getGCSCurveByGeoId(geoId); + return const_cast(this)->getGCSCurveByGeoId(geoId); } // constraint adding ========================================================== -int Sketch::addConstraint(const Constraint *constraint) +int Sketch::addConstraint(const Constraint* constraint) { if (Geoms.empty()) - throw Base::ValueError("Sketch::addConstraint. Can't add constraint to a sketch with no geometry!"); + throw Base::ValueError( + "Sketch::addConstraint. Can't add constraint to a sketch with no geometry!"); int rtn = -1; ConstrDef c; - c.constr=const_cast(constraint); - c.driving=constraint->isDriving; + c.constr = const_cast(constraint); + c.driving = constraint->isDriving; switch (constraint->Type) { - case DistanceX: - if (constraint->FirstPos == PointPos::none){ // horizontal length of a line - c.value = new double(constraint->getValue()); - if(c.driving) - FixParameters.push_back(c.value); - else { - Parameters.push_back(c.value); - DrivenParameters.push_back(c.value); - } - - rtn = addDistanceXConstraint(constraint->First,c.value,c.driving); - } - else if (constraint->Second == GeoEnum::GeoUndef) {// point on fixed x-coordinate - c.value = new double(constraint->getValue()); - if(c.driving) - FixParameters.push_back(c.value); - else { - Parameters.push_back(c.value); - DrivenParameters.push_back(c.value); - } - - rtn = addCoordinateXConstraint(constraint->First,constraint->FirstPos,c.value,c.driving); - } - else if (constraint->SecondPos != PointPos::none) {// point to point horizontal distance - c.value = new double(constraint->getValue()); - if(c.driving) - FixParameters.push_back(c.value); - else { - Parameters.push_back(c.value); - DrivenParameters.push_back(c.value); - } - - rtn = addDistanceXConstraint(constraint->First,constraint->FirstPos, - constraint->Second,constraint->SecondPos,c.value,c.driving); - } - break; - case DistanceY: - if (constraint->FirstPos == PointPos::none){ // vertical length of a line - c.value = new double(constraint->getValue()); - if(c.driving) - FixParameters.push_back(c.value); - else { - Parameters.push_back(c.value); - DrivenParameters.push_back(c.value); - } - - rtn = addDistanceYConstraint(constraint->First,c.value,c.driving); - } - else if (constraint->Second == GeoEnum::GeoUndef){ // point on fixed y-coordinate - c.value = new double(constraint->getValue()); - if(c.driving) - FixParameters.push_back(c.value); - else { - Parameters.push_back(c.value); - DrivenParameters.push_back(c.value); - } - - rtn = addCoordinateYConstraint(constraint->First,constraint->FirstPos,c.value,c.driving); - } - else if (constraint->SecondPos != PointPos::none){ // point to point vertical distance - c.value = new double(constraint->getValue()); - if(c.driving) - FixParameters.push_back(c.value); - else { - Parameters.push_back(c.value); - DrivenParameters.push_back(c.value); - } - - rtn = addDistanceYConstraint(constraint->First,constraint->FirstPos, - constraint->Second,constraint->SecondPos,c.value,c.driving); - } - break; - case Horizontal: - if (constraint->Second == GeoEnum::GeoUndef) // horizontal line - rtn = addHorizontalConstraint(constraint->First); - else // two points on the same horizontal line - rtn = addHorizontalConstraint(constraint->First,constraint->FirstPos, - constraint->Second,constraint->SecondPos); - break; - case Vertical: - if (constraint->Second == GeoEnum::GeoUndef) // vertical line - rtn = addVerticalConstraint(constraint->First); - else // two points on the same vertical line - rtn = addVerticalConstraint(constraint->First,constraint->FirstPos, - constraint->Second,constraint->SecondPos); - break; - case Coincident: - rtn = addPointCoincidentConstraint(constraint->First,constraint->FirstPos,constraint->Second,constraint->SecondPos); - break; - case PointOnObject: - if (Geoms[checkGeoId(constraint->Second)].type == BSpline) { - c.value = new double(constraint->getValue()); - // Driving doesn't make sense here - Parameters.push_back(c.value); - - rtn = addPointOnObjectConstraint(constraint->First,constraint->FirstPos, constraint->Second, c.value); - } - else - rtn = addPointOnObjectConstraint(constraint->First,constraint->FirstPos, constraint->Second); - break; - case Parallel: - rtn = addParallelConstraint(constraint->First,constraint->Second); - break; - case Perpendicular: - if (constraint->FirstPos == PointPos::none && - constraint->SecondPos == PointPos::none && - constraint->Third == GeoEnum::GeoUndef){ - //simple perpendicularity - rtn = addPerpendicularConstraint(constraint->First,constraint->Second); - } - else { - //any other point-wise perpendicularity - c.value = new double(constraint->getValue()); - if(c.driving) - FixParameters.push_back(c.value); - else { - Parameters.push_back(c.value); - DrivenParameters.push_back(c.value); - } - - rtn = addAngleAtPointConstraint( - constraint->First, constraint->FirstPos, - constraint->Second, constraint->SecondPos, - constraint->Third, constraint->ThirdPos, - c.value, constraint->Type, c.driving); - } - break; - case Tangent: { - bool isSpecialCase = false; - - if (constraint->FirstPos == PointPos::none && - constraint->SecondPos == PointPos::none && - constraint->Third == GeoEnum::GeoUndef){ - //simple tangency - rtn = addTangentConstraint(constraint->First,constraint->Second); - - isSpecialCase = true; - } - else if (constraint->FirstPos == PointPos::start && - constraint->Third == GeoEnum::GeoUndef) { - // check for B-Spline Knot to curve tangency - auto knotgeoId = checkGeoId(constraint->First); - if (Geoms[knotgeoId].type == Point) { - auto *point = static_cast(Geoms[knotgeoId].geo); - - if (GeometryFacade::isInternalType(point,InternalType::BSplineKnotPoint)) { - auto bsplinegeoid = internalAlignmentGeometryMap.at(constraint->First); - - bsplinegeoid = checkGeoId(bsplinegeoid); - - auto linegeoid = checkGeoId(constraint->Second); - - if (Geoms[linegeoid].type == Line) { - if (constraint->SecondPos == PointPos::none) { - rtn = addTangentLineAtBSplineKnotConstraint( - linegeoid, bsplinegeoid, knotgeoId); - - isSpecialCase = true; - } - else if (constraint->SecondPos == PointPos::start || - constraint->SecondPos == PointPos::end) { - rtn = addTangentLineEndpointAtBSplineKnotConstraint( - linegeoid, constraint->SecondPos, bsplinegeoid, knotgeoId); - - isSpecialCase = true; - } - } - } - } - } - if (!isSpecialCase) { - //any other point-wise tangency (endpoint-to-curve, endpoint-to-endpoint, tangent-via-point) - c.value = new double(constraint->getValue()); - if(c.driving) - FixParameters.push_back(c.value); - else { - Parameters.push_back(c.value); - DrivenParameters.push_back(c.value); - } - - rtn = addAngleAtPointConstraint( - constraint->First, constraint->FirstPos, - constraint->Second, constraint->SecondPos, - constraint->Third, constraint->ThirdPos, - c.value, constraint->Type, c.driving); - } - break; - } - case Distance: - if (constraint->SecondPos != PointPos::none){ // point to point distance - c.value = new double(constraint->getValue()); - if(c.driving) - FixParameters.push_back(c.value); - else { - Parameters.push_back(c.value); - DrivenParameters.push_back(c.value); - } - rtn = addDistanceConstraint(constraint->First,constraint->FirstPos, - constraint->Second,constraint->SecondPos, - c.value,c.driving); - } - else if (constraint->FirstPos == PointPos::none && - constraint->SecondPos == PointPos::none && - constraint->Second != GeoEnum::GeoUndef && - constraint->Third == GeoEnum::GeoUndef) { // circle to circle, circle to arc, etc. - - c.value = new double(constraint->getValue()); - if(c.driving) - FixParameters.push_back(c.value); - else { - Parameters.push_back(c.value); - DrivenParameters.push_back(c.value); - } - rtn = addDistanceConstraint(constraint->First, constraint->Second,c.value,c.driving); - } - else if (constraint->Second != GeoEnum::GeoUndef) { - if (constraint->FirstPos != PointPos::none) { // point to line distance + case DistanceX: + if (constraint->FirstPos == PointPos::none) {// horizontal length of a line c.value = new double(constraint->getValue()); - if(c.driving) + if (c.driving) FixParameters.push_back(c.value); else { Parameters.push_back(c.value); DrivenParameters.push_back(c.value); } - rtn = addDistanceConstraint(constraint->First,constraint->FirstPos,constraint->Second,c.value,c.driving); + + rtn = addDistanceXConstraint(constraint->First, c.value, c.driving); } + else if (constraint->Second == GeoEnum::GeoUndef) {// point on fixed x-coordinate + c.value = new double(constraint->getValue()); + if (c.driving) + FixParameters.push_back(c.value); + else { + Parameters.push_back(c.value); + DrivenParameters.push_back(c.value); + } + + rtn = addCoordinateXConstraint( + constraint->First, constraint->FirstPos, c.value, c.driving); + } + else if (constraint->SecondPos != PointPos::none) {// point to point horizontal distance + c.value = new double(constraint->getValue()); + if (c.driving) + FixParameters.push_back(c.value); + else { + Parameters.push_back(c.value); + DrivenParameters.push_back(c.value); + } + + rtn = addDistanceXConstraint(constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + c.value, + c.driving); + } + break; + case DistanceY: + if (constraint->FirstPos == PointPos::none) {// vertical length of a line + c.value = new double(constraint->getValue()); + if (c.driving) + FixParameters.push_back(c.value); + else { + Parameters.push_back(c.value); + DrivenParameters.push_back(c.value); + } + + rtn = addDistanceYConstraint(constraint->First, c.value, c.driving); + } + else if (constraint->Second == GeoEnum::GeoUndef) {// point on fixed y-coordinate + c.value = new double(constraint->getValue()); + if (c.driving) + FixParameters.push_back(c.value); + else { + Parameters.push_back(c.value); + DrivenParameters.push_back(c.value); + } + + rtn = addCoordinateYConstraint( + constraint->First, constraint->FirstPos, c.value, c.driving); + } + else if (constraint->SecondPos != PointPos::none) {// point to point vertical distance + c.value = new double(constraint->getValue()); + if (c.driving) + FixParameters.push_back(c.value); + else { + Parameters.push_back(c.value); + DrivenParameters.push_back(c.value); + } + + rtn = addDistanceYConstraint(constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + c.value, + c.driving); + } + break; + case Horizontal: + if (constraint->Second == GeoEnum::GeoUndef)// horizontal line + rtn = addHorizontalConstraint(constraint->First); + else// two points on the same horizontal line + rtn = addHorizontalConstraint(constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos); + break; + case Vertical: + if (constraint->Second == GeoEnum::GeoUndef)// vertical line + rtn = addVerticalConstraint(constraint->First); + else// two points on the same vertical line + rtn = addVerticalConstraint(constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos); + break; + case Coincident: + rtn = addPointCoincidentConstraint( + constraint->First, constraint->FirstPos, constraint->Second, constraint->SecondPos); + break; + case PointOnObject: + if (Geoms[checkGeoId(constraint->Second)].type == BSpline) { + c.value = new double(constraint->getValue()); + // Driving doesn't make sense here + Parameters.push_back(c.value); + + rtn = addPointOnObjectConstraint( + constraint->First, constraint->FirstPos, constraint->Second, c.value); + } + else + rtn = addPointOnObjectConstraint( + constraint->First, constraint->FirstPos, constraint->Second); + break; + case Parallel: + rtn = addParallelConstraint(constraint->First, constraint->Second); + break; + case Perpendicular: + if (constraint->FirstPos == PointPos::none && constraint->SecondPos == PointPos::none + && constraint->Third == GeoEnum::GeoUndef) { + // simple perpendicularity + rtn = addPerpendicularConstraint(constraint->First, constraint->Second); + } + else { + // any other point-wise perpendicularity + c.value = new double(constraint->getValue()); + if (c.driving) + FixParameters.push_back(c.value); + else { + Parameters.push_back(c.value); + DrivenParameters.push_back(c.value); + } + + rtn = addAngleAtPointConstraint(constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + constraint->Third, + constraint->ThirdPos, + c.value, + constraint->Type, + c.driving); + } + break; + case Tangent: { + bool isSpecialCase = false; + + if (constraint->FirstPos == PointPos::none && constraint->SecondPos == PointPos::none + && constraint->Third == GeoEnum::GeoUndef) { + // simple tangency + rtn = addTangentConstraint(constraint->First, constraint->Second); + + isSpecialCase = true; + } + else if (constraint->FirstPos == PointPos::start + && constraint->Third == GeoEnum::GeoUndef) { + // check for B-Spline Knot to curve tangency + auto knotgeoId = checkGeoId(constraint->First); + if (Geoms[knotgeoId].type == Point) { + auto* point = static_cast(Geoms[knotgeoId].geo); + + if (GeometryFacade::isInternalType(point, InternalType::BSplineKnotPoint)) { + auto bsplinegeoid = internalAlignmentGeometryMap.at(constraint->First); + + bsplinegeoid = checkGeoId(bsplinegeoid); + + auto linegeoid = checkGeoId(constraint->Second); + + if (Geoms[linegeoid].type == Line) { + if (constraint->SecondPos == PointPos::none) { + rtn = addTangentLineAtBSplineKnotConstraint( + linegeoid, bsplinegeoid, knotgeoId); + + isSpecialCase = true; + } + else if (constraint->SecondPos == PointPos::start + || constraint->SecondPos == PointPos::end) { + rtn = addTangentLineEndpointAtBSplineKnotConstraint( + linegeoid, constraint->SecondPos, bsplinegeoid, knotgeoId); + + isSpecialCase = true; + } + } + } + } + } + if (!isSpecialCase) { + // any other point-wise tangency (endpoint-to-curve, endpoint-to-endpoint, + // tangent-via-point) + c.value = new double(constraint->getValue()); + if (c.driving) + FixParameters.push_back(c.value); + else { + Parameters.push_back(c.value); + DrivenParameters.push_back(c.value); + } + + rtn = addAngleAtPointConstraint(constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + constraint->Third, + constraint->ThirdPos, + c.value, + constraint->Type, + c.driving); + } + break; } - else {// line length + case Distance: + if (constraint->SecondPos != PointPos::none) {// point to point distance + c.value = new double(constraint->getValue()); + if (c.driving) + FixParameters.push_back(c.value); + else { + Parameters.push_back(c.value); + DrivenParameters.push_back(c.value); + } + rtn = addDistanceConstraint(constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + c.value, + c.driving); + } + else if (constraint->FirstPos == PointPos::none + && constraint->SecondPos == PointPos::none + && constraint->Second != GeoEnum::GeoUndef + && constraint->Third + == GeoEnum::GeoUndef) {// circle to circle, circle to arc, etc. + + c.value = new double(constraint->getValue()); + if (c.driving) + FixParameters.push_back(c.value); + else { + Parameters.push_back(c.value); + DrivenParameters.push_back(c.value); + } + rtn = addDistanceConstraint( + constraint->First, constraint->Second, c.value, c.driving); + } + else if (constraint->Second != GeoEnum::GeoUndef) { + if (constraint->FirstPos != PointPos::none) {// point to line distance + c.value = new double(constraint->getValue()); + if (c.driving) + FixParameters.push_back(c.value); + else { + Parameters.push_back(c.value); + DrivenParameters.push_back(c.value); + } + rtn = addDistanceConstraint(constraint->First, + constraint->FirstPos, + constraint->Second, + c.value, + c.driving); + } + } + else {// line length + c.value = new double(constraint->getValue()); + if (c.driving) + FixParameters.push_back(c.value); + else { + Parameters.push_back(c.value); + DrivenParameters.push_back(c.value); + } + + rtn = addDistanceConstraint(constraint->First, c.value, c.driving); + } + break; + case Angle: + if (constraint->Third != GeoEnum::GeoUndef) { + c.value = new double(constraint->getValue()); + if (c.driving) + FixParameters.push_back(c.value); + else { + Parameters.push_back(c.value); + DrivenParameters.push_back(c.value); + } + + rtn = addAngleAtPointConstraint(constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + constraint->Third, + constraint->ThirdPos, + c.value, + constraint->Type, + c.driving); + } + // angle between two lines (with explicit start points) + else if (constraint->SecondPos != PointPos::none) { + c.value = new double(constraint->getValue()); + if (c.driving) + FixParameters.push_back(c.value); + else { + Parameters.push_back(c.value); + DrivenParameters.push_back(c.value); + } + + rtn = addAngleConstraint(constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + c.value, + c.driving); + } + else if (constraint->Second != GeoEnum::GeoUndef) {// angle between two lines + c.value = new double(constraint->getValue()); + if (c.driving) + FixParameters.push_back(c.value); + else { + Parameters.push_back(c.value); + DrivenParameters.push_back(c.value); + } + + rtn = addAngleConstraint(constraint->First, constraint->Second, c.value, c.driving); + } + else if (constraint->First != GeoEnum::GeoUndef) {// orientation angle of a line + c.value = new double(constraint->getValue()); + if (c.driving) + FixParameters.push_back(c.value); + else { + Parameters.push_back(c.value); + DrivenParameters.push_back(c.value); + } + + rtn = addAngleConstraint(constraint->First, c.value, c.driving); + } + break; + case Radius: { c.value = new double(constraint->getValue()); - if(c.driving) + if (c.driving) FixParameters.push_back(c.value); else { Parameters.push_back(c.value); DrivenParameters.push_back(c.value); } - rtn = addDistanceConstraint(constraint->First,c.value,c.driving); + rtn = addRadiusConstraint(constraint->First, c.value, c.driving); + break; } - break; - case Angle: - if (constraint->Third != GeoEnum::GeoUndef){ + case Diameter: { c.value = new double(constraint->getValue()); - if(c.driving) + if (c.driving) FixParameters.push_back(c.value); else { Parameters.push_back(c.value); DrivenParameters.push_back(c.value); } - rtn = addAngleAtPointConstraint ( - constraint->First, constraint->FirstPos, - constraint->Second, constraint->SecondPos, - constraint->Third, constraint->ThirdPos, - c.value, constraint->Type,c.driving); + rtn = addDiameterConstraint(constraint->First, c.value, c.driving); + break; } - else if (constraint->SecondPos != PointPos::none){ // angle between two lines (with explicit start points) + case Weight: { c.value = new double(constraint->getValue()); - if(c.driving) + if (c.driving) FixParameters.push_back(c.value); else { Parameters.push_back(c.value); DrivenParameters.push_back(c.value); } - rtn = addAngleConstraint(constraint->First,constraint->FirstPos, - constraint->Second,constraint->SecondPos,c.value,c.driving); + rtn = addRadiusConstraint(constraint->First, c.value, c.driving); + break; } - else if (constraint->Second != GeoEnum::GeoUndef){ // angle between two lines - c.value = new double(constraint->getValue()); - if(c.driving) - FixParameters.push_back(c.value); - else { - Parameters.push_back(c.value); - DrivenParameters.push_back(c.value); + case Equal: + rtn = addEqualConstraint(constraint->First, constraint->Second); + break; + case Symmetric: + if (constraint->ThirdPos != PointPos::none) + rtn = addSymmetricConstraint(constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + constraint->Third, + constraint->ThirdPos); + else + rtn = addSymmetricConstraint(constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + constraint->Third); + break; + case InternalAlignment: + switch (constraint->AlignmentType) { + case EllipseMajorDiameter: + rtn = addInternalAlignmentEllipseMajorDiameter(constraint->First, + constraint->Second); + break; + case EllipseMinorDiameter: + rtn = addInternalAlignmentEllipseMinorDiameter(constraint->First, + constraint->Second); + break; + case EllipseFocus1: + rtn = addInternalAlignmentEllipseFocus1(constraint->First, constraint->Second); + break; + case EllipseFocus2: + rtn = addInternalAlignmentEllipseFocus2(constraint->First, constraint->Second); + break; + case HyperbolaMajor: + rtn = addInternalAlignmentHyperbolaMajorDiameter(constraint->First, + constraint->Second); + break; + case HyperbolaMinor: + rtn = addInternalAlignmentHyperbolaMinorDiameter(constraint->First, + constraint->Second); + break; + case HyperbolaFocus: + rtn = addInternalAlignmentHyperbolaFocus(constraint->First, constraint->Second); + break; + case ParabolaFocus: + rtn = addInternalAlignmentParabolaFocus(constraint->First, constraint->Second); + break; + case BSplineControlPoint: + rtn = addInternalAlignmentBSplineControlPoint( + constraint->First, constraint->Second, constraint->InternalAlignmentIndex); + break; + case BSplineKnotPoint: + rtn = addInternalAlignmentKnotPoint( + constraint->First, constraint->Second, constraint->InternalAlignmentIndex); + break; + case ParabolaFocalAxis: + rtn = addInternalAlignmentParabolaFocalDistance(constraint->First, + constraint->Second); + break; + default: + break; } - - rtn = addAngleConstraint(constraint->First,constraint->Second,c.value,c.driving); - } - else if (constraint->First != GeoEnum::GeoUndef) {// orientation angle of a line - c.value = new double(constraint->getValue()); - if(c.driving) - FixParameters.push_back(c.value); - else { - Parameters.push_back(c.value); - DrivenParameters.push_back(c.value); - } - - rtn = addAngleConstraint(constraint->First,c.value,c.driving); - } - break; - case Radius: - { - c.value = new double(constraint->getValue()); - if(c.driving) - FixParameters.push_back(c.value); - else { - Parameters.push_back(c.value); - DrivenParameters.push_back(c.value); - } - - rtn = addRadiusConstraint(constraint->First, c.value,c.driving); - break; - } - case Diameter: - { - c.value = new double(constraint->getValue()); - if(c.driving) - FixParameters.push_back(c.value); - else { - Parameters.push_back(c.value); - DrivenParameters.push_back(c.value); - } - - rtn = addDiameterConstraint(constraint->First, c.value,c.driving); - break; - } - case Weight: - { - c.value = new double(constraint->getValue()); - if(c.driving) - FixParameters.push_back(c.value); - else { - Parameters.push_back(c.value); - DrivenParameters.push_back(c.value); - } - - rtn = addRadiusConstraint(constraint->First, c.value,c.driving); - break; - } - case Equal: - rtn = addEqualConstraint(constraint->First,constraint->Second); - break; - case Symmetric: - if (constraint->ThirdPos != PointPos::none) - rtn = addSymmetricConstraint(constraint->First,constraint->FirstPos, - constraint->Second,constraint->SecondPos, - constraint->Third,constraint->ThirdPos); - else - rtn = addSymmetricConstraint(constraint->First,constraint->FirstPos, - constraint->Second,constraint->SecondPos,constraint->Third); - break; - case InternalAlignment: - switch(constraint->AlignmentType) { - case EllipseMajorDiameter: - rtn = addInternalAlignmentEllipseMajorDiameter(constraint->First,constraint->Second); - break; - case EllipseMinorDiameter: - rtn = addInternalAlignmentEllipseMinorDiameter(constraint->First,constraint->Second); - break; - case EllipseFocus1: - rtn = addInternalAlignmentEllipseFocus1(constraint->First,constraint->Second); - break; - case EllipseFocus2: - rtn = addInternalAlignmentEllipseFocus2(constraint->First,constraint->Second); - break; - case HyperbolaMajor: - rtn = addInternalAlignmentHyperbolaMajorDiameter(constraint->First,constraint->Second); - break; - case HyperbolaMinor: - rtn = addInternalAlignmentHyperbolaMinorDiameter(constraint->First,constraint->Second); - break; - case HyperbolaFocus: - rtn = addInternalAlignmentHyperbolaFocus(constraint->First,constraint->Second); - break; - case ParabolaFocus: - rtn = addInternalAlignmentParabolaFocus(constraint->First,constraint->Second); - break; - case BSplineControlPoint: - rtn = addInternalAlignmentBSplineControlPoint(constraint->First,constraint->Second, constraint->InternalAlignmentIndex); - break; - case BSplineKnotPoint: - rtn = addInternalAlignmentKnotPoint(constraint->First,constraint->Second, constraint->InternalAlignmentIndex); - break; - case ParabolaFocalAxis: - rtn = addInternalAlignmentParabolaFocalDistance(constraint->First,constraint->Second); - break; - default: - break; - } - break; - case SnellsLaw: - { + break; + case SnellsLaw: { c.value = new double(constraint->getValue()); c.secondvalue = new double(constraint->getValue()); - if(c.driving) { + if (c.driving) { FixParameters.push_back(c.value); FixParameters.push_back(c.secondvalue); } @@ -1990,37 +2267,42 @@ int Sketch::addConstraint(const Constraint *constraint) Parameters.push_back(c.secondvalue); DrivenParameters.push_back(c.value); DrivenParameters.push_back(c.secondvalue); - } - //assert(constraint->ThirdPos==none); //will work anyway... - rtn = addSnellsLawConstraint(constraint->First, constraint->FirstPos, - constraint->Second, constraint->SecondPos, + // assert(constraint->ThirdPos==none); //will work anyway... + rtn = addSnellsLawConstraint(constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, constraint->Third, - c.value, c.secondvalue,c.driving); - } - break; - case Sketcher::None: // ambiguous enum value - case Sketcher::Block: // handled separately while adding geometry - case NumConstraintTypes: - break; + c.value, + c.secondvalue, + c.driving); + } break; + case Sketcher::None: // ambiguous enum value + case Sketcher::Block:// handled separately while adding geometry + case NumConstraintTypes: + break; } Constrs.push_back(c); return rtn; } -int Sketch::addConstraints(const std::vector &ConstraintList) +int Sketch::addConstraints(const std::vector& ConstraintList) { int rtn = -1; int cid = 0; - for (std::vector::const_iterator it = ConstraintList.begin();it!=ConstraintList.end();++it,++cid) { - rtn = addConstraint (*it); + for (std::vector::const_iterator it = ConstraintList.begin(); + it != ConstraintList.end(); + ++it, ++cid) { + rtn = addConstraint(*it); - if(rtn == -1) { + if (rtn == -1) { int humanconstraintid = cid + 1; - Base::Console().Error("Sketcher constraint number %d is malformed!\n",humanconstraintid); + Base::Console().Error("Sketcher constraint number %d is malformed!\n", + humanconstraintid); MalformedConstraints.push_back(humanconstraintid); } } @@ -2028,127 +2310,164 @@ int Sketch::addConstraints(const std::vector &ConstraintList) return rtn; } -int Sketch::addConstraints(const std::vector &ConstraintList, - const std::vector &unenforceableConstraints) +int Sketch::addConstraints(const std::vector& ConstraintList, + const std::vector& unenforceableConstraints) { int rtn = -1; int cid = 0; - for (std::vector::const_iterator it = ConstraintList.begin();it!=ConstraintList.end();++it,++cid) { + for (std::vector::const_iterator it = ConstraintList.begin(); + it != ConstraintList.end(); + ++it, ++cid) { if (!unenforceableConstraints[cid] && (*it)->Type != Block && (*it)->isActive) { - rtn = addConstraint (*it); + rtn = addConstraint(*it); - if(rtn == -1) { + if (rtn == -1) { int humanconstraintid = cid + 1; - Base::Console().Error("Sketcher constraint number %d is malformed!\n",humanconstraintid); + Base::Console().Error("Sketcher constraint number %d is malformed!\n", + humanconstraintid); MalformedConstraints.push_back(humanconstraintid); } } else { - ++ConstraintsCounter; // For correct solver redundant reporting + ++ConstraintsCounter;// For correct solver redundant reporting } } return rtn; } -void Sketch::getBlockedGeometry(std::vector & blockedGeometry, - std::vector & unenforceableConstraints, - const std::vector &ConstraintList) const +void Sketch::getBlockedGeometry(std::vector& blockedGeometry, + std::vector& unenforceableConstraints, + const std::vector& ConstraintList) const { std::vector internalAlignmentConstraintIndex; std::vector internalAlignmentgeo; - std::vector geo2blockingconstraintindex(blockedGeometry.size(),-1); + std::vector geo2blockingconstraintindex(blockedGeometry.size(), -1); // Detect Blocked and internal constraints int i = 0; - for (std::vector::const_iterator it = ConstraintList.begin();it!=ConstraintList.end();++it,++i) { - switch((*it)->Type) { - case Block: - { + for (std::vector::const_iterator it = ConstraintList.begin(); + it != ConstraintList.end(); + ++it, ++i) { + switch ((*it)->Type) { + case Block: { int geoid = (*it)->First; - if(geoid>=0 && geoid= 0 && geoid < int(blockedGeometry.size())) { + blockedGeometry[geoid] = true; + geo2blockingconstraintindex[geoid] = i; } - } - break; + } break; case InternalAlignment: internalAlignmentConstraintIndex.push_back(i); - break; + break; default: - break; + break; } } - // if a GeoId is blocked and it is linked to Internal Alignment, then GeoIds linked via Internal Alignment are also to be blocked - for(std::vector::iterator it = internalAlignmentConstraintIndex.begin(); it != internalAlignmentConstraintIndex.end() ; it++) { + // if a GeoId is blocked and it is linked to Internal Alignment, then GeoIds linked via Internal + // Alignment are also to be blocked + for (std::vector::iterator it = internalAlignmentConstraintIndex.begin(); + it != internalAlignmentConstraintIndex.end(); + it++) { if (blockedGeometry[ConstraintList[(*it)]->Second]) { blockedGeometry[ConstraintList[(*it)]->First] = true; // associated geometry gets the same blocking constraint index as the blocked element - geo2blockingconstraintindex[ConstraintList[(*it)]->First]= geo2blockingconstraintindex[ConstraintList[(*it)]->Second]; + geo2blockingconstraintindex[ConstraintList[(*it)]->First] = + geo2blockingconstraintindex[ConstraintList[(*it)]->Second]; internalAlignmentgeo.push_back(ConstraintList[(*it)]->First); - unenforceableConstraints[(*it)]= true; + unenforceableConstraints[(*it)] = true; } } i = 0; - for (std::vector::const_iterator it = ConstraintList.begin();it!=ConstraintList.end();++it,++i) { - if((*it)->isDriving) { - // additionally any further constraint on auxiliary elements linked via Internal Alignment are also unenforceable. - for(std::vector::iterator itg = internalAlignmentgeo.begin(); itg != internalAlignmentgeo.end() ; itg++) { - if( (*it)->First==*itg || (*it)->Second==*itg || (*it)->Third==*itg ) { - unenforceableConstraints[i]= true; + for (std::vector::const_iterator it = ConstraintList.begin(); + it != ConstraintList.end(); + ++it, ++i) { + if ((*it)->isDriving) { + // additionally any further constraint on auxiliary elements linked via Internal + // Alignment are also unenforceable. + for (std::vector::iterator itg = internalAlignmentgeo.begin(); + itg != internalAlignmentgeo.end(); + itg++) { + if ((*it)->First == *itg || (*it)->Second == *itg || (*it)->Third == *itg) { + unenforceableConstraints[i] = true; } } // IMPORTANT NOTE: - // The rest of the ignoring of redundant/conflicting applies to constraints introduced before the blocking constraint only - // Constraints introduced after the block will not be ignored and will lead to redundancy/conflicting status as per normal - // solver behaviour + // The rest of the ignoring of redundant/conflicting applies to constraints introduced + // before the blocking constraint only Constraints introduced after the block will not + // be ignored and will lead to redundancy/conflicting status as per normal solver + // behaviour - // further, any constraint taking only one element, which is blocked is also unenforceable - if((*it)->Second==GeoEnum::GeoUndef && (*it)->Third==GeoEnum::GeoUndef && (*it)->First>=0 ) { - if (blockedGeometry[(*it)->First] && i < geo2blockingconstraintindex[(*it)->First]) { - unenforceableConstraints[i]= true; + // further, any constraint taking only one element, which is blocked is also + // unenforceable + if ((*it)->Second == GeoEnum::GeoUndef && (*it)->Third == GeoEnum::GeoUndef + && (*it)->First >= 0) { + if (blockedGeometry[(*it)->First] + && i < geo2blockingconstraintindex[(*it)->First]) { + unenforceableConstraints[i] = true; } } - // further any constraint on only two elements where both elements are blocked or one is blocked and the other is an axis or external - // provided that the constraints precede the last block constraint. - else if((*it)->Third==GeoEnum::GeoUndef) { - if ( ((*it)->First>=0 && (*it)->Second>=0 && blockedGeometry[(*it)->First] && blockedGeometry[(*it)->Second] && - (i < geo2blockingconstraintindex[(*it)->First] || i < geo2blockingconstraintindex[(*it)->Second])) || - ((*it)->First<0 && (*it)->Second>=0 && blockedGeometry[(*it)->Second] && i < geo2blockingconstraintindex[(*it)->Second]) || - ((*it)->First>=0 && (*it)->Second<0 && blockedGeometry[(*it)->First] && i < geo2blockingconstraintindex[(*it)->First]) ){ - unenforceableConstraints[i]= true; - } - } - // further any constraint on three elements where the three of them are blocked, or two are blocked and the other is an axis or external geo - // or any constraint on three elements where one is blocked and the other two are axis or external geo, provided that the constraints precede + // further any constraint on only two elements where both elements are blocked or one is + // blocked and the other is an axis or external provided that the constraints precede // the last block constraint. + else if ((*it)->Third == GeoEnum::GeoUndef) { + if (((*it)->First >= 0 && (*it)->Second >= 0 && blockedGeometry[(*it)->First] + && blockedGeometry[(*it)->Second] + && (i < geo2blockingconstraintindex[(*it)->First] + || i < geo2blockingconstraintindex[(*it)->Second])) + || ((*it)->First < 0 && (*it)->Second >= 0 && blockedGeometry[(*it)->Second] + && i < geo2blockingconstraintindex[(*it)->Second]) + || ((*it)->First >= 0 && (*it)->Second < 0 && blockedGeometry[(*it)->First] + && i < geo2blockingconstraintindex[(*it)->First])) { + unenforceableConstraints[i] = true; + } + } + // further any constraint on three elements where the three of them are blocked, or two + // are blocked and the other is an axis or external geo or any constraint on three + // elements where one is blocked and the other two are axis or external geo, provided + // that the constraints precede the last block constraint. else { - if( ((*it)->First>=0 && (*it)->Second>=0 && (*it)->Third>=0 && - blockedGeometry[(*it)->First] && blockedGeometry[(*it)->Second] && blockedGeometry[(*it)->Third] && - (i < geo2blockingconstraintindex[(*it)->First] || i < geo2blockingconstraintindex[(*it)->Second] || i < geo2blockingconstraintindex[(*it)->Third])) || - ((*it)->First<0 && (*it)->Second>=0 && (*it)->Third>=0 && blockedGeometry[(*it)->Second] && blockedGeometry[(*it)->Third] && - (i < geo2blockingconstraintindex[(*it)->Second] || i < geo2blockingconstraintindex[(*it)->Third])) || - ((*it)->First>=0 && (*it)->Second<0 && (*it)->Third>=0 && blockedGeometry[(*it)->First] && blockedGeometry[(*it)->Third] && - (i < geo2blockingconstraintindex[(*it)->First] || i < geo2blockingconstraintindex[(*it)->Third])) || - ((*it)->First>=0 && (*it)->Second>=0 && (*it)->Third<0 && blockedGeometry[(*it)->First] && blockedGeometry[(*it)->Second] && - (i < geo2blockingconstraintindex[(*it)->First] || i < geo2blockingconstraintindex[(*it)->Second])) || - ((*it)->First>=0 && (*it)->Second<0 && (*it)->Third<0 && blockedGeometry[(*it)->First] && i < geo2blockingconstraintindex[(*it)->First]) || - ((*it)->First<0 && (*it)->Second>=0 && (*it)->Third<0 && blockedGeometry[(*it)->Second] && i < geo2blockingconstraintindex[(*it)->Second]) || - ((*it)->First<0 && (*it)->Second<0 && (*it)->Third>=0 && blockedGeometry[(*it)->Third] && i < geo2blockingconstraintindex[(*it)->Third]) ) { + if (((*it)->First >= 0 && (*it)->Second >= 0 && (*it)->Third >= 0 + && blockedGeometry[(*it)->First] && blockedGeometry[(*it)->Second] + && blockedGeometry[(*it)->Third] + && (i < geo2blockingconstraintindex[(*it)->First] + || i < geo2blockingconstraintindex[(*it)->Second] + || i < geo2blockingconstraintindex[(*it)->Third])) + || ((*it)->First < 0 && (*it)->Second >= 0 && (*it)->Third >= 0 + && blockedGeometry[(*it)->Second] && blockedGeometry[(*it)->Third] + && (i < geo2blockingconstraintindex[(*it)->Second] + || i < geo2blockingconstraintindex[(*it)->Third])) + || ((*it)->First >= 0 && (*it)->Second < 0 && (*it)->Third >= 0 + && blockedGeometry[(*it)->First] && blockedGeometry[(*it)->Third] + && (i < geo2blockingconstraintindex[(*it)->First] + || i < geo2blockingconstraintindex[(*it)->Third])) + || ((*it)->First >= 0 && (*it)->Second >= 0 && (*it)->Third < 0 + && blockedGeometry[(*it)->First] && blockedGeometry[(*it)->Second] + && (i < geo2blockingconstraintindex[(*it)->First] + || i < geo2blockingconstraintindex[(*it)->Second])) + || ((*it)->First >= 0 && (*it)->Second < 0 && (*it)->Third < 0 + && blockedGeometry[(*it)->First] + && i < geo2blockingconstraintindex[(*it)->First]) + || ((*it)->First < 0 && (*it)->Second >= 0 && (*it)->Third < 0 + && blockedGeometry[(*it)->Second] + && i < geo2blockingconstraintindex[(*it)->Second]) + || ((*it)->First < 0 && (*it)->Second < 0 && (*it)->Third >= 0 + && blockedGeometry[(*it)->Third] + && i < geo2blockingconstraintindex[(*it)->Third])) { - unenforceableConstraints[i]= true; + unenforceableConstraints[i] = true; } } } } } -int Sketch::addCoordinateXConstraint(int geoId, PointPos pos, double * value, bool driving) +int Sketch::addCoordinateXConstraint(int geoId, PointPos pos, double* value, bool driving) { geoId = checkGeoId(geoId); @@ -2156,7 +2475,7 @@ int Sketch::addCoordinateXConstraint(int geoId, PointPos pos, double * value, bo if (pointId >= 0 && pointId < int(Points.size())) { - GCS::Point &p = Points[pointId]; + GCS::Point& p = Points[pointId]; int tag = ++ConstraintsCounter; GCSsys.addConstraintCoordinateX(p, value, tag, driving); return ConstraintsCounter; @@ -2164,14 +2483,14 @@ int Sketch::addCoordinateXConstraint(int geoId, PointPos pos, double * value, bo return -1; } -int Sketch::addCoordinateYConstraint(int geoId, PointPos pos, double * value, bool driving) +int Sketch::addCoordinateYConstraint(int geoId, PointPos pos, double* value, bool driving) { geoId = checkGeoId(geoId); int pointId = getPointId(geoId, pos); if (pointId >= 0 && pointId < int(Points.size())) { - GCS::Point &p = Points[pointId]; + GCS::Point& p = Points[pointId]; int tag = ++ConstraintsCounter; GCSsys.addConstraintCoordinateY(p, value, tag, driving); return ConstraintsCounter; @@ -2179,35 +2498,36 @@ int Sketch::addCoordinateYConstraint(int geoId, PointPos pos, double * value, bo return -1; } -int Sketch::addDistanceXConstraint(int geoId, double * value, bool driving) +int Sketch::addDistanceXConstraint(int geoId, double* value, bool driving) { geoId = checkGeoId(geoId); if (Geoms[geoId].type != Line) return -1; - GCS::Line &l = Lines[Geoms[geoId].index]; + GCS::Line& l = Lines[Geoms[geoId].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintDifference(l.p1.x, l.p2.x, value, tag, driving); return ConstraintsCounter; } -int Sketch::addDistanceYConstraint(int geoId, double * value, bool driving) +int Sketch::addDistanceYConstraint(int geoId, double* value, bool driving) { geoId = checkGeoId(geoId); if (Geoms[geoId].type != Line) return -1; - GCS::Line &l = Lines[Geoms[geoId].index]; + GCS::Line& l = Lines[Geoms[geoId].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintDifference(l.p1.y, l.p2.y, value, tag, driving); return ConstraintsCounter; } -int Sketch::addDistanceXConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, double * value, bool driving) +int Sketch::addDistanceXConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, + double* value, bool driving) { geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); @@ -2215,10 +2535,10 @@ int Sketch::addDistanceXConstraint(int geoId1, PointPos pos1, int geoId2, PointP int pointId1 = getPointId(geoId1, pos1); int pointId2 = getPointId(geoId2, pos2); - if (pointId1 >= 0 && pointId1 < int(Points.size()) && - pointId2 >= 0 && pointId2 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; - GCS::Point &p2 = Points[pointId2]; + if (pointId1 >= 0 && pointId1 < int(Points.size()) && pointId2 >= 0 + && pointId2 < int(Points.size())) { + GCS::Point& p1 = Points[pointId1]; + GCS::Point& p2 = Points[pointId2]; int tag = ++ConstraintsCounter; GCSsys.addConstraintDifference(p1.x, p2.x, value, tag, driving); @@ -2227,7 +2547,8 @@ int Sketch::addDistanceXConstraint(int geoId1, PointPos pos1, int geoId2, PointP return -1; } -int Sketch::addDistanceYConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, double * value, bool driving) +int Sketch::addDistanceYConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, + double* value, bool driving) { geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); @@ -2235,10 +2556,10 @@ int Sketch::addDistanceYConstraint(int geoId1, PointPos pos1, int geoId2, PointP int pointId1 = getPointId(geoId1, pos1); int pointId2 = getPointId(geoId2, pos2); - if (pointId1 >= 0 && pointId1 < int(Points.size()) && - pointId2 >= 0 && pointId2 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; - GCS::Point &p2 = Points[pointId2]; + if (pointId1 >= 0 && pointId1 < int(Points.size()) && pointId2 >= 0 + && pointId2 < int(Points.size())) { + GCS::Point& p1 = Points[pointId1]; + GCS::Point& p2 = Points[pointId2]; int tag = ++ConstraintsCounter; GCSsys.addConstraintDifference(p1.y, p2.y, value, tag, driving); @@ -2255,7 +2576,7 @@ int Sketch::addHorizontalConstraint(int geoId) if (Geoms[geoId].type != Line) return -1; - GCS::Line &l = Lines[Geoms[geoId].index]; + GCS::Line& l = Lines[Geoms[geoId].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintHorizontal(l, tag); return ConstraintsCounter; @@ -2270,10 +2591,10 @@ int Sketch::addHorizontalConstraint(int geoId1, PointPos pos1, int geoId2, Point int pointId1 = getPointId(geoId1, pos1); int pointId2 = getPointId(geoId2, pos2); - if (pointId1 >= 0 && pointId1 < int(Points.size()) && - pointId2 >= 0 && pointId2 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; - GCS::Point &p2 = Points[pointId2]; + if (pointId1 >= 0 && pointId1 < int(Points.size()) && pointId2 >= 0 + && pointId2 < int(Points.size())) { + GCS::Point& p1 = Points[pointId1]; + GCS::Point& p2 = Points[pointId2]; int tag = ++ConstraintsCounter; GCSsys.addConstraintHorizontal(p1, p2, tag); return ConstraintsCounter; @@ -2289,7 +2610,7 @@ int Sketch::addVerticalConstraint(int geoId) if (Geoms[geoId].type != Line) return -1; - GCS::Line &l = Lines[Geoms[geoId].index]; + GCS::Line& l = Lines[Geoms[geoId].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintVertical(l, tag); return ConstraintsCounter; @@ -2304,10 +2625,10 @@ int Sketch::addVerticalConstraint(int geoId1, PointPos pos1, int geoId2, PointPo int pointId1 = getPointId(geoId1, pos1); int pointId2 = getPointId(geoId2, pos2); - if (pointId1 >= 0 && pointId1 < int(Points.size()) && - pointId2 >= 0 && pointId2 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; - GCS::Point &p2 = Points[pointId2]; + if (pointId1 >= 0 && pointId1 < int(Points.size()) && pointId2 >= 0 + && pointId2 < int(Points.size())) { + GCS::Point& p1 = Points[pointId1]; + GCS::Point& p2 = Points[pointId2]; int tag = ++ConstraintsCounter; GCSsys.addConstraintVertical(p1, p2, tag); return ConstraintsCounter; @@ -2323,10 +2644,10 @@ int Sketch::addPointCoincidentConstraint(int geoId1, PointPos pos1, int geoId2, int pointId1 = getPointId(geoId1, pos1); int pointId2 = getPointId(geoId2, pos2); - if (pointId1 >= 0 && pointId1 < int(Points.size()) && - pointId2 >= 0 && pointId2 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; - GCS::Point &p2 = Points[pointId2]; + if (pointId1 >= 0 && pointId1 < int(Points.size()) && pointId2 >= 0 + && pointId2 < int(Points.size())) { + GCS::Point& p1 = Points[pointId1]; + GCS::Point& p2 = Points[pointId2]; int tag = ++ConstraintsCounter; GCSsys.addConstraintP2PCoincident(p1, p2, tag); return ConstraintsCounter; @@ -2339,12 +2660,11 @@ int Sketch::addParallelConstraint(int geoId1, int geoId2) geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); - if (Geoms[geoId1].type != Line || - Geoms[geoId2].type != Line) + if (Geoms[geoId1].type != Line || Geoms[geoId2].type != Line) return -1; - GCS::Line &l1 = Lines[Geoms[geoId1].index]; - GCS::Line &l2 = Lines[Geoms[geoId2].index]; + GCS::Line& l1 = Lines[Geoms[geoId1].index]; + GCS::Line& l2 = Lines[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintParallel(l1, l2, tag); return ConstraintsCounter; @@ -2362,8 +2682,8 @@ int Sketch::addPerpendicularConstraint(int geoId1, int geoId2) if (Geoms[geoId2].type == Line) { if (Geoms[geoId1].type == Line) { - GCS::Line &l1 = Lines[Geoms[geoId1].index]; - GCS::Line &l2 = Lines[Geoms[geoId2].index]; + GCS::Line& l1 = Lines[Geoms[geoId1].index]; + GCS::Line& l2 = Lines[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintPerpendicular(l1, l2, tag); return ConstraintsCounter; @@ -2373,9 +2693,9 @@ int Sketch::addPerpendicularConstraint(int geoId1, int geoId2) } if (Geoms[geoId1].type == Line) { - GCS::Line &l1 = Lines[Geoms[geoId1].index]; + GCS::Line& l1 = Lines[Geoms[geoId1].index]; if (Geoms[geoId2].type == Arc || Geoms[geoId2].type == Circle) { - GCS::Point &p2 = Points[Geoms[geoId2].midPointId]; + GCS::Point& p2 = Points[Geoms[geoId2].midPointId]; int tag = ++ConstraintsCounter; GCSsys.addConstraintPointOnLine(p2, l1, tag); return ConstraintsCounter; @@ -2383,7 +2703,8 @@ int Sketch::addPerpendicularConstraint(int geoId1, int geoId2) } Base::Console().Warning("Perpendicular constraints between %s and %s are not supported.\n", - nameByType(Geoms[geoId1].type), nameByType(Geoms[geoId2].type)); + nameByType(Geoms[geoId1].type), + nameByType(Geoms[geoId2].type)); return -1; } @@ -2401,9 +2722,9 @@ int Sketch::addTangentConstraint(int geoId1, int geoId2) if (Geoms[geoId2].type == Line) { if (Geoms[geoId1].type == Line) { - GCS::Line &l1 = Lines[Geoms[geoId1].index]; - GCS::Point &l2p1 = Points[Geoms[geoId2].startPointId]; - GCS::Point &l2p2 = Points[Geoms[geoId2].endPointId]; + GCS::Line& l1 = Lines[Geoms[geoId1].index]; + GCS::Point& l2p1 = Points[Geoms[geoId2].startPointId]; + GCS::Point& l2p2 = Points[Geoms[geoId2].endPointId]; int tag = ++ConstraintsCounter; GCSsys.addConstraintPointOnLine(l2p1, l1, tag); GCSsys.addConstraintPointOnLine(l2p2, l1, tag); @@ -2414,46 +2735,47 @@ int Sketch::addTangentConstraint(int geoId1, int geoId2) } if (Geoms[geoId1].type == Line) { - GCS::Line &l = Lines[Geoms[geoId1].index]; + GCS::Line& l = Lines[Geoms[geoId1].index]; if (Geoms[geoId2].type == Arc) { - GCS::Arc &a = Arcs[Geoms[geoId2].index]; + GCS::Arc& a = Arcs[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintTangent(l, a, tag); return ConstraintsCounter; } else if (Geoms[geoId2].type == Circle) { - GCS::Circle &c = Circles[Geoms[geoId2].index]; + GCS::Circle& c = Circles[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintTangent(l, c, tag); return ConstraintsCounter; } else if (Geoms[geoId2].type == Ellipse) { - GCS::Ellipse &e = Ellipses[Geoms[geoId2].index]; + GCS::Ellipse& e = Ellipses[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintTangent(l, e, tag); return ConstraintsCounter; } else if (Geoms[geoId2].type == ArcOfEllipse) { - GCS::ArcOfEllipse &a = ArcsOfEllipse[Geoms[geoId2].index]; + GCS::ArcOfEllipse& a = ArcsOfEllipse[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintTangent(l, a, tag); return ConstraintsCounter; } } else if (Geoms[geoId1].type == Circle) { - GCS::Circle &c = Circles[Geoms[geoId1].index]; + GCS::Circle& c = Circles[Geoms[geoId1].index]; if (Geoms[geoId2].type == Circle) { - GCS::Circle &c2 = Circles[Geoms[geoId2].index]; + GCS::Circle& c2 = Circles[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintTangent(c, c2, tag); return ConstraintsCounter; } else if (Geoms[geoId2].type == Ellipse) { - Base::Console().Error("Direct tangency constraint between circle and ellipse is not supported. Use tangent-via-point instead."); + Base::Console().Error("Direct tangency constraint between circle and ellipse is not " + "supported. Use tangent-via-point instead."); return -1; } else if (Geoms[geoId2].type == Arc) { - GCS::Arc &a = Arcs[Geoms[geoId2].index]; + GCS::Arc& a = Arcs[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintTangent(c, a, tag); return ConstraintsCounter; @@ -2461,28 +2783,31 @@ int Sketch::addTangentConstraint(int geoId1, int geoId2) } else if (Geoms[geoId1].type == Ellipse) { if (Geoms[geoId2].type == Circle) { - Base::Console().Error("Direct tangency constraint between circle and ellipse is not supported. Use tangent-via-point instead."); + Base::Console().Error("Direct tangency constraint between circle and ellipse is not " + "supported. Use tangent-via-point instead."); return -1; } else if (Geoms[geoId2].type == Arc) { - Base::Console().Error("Direct tangency constraint between arc and ellipse is not supported. Use tangent-via-point instead."); + Base::Console().Error("Direct tangency constraint between arc and ellipse is not " + "supported. Use tangent-via-point instead."); return -1; } } else if (Geoms[geoId1].type == Arc) { - GCS::Arc &a = Arcs[Geoms[geoId1].index]; + GCS::Arc& a = Arcs[Geoms[geoId1].index]; if (Geoms[geoId2].type == Circle) { - GCS::Circle &c = Circles[Geoms[geoId2].index]; + GCS::Circle& c = Circles[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintTangent(c, a, tag); return ConstraintsCounter; } else if (Geoms[geoId2].type == Ellipse) { - Base::Console().Error("Direct tangency constraint between arc and ellipse is not supported. Use tangent-via-point instead."); + Base::Console().Error("Direct tangency constraint between arc and ellipse is not " + "supported. Use tangent-via-point instead."); return -1; } else if (Geoms[geoId2].type == Arc) { - GCS::Arc &a2 = Arcs[Geoms[geoId2].index]; + GCS::Arc& a2 = Arcs[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintTangent(a, a2, tag); return ConstraintsCounter; @@ -2492,26 +2817,27 @@ int Sketch::addTangentConstraint(int geoId1, int geoId2) return -1; } -int Sketch::addTangentLineAtBSplineKnotConstraint(int checkedlinegeoId, int checkedbsplinegeoId, int checkedknotgeoid) +int Sketch::addTangentLineAtBSplineKnotConstraint(int checkedlinegeoId, int checkedbsplinegeoId, + int checkedknotgeoid) { - GCS::BSpline &b = BSplines[Geoms[checkedbsplinegeoId].index]; - GCS::Line &l = Lines[Geoms[checkedlinegeoId].index]; + GCS::BSpline& b = BSplines[Geoms[checkedbsplinegeoId].index]; + GCS::Line& l = Lines[Geoms[checkedlinegeoId].index]; size_t knotindex = b.knots.size(); - auto knotIt = std::find(b.knotpointGeoids.begin(), - b.knotpointGeoids.end(), checkedknotgeoid); + auto knotIt = std::find(b.knotpointGeoids.begin(), b.knotpointGeoids.end(), checkedknotgeoid); knotindex = std::distance(b.knotpointGeoids.begin(), knotIt); - if (knotindex >= b.knots.size()){ + if (knotindex >= b.knots.size()) { Base::Console().Error("addConstraint: Knot index out-of-range!\n"); return -1; } if (b.mult[knotindex] >= b.degree) { - if (b.periodic || (knotindex > 0 && knotindex < (b.knots.size()-1))) { - Base::Console().Error("addTangentLineAtBSplineKnotConstraint: cannot set constraint when B-spline slope is discontinuous at knot!\n"); + if (b.periodic || (knotindex > 0 && knotindex < (b.knots.size() - 1))) { + Base::Console().Error("addTangentLineAtBSplineKnotConstraint: cannot set constraint " + "when B-spline slope is discontinuous at knot!\n"); return -1; } else { @@ -2523,41 +2849,48 @@ int Sketch::addTangentLineAtBSplineKnotConstraint(int checkedlinegeoId, int chec // nullptr, Tangent, true); // For now we just throw an error. - Base::Console().Error("addTangentLineAtBSplineKnotConstraint: This method cannot set tangent constraint at end knots of a B-spline. Please constrain the start/end points instead.\n"); + Base::Console().Error( + "addTangentLineAtBSplineKnotConstraint: This method cannot set tangent constraint " + "at end knots of a B-spline. Please constrain the start/end points instead.\n"); return -1; } } else { - int tag = Sketch::addPointOnObjectConstraint(checkedknotgeoid, PointPos::start, checkedlinegeoId);//increases ConstraintsCounter + // increases ConstraintsCounter + int tag = + Sketch::addPointOnObjectConstraint(checkedknotgeoid, PointPos::start, checkedlinegeoId); GCSsys.addConstraintTangentAtBSplineKnot(b, l, knotindex, tag); return ConstraintsCounter; } } -int Sketch::addTangentLineEndpointAtBSplineKnotConstraint(int checkedlinegeoId, PointPos endpointPos, int checkedbsplinegeoId, int checkedknotgeoid) +int Sketch::addTangentLineEndpointAtBSplineKnotConstraint(int checkedlinegeoId, + PointPos endpointPos, + int checkedbsplinegeoId, + int checkedknotgeoid) { - GCS::BSpline &b = BSplines[Geoms[checkedbsplinegeoId].index]; - GCS::Line &l = Lines[Geoms[checkedlinegeoId].index]; + GCS::BSpline& b = BSplines[Geoms[checkedbsplinegeoId].index]; + GCS::Line& l = Lines[Geoms[checkedlinegeoId].index]; auto pointId = getPointId(checkedlinegeoId, endpointPos); auto pointIdKnot = getPointId(checkedknotgeoid, PointPos::start); - GCS::Point &p = Points[pointId]; - GCS::Point &pk = Points[pointIdKnot]; + GCS::Point& p = Points[pointId]; + GCS::Point& pk = Points[pointIdKnot]; size_t knotindex = b.knots.size(); - auto knotIt = std::find(b.knotpointGeoids.begin(), - b.knotpointGeoids.end(), checkedknotgeoid); + auto knotIt = std::find(b.knotpointGeoids.begin(), b.knotpointGeoids.end(), checkedknotgeoid); knotindex = std::distance(b.knotpointGeoids.begin(), knotIt); - if (knotindex >= b.knots.size()){ + if (knotindex >= b.knots.size()) { Base::Console().Error("addConstraint: Knot index out-of-range!\n"); return -1; } if (b.mult[knotindex] >= b.degree) { - if (b.periodic || (knotindex > 0 && knotindex < (b.knots.size()-1))) { - Base::Console().Error("addTangentLineEndpointAtBSplineKnotConstraint: cannot set constraint when B-spline slope is discontinuous at knot!\n"); + if (b.periodic || (knotindex > 0 && knotindex < (b.knots.size() - 1))) { + Base::Console().Error("addTangentLineEndpointAtBSplineKnotConstraint: cannot set " + "constraint when B-spline slope is discontinuous at knot!\n"); return -1; } else { @@ -2569,7 +2902,9 @@ int Sketch::addTangentLineEndpointAtBSplineKnotConstraint(int checkedlinegeoId, // nullptr, Tangent, true); // For now we just throw an error. - Base::Console().Error("addTangentLineEndpointAtBSplineKnotConstraint: This method cannot set tangent constraint at end knots of a B-spline. Please constrain the start/end points instead.\n"); + Base::Console().Error("addTangentLineEndpointAtBSplineKnotConstraint: This method " + "cannot set tangent constraint at end knots of a B-spline. " + "Please constrain the start/end points instead.\n"); return -1; } } @@ -2581,129 +2916,138 @@ int Sketch::addTangentLineEndpointAtBSplineKnotConstraint(int checkedlinegeoId, } } -//This function handles any type of tangent, perpendicular and angle -// constraint that involves a point. -// i.e. endpoint-to-curve, endpoint-to-endpoint and tangent-via-point -//geoid1, geoid2 and geoid3 as in the constraint object. -//For perp-ty and tangency, angle is used to lock the direction. -//angle==0 - autodetect direction. +pi/2, -pi/2 - specific direction. -int Sketch::addAngleAtPointConstraint( - int geoId1, PointPos pos1, - int geoId2, PointPos pos2, - int geoId3, PointPos pos3, - double * value, - ConstraintType cTyp, bool driving) +// This function handles any type of tangent, perpendicular and angle +// constraint that involves a point. +// i.e. endpoint-to-curve, endpoint-to-endpoint and tangent-via-point +// geoid1, geoid2 and geoid3 as in the constraint object. +// For perp-ty and tangency, angle is used to lock the direction. +// angle==0 - autodetect direction. +pi/2, -pi/2 - specific direction. +int Sketch::addAngleAtPointConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, + int geoId3, PointPos pos3, double* value, ConstraintType cTyp, + bool driving) { - if(!(cTyp == Angle || cTyp == Tangent || cTyp == Perpendicular)) { - //assert(0);//none of the three types. Why are we here?? + if (!(cTyp == Angle || cTyp == Tangent || cTyp == Perpendicular)) { + // assert(0);//none of the three types. Why are we here?? return -1; } - bool avp = geoId3!=GeoEnum::GeoUndef; //is angle-via-point? - bool e2c = pos2 == PointPos::none && pos1 != PointPos::none;//is endpoint-to-curve? - bool e2e = pos2 != PointPos::none && pos1 != PointPos::none;//is endpoint-to-endpoint? + bool avp = geoId3 != GeoEnum::GeoUndef; // is angle-via-point? + bool e2c = pos2 == PointPos::none && pos1 != PointPos::none;// is endpoint-to-curve? + bool e2e = pos2 != PointPos::none && pos1 != PointPos::none;// is endpoint-to-endpoint? - if (!( avp || e2c || e2e )) { - //assert(0);//none of the three types. Why are we here?? + if (!(avp || e2c || e2e)) { + // assert(0);//none of the three types. Why are we here?? return -1; } geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); - if(avp) + if (avp) geoId3 = checkGeoId(geoId3); - if (Geoms[geoId1].type == Point || - Geoms[geoId2].type == Point){ + if (Geoms[geoId1].type == Point || Geoms[geoId2].type == Point) { Base::Console().Error("addAngleAtPointConstraint: one of the curves is a point!\n"); return -1; } - GCS::Curve* crv1 =getGCSCurveByGeoId(geoId1); - GCS::Curve* crv2 =getGCSCurveByGeoId(geoId2); + GCS::Curve* crv1 = getGCSCurveByGeoId(geoId1); + GCS::Curve* crv2 = getGCSCurveByGeoId(geoId2); if (!crv1 || !crv2) { Base::Console().Error("addAngleAtPointConstraint: getGCSCurveByGeoId returned NULL!\n"); return -1; } int pointId = -1; - if(avp) + if (avp) pointId = getPointId(geoId3, pos3); else if (e2e || e2c) pointId = getPointId(geoId1, pos1); - if (pointId < 0 || pointId >= int(Points.size())){ + if (pointId < 0 || pointId >= int(Points.size())) { Base::Console().Error("addAngleAtPointConstraint: point index out of range.\n"); return -1; } - GCS::Point &p = Points[pointId]; + GCS::Point& p = Points[pointId]; GCS::Point* p2 = nullptr; - if(e2e){//we need second point + if (e2e) {// we need second point int pointId = getPointId(geoId2, pos2); - if (pointId < 0 || pointId >= int(Points.size())){ + if (pointId < 0 || pointId >= int(Points.size())) { Base::Console().Error("addAngleAtPointConstraint: point index out of range.\n"); return -1; } p2 = &(Points[pointId]); } - double *angle = value; + double* angle = value; - //For tangency/perpendicularity, we don't just copy the angle. - //The angle stored for tangency/perpendicularity is offset, so that the options - // are -Pi/2 and Pi/2. If value is 0 - this is an indicator of an old sketch. - // Use autodetect then. - //The same functionality is implemented in SketchObject.cpp, where - // it is used to permanently lock down the autodecision. - if (cTyp != Angle) - { - //The same functionality is implemented in SketchObject.cpp, where - // it is used to permanently lock down the autodecision. - double angleOffset = 0.0;//the difference between the datum value and the actual angle to apply. (datum=angle+offset) - double angleDesire = 0.0;//the desired angle value (and we are to decide if 180* should be added to it) - if (cTyp == Tangent) {angleOffset = -M_PI/2; angleDesire = 0.0;} - if (cTyp == Perpendicular) {angleOffset = 0; angleDesire = M_PI/2;} + // For tangency/perpendicularity, we don't just copy the angle. + // The angle stored for tangency/perpendicularity is offset, so that the options + // are -Pi/2 and Pi/2. If value is 0 - this is an indicator of an old sketch. + // Use autodetect then. + // The same functionality is implemented in SketchObject.cpp, where + // it is used to permanently lock down the autodecision. + if (cTyp != Angle) { + // The same functionality is implemented in SketchObject.cpp, where + // it is used to permanently lock down the autodecision. + // the difference between the datum value and the actual angle to apply. + // (datum=angle+offset) + double angleOffset = 0.0; + // the desired angle value (and we are to decide if 180* should be added to it) + double angleDesire = 0.0; + if (cTyp == Tangent) { + angleOffset = -M_PI / 2; + angleDesire = 0.0; + } + if (cTyp == Perpendicular) { + angleOffset = 0; + angleDesire = M_PI / 2; + } - if (*value==0.0) {//autodetect tangency internal/external (and same for perpendicularity) + if (*value == 0.0) {// autodetect tangency internal/external (and same for perpendicularity) double angleErr = GCSsys.calculateAngleViaPoint(*crv1, *crv2, p) - angleDesire; - //bring angleErr to -pi..pi - if (angleErr > M_PI) angleErr -= M_PI*2; - if (angleErr < -M_PI) angleErr += M_PI*2; + // bring angleErr to -pi..pi + if (angleErr > M_PI) + angleErr -= M_PI * 2; + if (angleErr < -M_PI) + angleErr += M_PI * 2; - //the autodetector - if(fabs(angleErr) > M_PI/2 ) + // the autodetector + if (fabs(angleErr) > M_PI / 2) angleDesire += M_PI; *angle = angleDesire; } else - *angle = *value-angleOffset; + *angle = *value - angleOffset; } int tag = -1; - if(e2c) - tag = Sketch::addPointOnObjectConstraint(geoId1, pos1, geoId2, driving);//increases ConstraintsCounter - if (e2e){ + if (e2c) { + // increases ConstraintsCounter + tag = Sketch::addPointOnObjectConstraint(geoId1, pos1, geoId2, driving); + } + if (e2e) { tag = ++ConstraintsCounter; GCSsys.addConstraintP2PCoincident(p, *p2, tag, driving); } - if(avp) + if (avp) { tag = ++ConstraintsCounter; + } GCSsys.addConstraintAngleViaPoint(*crv1, *crv2, p, angle, tag, driving); return ConstraintsCounter; } // line length constraint -int Sketch::addDistanceConstraint(int geoId, double * value, bool driving) +int Sketch::addDistanceConstraint(int geoId, double* value, bool driving) { geoId = checkGeoId(geoId); if (Geoms[geoId].type != Line) return -1; - GCS::Line &l = Lines[Geoms[geoId].index]; + GCS::Line& l = Lines[Geoms[geoId].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintP2PDistance(l.p1, l.p2, value, tag, driving); @@ -2711,7 +3055,8 @@ int Sketch::addDistanceConstraint(int geoId, double * value, bool driving) } // point to line distance constraint -int Sketch::addDistanceConstraint(int geoId1, PointPos pos1, int geoId2, double * value, bool driving) +int Sketch::addDistanceConstraint(int geoId1, PointPos pos1, int geoId2, double* value, + bool driving) { geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); @@ -2722,8 +3067,8 @@ int Sketch::addDistanceConstraint(int geoId1, PointPos pos1, int geoId2, double return -1; if (pointId1 >= 0 && pointId1 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; - GCS::Line &l2 = Lines[Geoms[geoId2].index]; + GCS::Point& p1 = Points[pointId1]; + GCS::Line& l2 = Lines[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintP2LDistance(p1, l2, value, tag, driving); @@ -2733,7 +3078,8 @@ int Sketch::addDistanceConstraint(int geoId1, PointPos pos1, int geoId2, double } // point to point distance constraint -int Sketch::addDistanceConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, double * value, bool driving) +int Sketch::addDistanceConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, + double* value, bool driving) { geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); @@ -2741,10 +3087,10 @@ int Sketch::addDistanceConstraint(int geoId1, PointPos pos1, int geoId2, PointPo int pointId1 = getPointId(geoId1, pos1); int pointId2 = getPointId(geoId2, pos2); - if (pointId1 >= 0 && pointId1 < int(Points.size()) && - pointId2 >= 0 && pointId2 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; - GCS::Point &p2 = Points[pointId2]; + if (pointId1 >= 0 && pointId1 < int(Points.size()) && pointId2 >= 0 + && pointId2 < int(Points.size())) { + GCS::Point& p1 = Points[pointId1]; + GCS::Point& p2 = Points[pointId2]; int tag = ++ConstraintsCounter; GCSsys.addConstraintP2PDistance(p1, p2, value, tag, driving); @@ -2754,18 +3100,19 @@ int Sketch::addDistanceConstraint(int geoId1, PointPos pos1, int geoId2, PointPo } // circle-(circle or line) distance constraint -int Sketch::addDistanceConstraint(int geoId1, int geoId2, double * value, bool driving) +int Sketch::addDistanceConstraint(int geoId1, int geoId2, double* value, bool driving) { if (Geoms[geoId1].type == Circle) { if (Geoms[geoId2].type == Circle) { - GCS::Circle &c1 = Circles[Geoms[geoId1].index]; - GCS::Circle &c2 = Circles[Geoms[geoId2].index]; + GCS::Circle& c1 = Circles[Geoms[geoId1].index]; + GCS::Circle& c2 = Circles[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintC2CDistance(c1, c2, value, tag, driving); return ConstraintsCounter; - } else if (Geoms[geoId2].type == Line) { - GCS::Circle &c = Circles[Geoms[geoId1].index]; - GCS::Line &l = Lines[Geoms[geoId2].index]; + } + else if (Geoms[geoId2].type == Line) { + GCS::Circle& c = Circles[Geoms[geoId1].index]; + GCS::Line& l = Lines[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintC2LDistance(c, l, value, tag, driving); return ConstraintsCounter; @@ -2775,19 +3122,18 @@ int Sketch::addDistanceConstraint(int geoId1, int geoId2, double * value, bool d } - -int Sketch::addRadiusConstraint(int geoId, double * value, bool driving) +int Sketch::addRadiusConstraint(int geoId, double* value, bool driving) { geoId = checkGeoId(geoId); if (Geoms[geoId].type == Circle) { - GCS::Circle &c = Circles[Geoms[geoId].index]; + GCS::Circle& c = Circles[Geoms[geoId].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintCircleRadius(c, value, tag, driving); return ConstraintsCounter; } else if (Geoms[geoId].type == Arc) { - GCS::Arc &a = Arcs[Geoms[geoId].index]; + GCS::Arc& a = Arcs[Geoms[geoId].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintArcRadius(a, value, tag, driving); return ConstraintsCounter; @@ -2795,18 +3141,18 @@ int Sketch::addRadiusConstraint(int geoId, double * value, bool driving) return -1; } -int Sketch::addDiameterConstraint(int geoId, double * value, bool driving) +int Sketch::addDiameterConstraint(int geoId, double* value, bool driving) { geoId = checkGeoId(geoId); if (Geoms[geoId].type == Circle) { - GCS::Circle &c = Circles[Geoms[geoId].index]; + GCS::Circle& c = Circles[Geoms[geoId].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintCircleDiameter(c, value, tag, driving); return ConstraintsCounter; } else if (Geoms[geoId].type == Arc) { - GCS::Arc &a = Arcs[Geoms[geoId].index]; + GCS::Arc& a = Arcs[Geoms[geoId].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintArcDiameter(a, value, tag, driving); return ConstraintsCounter; @@ -2815,19 +3161,19 @@ int Sketch::addDiameterConstraint(int geoId, double * value, bool driving) } // line orientation angle constraint -int Sketch::addAngleConstraint(int geoId, double * value, bool driving) +int Sketch::addAngleConstraint(int geoId, double* value, bool driving) { geoId = checkGeoId(geoId); if (Geoms[geoId].type == Line) { - GCS::Line &l = Lines[Geoms[geoId].index]; + GCS::Line& l = Lines[Geoms[geoId].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintP2PAngle(l.p1, l.p2, value, tag, driving); return ConstraintsCounter; } else if (Geoms[geoId].type == Arc) { - GCS::Arc &a = Arcs[Geoms[geoId].index]; + GCS::Arc& a = Arcs[Geoms[geoId].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintL2LAngle(a.center, a.start, a.center, a.end, value, tag, driving); @@ -2837,17 +3183,16 @@ int Sketch::addAngleConstraint(int geoId, double * value, bool driving) } // line to line angle constraint -int Sketch::addAngleConstraint(int geoId1, int geoId2, double * value, bool driving) +int Sketch::addAngleConstraint(int geoId1, int geoId2, double* value, bool driving) { geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); - if (Geoms[geoId1].type != Line || - Geoms[geoId2].type != Line) + if (Geoms[geoId1].type != Line || Geoms[geoId2].type != Line) return -1; - GCS::Line &l1 = Lines[Geoms[geoId1].index]; - GCS::Line &l2 = Lines[Geoms[geoId2].index]; + GCS::Line& l1 = Lines[Geoms[geoId1].index]; + GCS::Line& l2 = Lines[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintL2LAngle(l1, l2, value, tag, driving); @@ -2855,16 +3200,16 @@ int Sketch::addAngleConstraint(int geoId1, int geoId2, double * value, bool driv } // line to line angle constraint (with explicitly given start points) -int Sketch::addAngleConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, double * value, bool driving) +int Sketch::addAngleConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, double* value, + bool driving) { geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); - if (Geoms[geoId1].type != Line || - Geoms[geoId2].type != Line) + if (Geoms[geoId1].type != Line || Geoms[geoId2].type != Line) return -1; - GCS::Point *l1p1=nullptr, *l1p2=nullptr; + GCS::Point *l1p1 = nullptr, *l1p2 = nullptr; if (pos1 == PointPos::start) { l1p1 = &Points[Geoms[geoId1].startPointId]; l1p2 = &Points[Geoms[geoId1].endPointId]; @@ -2874,7 +3219,7 @@ int Sketch::addAngleConstraint(int geoId1, PointPos pos1, int geoId2, PointPos p l1p2 = &Points[Geoms[geoId1].startPointId]; } - GCS::Point *l2p1=nullptr, *l2p2=nullptr; + GCS::Point *l2p1 = nullptr, *l2p2 = nullptr; if (pos2 == PointPos::start) { l2p1 = &Points[Geoms[geoId2].startPointId]; l2p2 = &Points[Geoms[geoId2].endPointId]; @@ -2898,10 +3243,9 @@ int Sketch::addEqualConstraint(int geoId1, int geoId2) geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); - if (Geoms[geoId1].type == Line && - Geoms[geoId2].type == Line) { - GCS::Line &l1 = Lines[Geoms[geoId1].index]; - GCS::Line &l2 = Lines[Geoms[geoId2].index]; + if (Geoms[geoId1].type == Line && Geoms[geoId2].type == Line) { + GCS::Line& l1 = Lines[Geoms[geoId1].index]; + GCS::Line& l2 = Lines[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintEqualLength(l1, l2, tag); @@ -2910,8 +3254,8 @@ int Sketch::addEqualConstraint(int geoId1, int geoId2) if (Geoms[geoId2].type == Circle) { if (Geoms[geoId1].type == Circle) { - GCS::Circle &c1 = Circles[Geoms[geoId1].index]; - GCS::Circle &c2 = Circles[Geoms[geoId2].index]; + GCS::Circle& c1 = Circles[Geoms[geoId1].index]; + GCS::Circle& c2 = Circles[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintEqualRadius(c1, c2, tag); return ConstraintsCounter; @@ -2922,8 +3266,8 @@ int Sketch::addEqualConstraint(int geoId1, int geoId2) if (Geoms[geoId2].type == Ellipse) { if (Geoms[geoId1].type == Ellipse) { - GCS::Ellipse &e1 = Ellipses[Geoms[geoId1].index]; - GCS::Ellipse &e2 = Ellipses[Geoms[geoId2].index]; + GCS::Ellipse& e1 = Ellipses[Geoms[geoId1].index]; + GCS::Ellipse& e2 = Ellipses[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintEqualRadii(e1, e2, tag); return ConstraintsCounter; @@ -2933,19 +3277,18 @@ int Sketch::addEqualConstraint(int geoId1, int geoId2) } if (Geoms[geoId1].type == Circle) { - GCS::Circle &c1 = Circles[Geoms[geoId1].index]; + GCS::Circle& c1 = Circles[Geoms[geoId1].index]; if (Geoms[geoId2].type == Arc) { - GCS::Arc &a2 = Arcs[Geoms[geoId2].index]; + GCS::Arc& a2 = Arcs[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintEqualRadius(c1, a2, tag); return ConstraintsCounter; } } - if (Geoms[geoId1].type == Arc && - Geoms[geoId2].type == Arc) { - GCS::Arc &a1 = Arcs[Geoms[geoId1].index]; - GCS::Arc &a2 = Arcs[Geoms[geoId2].index]; + if (Geoms[geoId1].type == Arc && Geoms[geoId2].type == Arc) { + GCS::Arc& a1 = Arcs[Geoms[geoId1].index]; + GCS::Arc& a2 = Arcs[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintEqualRadius(a1, a2, tag); return ConstraintsCounter; @@ -2953,8 +3296,8 @@ int Sketch::addEqualConstraint(int geoId1, int geoId2) if (Geoms[geoId2].type == ArcOfEllipse) { if (Geoms[geoId1].type == ArcOfEllipse) { - GCS::ArcOfEllipse &a1 = ArcsOfEllipse[Geoms[geoId1].index]; - GCS::ArcOfEllipse &a2 = ArcsOfEllipse[Geoms[geoId2].index]; + GCS::ArcOfEllipse& a1 = ArcsOfEllipse[Geoms[geoId1].index]; + GCS::ArcOfEllipse& a2 = ArcsOfEllipse[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintEqualRadii(a1, a2, tag); return ConstraintsCounter; @@ -2963,8 +3306,8 @@ int Sketch::addEqualConstraint(int geoId1, int geoId2) if (Geoms[geoId2].type == ArcOfHyperbola) { if (Geoms[geoId1].type == ArcOfHyperbola) { - GCS::ArcOfHyperbola &a1 = ArcsOfHyperbola[Geoms[geoId1].index]; - GCS::ArcOfHyperbola &a2 = ArcsOfHyperbola[Geoms[geoId2].index]; + GCS::ArcOfHyperbola& a1 = ArcsOfHyperbola[Geoms[geoId1].index]; + GCS::ArcOfHyperbola& a2 = ArcsOfHyperbola[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintEqualRadii(a1, a2, tag); return ConstraintsCounter; @@ -2973,8 +3316,8 @@ int Sketch::addEqualConstraint(int geoId1, int geoId2) if (Geoms[geoId2].type == ArcOfParabola) { if (Geoms[geoId1].type == ArcOfParabola) { - GCS::ArcOfParabola &a1 = ArcsOfParabola[Geoms[geoId1].index]; - GCS::ArcOfParabola &a2 = ArcsOfParabola[Geoms[geoId2].index]; + GCS::ArcOfParabola& a1 = ArcsOfParabola[Geoms[geoId1].index]; + GCS::ArcOfParabola& a2 = ArcsOfParabola[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintEqualFocus(a1, a2, tag); return ConstraintsCounter; @@ -2982,9 +3325,9 @@ int Sketch::addEqualConstraint(int geoId1, int geoId2) } if (Geoms[geoId1].type == Ellipse) { - GCS::Ellipse &e1 = Ellipses[Geoms[geoId1].index]; + GCS::Ellipse& e1 = Ellipses[Geoms[geoId1].index]; if (Geoms[geoId2].type == ArcOfEllipse) { - GCS::ArcOfEllipse &a2 = ArcsOfEllipse[Geoms[geoId2].index]; + GCS::ArcOfEllipse& a2 = ArcsOfEllipse[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintEqualRadii(a2, e1, tag); return ConstraintsCounter; @@ -2992,7 +3335,8 @@ int Sketch::addEqualConstraint(int geoId1, int geoId2) } Base::Console().Warning("Equality constraints between %s and %s are not supported.\n", - nameByType(Geoms[geoId1].type), nameByType(Geoms[geoId2].type)); + nameByType(Geoms[geoId1].type), + nameByType(Geoms[geoId2].type)); return -1; } @@ -3005,46 +3349,46 @@ int Sketch::addPointOnObjectConstraint(int geoId1, PointPos pos1, int geoId2, bo int pointId1 = getPointId(geoId1, pos1); if (pointId1 >= 0 && pointId1 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; + GCS::Point& p1 = Points[pointId1]; if (Geoms[geoId2].type == Line) { - GCS::Line &l2 = Lines[Geoms[geoId2].index]; + GCS::Line& l2 = Lines[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintPointOnLine(p1, l2, tag, driving); return ConstraintsCounter; } else if (Geoms[geoId2].type == Arc) { - GCS::Arc &a = Arcs[Geoms[geoId2].index]; + GCS::Arc& a = Arcs[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintPointOnArc(p1, a, tag, driving); return ConstraintsCounter; } else if (Geoms[geoId2].type == Circle) { - GCS::Circle &c = Circles[Geoms[geoId2].index]; + GCS::Circle& c = Circles[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintPointOnCircle(p1, c, tag, driving); return ConstraintsCounter; } else if (Geoms[geoId2].type == Ellipse) { - GCS::Ellipse &e = Ellipses[Geoms[geoId2].index]; + GCS::Ellipse& e = Ellipses[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintPointOnEllipse(p1, e, tag, driving); return ConstraintsCounter; } else if (Geoms[geoId2].type == ArcOfEllipse) { - GCS::ArcOfEllipse &a = ArcsOfEllipse[Geoms[geoId2].index]; + GCS::ArcOfEllipse& a = ArcsOfEllipse[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintPointOnEllipse(p1, a, tag, driving); return ConstraintsCounter; } else if (Geoms[geoId2].type == ArcOfHyperbola) { - GCS::ArcOfHyperbola &a = ArcsOfHyperbola[Geoms[geoId2].index]; + GCS::ArcOfHyperbola& a = ArcsOfHyperbola[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintPointOnHyperbolicArc(p1, a, tag, driving); return ConstraintsCounter; } else if (Geoms[geoId2].type == ArcOfParabola) { - GCS::ArcOfParabola &a = ArcsOfParabola[Geoms[geoId2].index]; + GCS::ArcOfParabola& a = ArcsOfParabola[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintPointOnParabolicArc(p1, a, tag, driving); return ConstraintsCounter; @@ -3053,7 +3397,8 @@ int Sketch::addPointOnObjectConstraint(int geoId1, PointPos pos1, int geoId2, bo return -1; } -int Sketch::addPointOnObjectConstraint(int geoId1, PointPos pos1, int geoId2, double* pointparam, bool driving) +int Sketch::addPointOnObjectConstraint(int geoId1, PointPos pos1, int geoId2, double* pointparam, + bool driving) { geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); @@ -3061,10 +3406,10 @@ int Sketch::addPointOnObjectConstraint(int geoId1, PointPos pos1, int geoId2, do int pointId1 = getPointId(geoId1, pos1); if (pointId1 >= 0 && pointId1 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; + GCS::Point& p1 = Points[pointId1]; if (Geoms[geoId2].type == BSpline) { - GCS::BSpline &b = BSplines[Geoms[geoId2].index]; + GCS::BSpline& b = BSplines[Geoms[geoId2].index]; int tag = ++ConstraintsCounter; auto partBsp = static_cast(Geoms[geoId2].geo); double uNear; @@ -3091,11 +3436,11 @@ int Sketch::addSymmetricConstraint(int geoId1, PointPos pos1, int geoId2, PointP int pointId1 = getPointId(geoId1, pos1); int pointId2 = getPointId(geoId2, pos2); - if (pointId1 >= 0 && pointId1 < int(Points.size()) && - pointId2 >= 0 && pointId2 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; - GCS::Point &p2 = Points[pointId2]; - GCS::Line &l = Lines[Geoms[geoId3].index]; + if (pointId1 >= 0 && pointId1 < int(Points.size()) && pointId2 >= 0 + && pointId2 < int(Points.size())) { + GCS::Point& p1 = Points[pointId1]; + GCS::Point& p2 = Points[pointId2]; + GCS::Line& l = Lines[Geoms[geoId3].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintP2PSymmetric(p1, p2, l, tag); return ConstraintsCounter; @@ -3103,8 +3448,8 @@ int Sketch::addSymmetricConstraint(int geoId1, PointPos pos1, int geoId2, PointP return -1; } -int Sketch::addSymmetricConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, - int geoId3, PointPos pos3) +int Sketch::addSymmetricConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, int geoId3, + PointPos pos3) { geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); @@ -3114,12 +3459,11 @@ int Sketch::addSymmetricConstraint(int geoId1, PointPos pos1, int geoId2, PointP int pointId2 = getPointId(geoId2, pos2); int pointId3 = getPointId(geoId3, pos3); - if (pointId1 >= 0 && pointId1 < int(Points.size()) && - pointId2 >= 0 && pointId2 < int(Points.size()) && - pointId3 >= 0 && pointId3 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; - GCS::Point &p2 = Points[pointId2]; - GCS::Point &p = Points[pointId3]; + if (pointId1 >= 0 && pointId1 < int(Points.size()) && pointId2 >= 0 + && pointId2 < int(Points.size()) && pointId3 >= 0 && pointId3 < int(Points.size())) { + GCS::Point& p1 = Points[pointId1]; + GCS::Point& p2 = Points[pointId2]; + GCS::Point& p = Points[pointId3]; int tag = ++ConstraintsCounter; GCSsys.addConstraintP2PSymmetric(p1, p2, p, tag); return ConstraintsCounter; @@ -3127,28 +3471,22 @@ int Sketch::addSymmetricConstraint(int geoId1, PointPos pos1, int geoId2, PointP return -1; } -int Sketch::addSnellsLawConstraint(int geoIdRay1, PointPos posRay1, - int geoIdRay2, PointPos posRay2, - int geoIdBnd, - double * value, - double * secondvalue, - bool driving - ) +int Sketch::addSnellsLawConstraint(int geoIdRay1, PointPos posRay1, int geoIdRay2, PointPos posRay2, + int geoIdBnd, double* value, double* secondvalue, bool driving) { geoIdRay1 = checkGeoId(geoIdRay1); geoIdRay2 = checkGeoId(geoIdRay2); geoIdBnd = checkGeoId(geoIdBnd); - if (Geoms[geoIdRay1].type == Point || - Geoms[geoIdRay2].type == Point){ + if (Geoms[geoIdRay1].type == Point || Geoms[geoIdRay2].type == Point) { Base::Console().Error("addSnellsLawConstraint: point is not a curve. Not applicable!\n"); return -1; } - GCS::Curve* ray1 =getGCSCurveByGeoId(geoIdRay1); - GCS::Curve* ray2 =getGCSCurveByGeoId(geoIdRay2); - GCS::Curve* boundary =getGCSCurveByGeoId(geoIdBnd); + GCS::Curve* ray1 = getGCSCurveByGeoId(geoIdRay1); + GCS::Curve* ray2 = getGCSCurveByGeoId(geoIdRay2); + GCS::Curve* boundary = getGCSCurveByGeoId(geoIdBnd); if (!ray1 || !ray2 || !boundary) { Base::Console().Error("addSnellsLawConstraint: getGCSCurveByGeoId returned NULL!\n"); return -1; @@ -3156,38 +3494,44 @@ int Sketch::addSnellsLawConstraint(int geoIdRay1, PointPos posRay1, int pointId1 = getPointId(geoIdRay1, posRay1); int pointId2 = getPointId(geoIdRay2, posRay2); - if ( pointId1 < 0 || pointId1 >= int(Points.size()) || - pointId2 < 0 || pointId2 >= int(Points.size()) ){ + if (pointId1 < 0 || pointId1 >= int(Points.size()) || pointId2 < 0 + || pointId2 >= int(Points.size())) { Base::Console().Error("addSnellsLawConstraint: point index out of range.\n"); return -1; } - GCS::Point &p1 = Points[pointId1]; + GCS::Point& p1 = Points[pointId1]; // add the parameters (refractive indexes) // n1 uses the place hold by n2divn1, so that is retrievable in updateNonDrivingConstraints - double *n1 = value; - double *n2 = secondvalue; + double* n1 = value; + double* n2 = secondvalue; - double n2divn1=*value; + double n2divn1 = *value; - if ( fabs(n2divn1) >= 1.0 ){ + if (fabs(n2divn1) >= 1.0) { *n2 = n2divn1; *n1 = 1.0; } else { *n2 = 1.0; - *n1 = 1/n2divn1; + *n1 = 1 / n2divn1; } int tag = -1; - //tag = Sketch::addPointOnObjectConstraint(geoIdRay1, posRay1, geoIdBnd);//increases ConstraintsCounter + // increases ConstraintsCounter + // tag = Sketch::addPointOnObjectConstraint(geoIdRay1, posRay1, geoIdBnd); tag = ++ConstraintsCounter; - //GCSsys.addConstraintP2PCoincident(p1, p2, tag); - GCSsys.addConstraintSnellsLaw(*ray1, *ray2, - *boundary, p1, - n1, n2, - posRay1 == PointPos::start, posRay2 == PointPos::end, - tag, driving); + // GCSsys.addConstraintP2PCoincident(p1, p2, tag); + GCSsys.addConstraintSnellsLaw(*ray1, + *ray2, + *boundary, + p1, + n1, + n2, + posRay1 == PointPos::start, + posRay2 == PointPos::end, + tag, + driving); return ConstraintsCounter; } @@ -3207,13 +3551,13 @@ int Sketch::addInternalAlignmentEllipseMajorDiameter(int geoId1, int geoId2) int pointId1 = getPointId(geoId2, PointPos::start); int pointId2 = getPointId(geoId2, PointPos::end); - if (pointId1 >= 0 && pointId1 < int(Points.size()) && - pointId2 >= 0 && pointId2 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; - GCS::Point &p2 = Points[pointId2]; + if (pointId1 >= 0 && pointId1 < int(Points.size()) && pointId2 >= 0 + && pointId2 < int(Points.size())) { + GCS::Point& p1 = Points[pointId1]; + GCS::Point& p2 = Points[pointId2]; - if(Geoms[geoId1].type == Ellipse) { - GCS::Ellipse &e1 = Ellipses[Geoms[geoId1].index]; + if (Geoms[geoId1].type == Ellipse) { + GCS::Ellipse& e1 = Ellipses[Geoms[geoId1].index]; // constraints // 1. start point with ellipse -a @@ -3221,10 +3565,9 @@ int Sketch::addInternalAlignmentEllipseMajorDiameter(int geoId1, int geoId2) int tag = ++ConstraintsCounter; GCSsys.addConstraintInternalAlignmentEllipseMajorDiameter(e1, p1, p2, tag); return ConstraintsCounter; - } else { - GCS::ArcOfEllipse &a1 = ArcsOfEllipse[Geoms[geoId1].index]; + GCS::ArcOfEllipse& a1 = ArcsOfEllipse[Geoms[geoId1].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintInternalAlignmentEllipseMajorDiameter(a1, p1, p2, tag); @@ -3249,13 +3592,13 @@ int Sketch::addInternalAlignmentEllipseMinorDiameter(int geoId1, int geoId2) int pointId1 = getPointId(geoId2, PointPos::start); int pointId2 = getPointId(geoId2, PointPos::end); - if (pointId1 >= 0 && pointId1 < int(Points.size()) && - pointId2 >= 0 && pointId2 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; - GCS::Point &p2 = Points[pointId2]; + if (pointId1 >= 0 && pointId1 < int(Points.size()) && pointId2 >= 0 + && pointId2 < int(Points.size())) { + GCS::Point& p1 = Points[pointId1]; + GCS::Point& p2 = Points[pointId2]; - if(Geoms[geoId1].type == Ellipse) { - GCS::Ellipse &e1 = Ellipses[Geoms[geoId1].index]; + if (Geoms[geoId1].type == Ellipse) { + GCS::Ellipse& e1 = Ellipses[Geoms[geoId1].index]; // constraints // 1. start point with ellipse -a @@ -3265,7 +3608,7 @@ int Sketch::addInternalAlignmentEllipseMinorDiameter(int geoId1, int geoId2) return ConstraintsCounter; } else { - GCS::ArcOfEllipse &a1 = ArcsOfEllipse[Geoms[geoId1].index]; + GCS::ArcOfEllipse& a1 = ArcsOfEllipse[Geoms[geoId1].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintInternalAlignmentEllipseMinorDiameter(a1, p1, p2, tag); @@ -3290,10 +3633,10 @@ int Sketch::addInternalAlignmentEllipseFocus1(int geoId1, int geoId2) int pointId1 = getPointId(geoId2, PointPos::start); if (pointId1 >= 0 && pointId1 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; + GCS::Point& p1 = Points[pointId1]; - if(Geoms[geoId1].type == Ellipse) { - GCS::Ellipse &e1 = Ellipses[Geoms[geoId1].index]; + if (Geoms[geoId1].type == Ellipse) { + GCS::Ellipse& e1 = Ellipses[Geoms[geoId1].index]; // constraints // 1. start point with ellipse -a @@ -3303,7 +3646,7 @@ int Sketch::addInternalAlignmentEllipseFocus1(int geoId1, int geoId2) return ConstraintsCounter; } else { - GCS::ArcOfEllipse &a1 = ArcsOfEllipse[Geoms[geoId1].index]; + GCS::ArcOfEllipse& a1 = ArcsOfEllipse[Geoms[geoId1].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintInternalAlignmentEllipseFocus1(a1, p1, tag); @@ -3329,10 +3672,10 @@ int Sketch::addInternalAlignmentEllipseFocus2(int geoId1, int geoId2) int pointId1 = getPointId(geoId2, PointPos::start); if (pointId1 >= 0 && pointId1 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; + GCS::Point& p1 = Points[pointId1]; - if(Geoms[geoId1].type == Ellipse) { - GCS::Ellipse &e1 = Ellipses[Geoms[geoId1].index]; + if (Geoms[geoId1].type == Ellipse) { + GCS::Ellipse& e1 = Ellipses[Geoms[geoId1].index]; // constraints // 1. start point with ellipse -a @@ -3342,7 +3685,7 @@ int Sketch::addInternalAlignmentEllipseFocus2(int geoId1, int geoId2) return ConstraintsCounter; } else { - GCS::ArcOfEllipse &a1 = ArcsOfEllipse[Geoms[geoId1].index]; + GCS::ArcOfEllipse& a1 = ArcsOfEllipse[Geoms[geoId1].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintInternalAlignmentEllipseFocus2(a1, p1, tag); @@ -3368,13 +3711,13 @@ int Sketch::addInternalAlignmentHyperbolaMajorDiameter(int geoId1, int geoId2) int pointId1 = getPointId(geoId2, PointPos::start); int pointId2 = getPointId(geoId2, PointPos::end); - if (pointId1 >= 0 && pointId1 < int(Points.size()) && - pointId2 >= 0 && pointId2 < int(Points.size())) { + if (pointId1 >= 0 && pointId1 < int(Points.size()) && pointId2 >= 0 + && pointId2 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; - GCS::Point &p2 = Points[pointId2]; + GCS::Point& p1 = Points[pointId1]; + GCS::Point& p2 = Points[pointId2]; - GCS::ArcOfHyperbola &a1 = ArcsOfHyperbola[Geoms[geoId1].index]; + GCS::ArcOfHyperbola& a1 = ArcsOfHyperbola[Geoms[geoId1].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintInternalAlignmentHyperbolaMajorDiameter(a1, p1, p2, tag); @@ -3399,13 +3742,13 @@ int Sketch::addInternalAlignmentHyperbolaMinorDiameter(int geoId1, int geoId2) int pointId1 = getPointId(geoId2, PointPos::start); int pointId2 = getPointId(geoId2, PointPos::end); - if (pointId1 >= 0 && pointId1 < int(Points.size()) && - pointId2 >= 0 && pointId2 < int(Points.size())) { + if (pointId1 >= 0 && pointId1 < int(Points.size()) && pointId2 >= 0 + && pointId2 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; - GCS::Point &p2 = Points[pointId2]; + GCS::Point& p1 = Points[pointId1]; + GCS::Point& p2 = Points[pointId2]; - GCS::ArcOfHyperbola &a1 = ArcsOfHyperbola[Geoms[geoId1].index]; + GCS::ArcOfHyperbola& a1 = ArcsOfHyperbola[Geoms[geoId1].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintInternalAlignmentHyperbolaMinorDiameter(a1, p1, p2, tag); @@ -3430,9 +3773,9 @@ int Sketch::addInternalAlignmentHyperbolaFocus(int geoId1, int geoId2) int pointId1 = getPointId(geoId2, PointPos::start); if (pointId1 >= 0 && pointId1 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; + GCS::Point& p1 = Points[pointId1]; - GCS::ArcOfHyperbola &a1 = ArcsOfHyperbola[Geoms[geoId1].index]; + GCS::ArcOfHyperbola& a1 = ArcsOfHyperbola[Geoms[geoId1].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintInternalAlignmentHyperbolaFocus(a1, p1, tag); @@ -3456,9 +3799,9 @@ int Sketch::addInternalAlignmentParabolaFocus(int geoId1, int geoId2) int pointId1 = getPointId(geoId2, PointPos::start); if (pointId1 >= 0 && pointId1 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; + GCS::Point& p1 = Points[pointId1]; - GCS::ArcOfParabola &a1 = ArcsOfParabola[Geoms[geoId1].index]; + GCS::ArcOfParabola& a1 = ArcsOfParabola[Geoms[geoId1].index]; int tag = ++ConstraintsCounter; GCSsys.addConstraintInternalAlignmentParabolaFocus(a1, p1, tag); @@ -3482,16 +3825,16 @@ int Sketch::addInternalAlignmentParabolaFocalDistance(int geoId1, int geoId2) int pointId1 = getPointId(geoId2, PointPos::start); int pointId2 = getPointId(geoId2, PointPos::end); - if (pointId1 >= 0 && pointId1 < int(Points.size()) && - pointId2 >= 0 && pointId2 < int(Points.size())) { + if (pointId1 >= 0 && pointId1 < int(Points.size()) && pointId2 >= 0 + && pointId2 < int(Points.size())) { - GCS::Point &p1 = Points[pointId1]; - GCS::Point &p2 = Points[pointId2]; + GCS::Point& p1 = Points[pointId1]; + GCS::Point& p2 = Points[pointId2]; - GCS::ArcOfParabola &a1 = ArcsOfParabola[Geoms[geoId1].index]; + GCS::ArcOfParabola& a1 = ArcsOfParabola[Geoms[geoId1].index]; - auto & vertexpoint = a1.vertex; - auto & focuspoint = a1.focus1; + auto& vertexpoint = a1.vertex; + auto& focuspoint = a1.focus1; int tag = ++ConstraintsCounter; GCSsys.addConstraintP2PCoincident(p1, vertexpoint, tag); @@ -3520,9 +3863,9 @@ int Sketch::addInternalAlignmentBSplineControlPoint(int geoId1, int geoId2, int int pointId1 = getPointId(geoId2, PointPos::mid); if (pointId1 >= 0 && pointId1 < int(Points.size())) { - GCS::Circle &c = Circles[Geoms[geoId2].index]; + GCS::Circle& c = Circles[Geoms[geoId2].index]; - GCS::BSpline &b = BSplines[Geoms[geoId1].index]; + GCS::BSpline& b = BSplines[Geoms[geoId1].index]; assert(poleindex < static_cast(b.poles.size()) && poleindex >= 0); @@ -3548,8 +3891,8 @@ int Sketch::addInternalAlignmentKnotPoint(int geoId1, int geoId2, int knotindex) int pointId1 = getPointId(geoId2, PointPos::start); if (pointId1 >= 0 && pointId1 < int(Points.size())) { - GCS::Point &p = Points[pointId1]; - GCS::BSpline &b = BSplines[Geoms[geoId1].index]; + GCS::Point& p = Points[pointId1]; + GCS::BSpline& b = BSplines[Geoms[geoId1].index]; assert(knotindex < static_cast(b.knots.size()) && knotindex >= 0); @@ -3571,9 +3914,9 @@ double Sketch::calculateAngleViaPoint(int geoId1, int geoId2, double px, double p.x = &px; p.y = &py; - //check pointers - GCS::Curve* crv1 =getGCSCurveByGeoId(geoId1); - GCS::Curve* crv2 =getGCSCurveByGeoId(geoId2); + // check pointers + GCS::Curve* crv1 = getGCSCurveByGeoId(geoId1); + GCS::Curve* crv2 = getGCSCurveByGeoId(geoId2); if (!crv1 || !crv2) { throw Base::ValueError("calculateAngleViaPoint: getGCSCurveByGeoId returned NULL!"); } @@ -3589,7 +3932,7 @@ Base::Vector3d Sketch::calculateNormalAtPoint(int geoIdCurve, double px, double p.x = &px; p.y = &py; - //check pointers + // check pointers const GCS::Curve* crv = getGCSCurveByGeoId(geoIdCurve); if (!crv) { throw Base::ValueError("calculateNormalAtPoint: getGCSCurveByGeoId returned NULL!\n"); @@ -3597,64 +3940,60 @@ Base::Vector3d Sketch::calculateNormalAtPoint(int geoIdCurve, double px, double double tx = 0.0, ty = 0.0; GCSsys.calculateNormalAtPoint(*crv, p, tx, ty); - return Base::Vector3d(tx,ty,0.0); + return Base::Vector3d(tx, ty, 0.0); } bool Sketch::updateGeometry() { - int i=0; - for (std::vector::const_iterator it=Geoms.begin(); it != Geoms.end(); ++it, i++) { + int i = 0; + for (std::vector::const_iterator it = Geoms.begin(); it != Geoms.end(); ++it, i++) { try { if (it->type == Point) { - GeomPoint *point = static_cast(it->geo); + GeomPoint* point = static_cast(it->geo); auto pointf = GeometryFacade::getFacade(point); - point->setPoint(Vector3d(*Points[it->startPointId].x, - *Points[it->startPointId].y, - 0.0)); + point->setPoint( + Vector3d(*Points[it->startPointId].x, *Points[it->startPointId].y, 0.0)); } else if (it->type == Line) { - GeomLineSegment *lineSeg = static_cast(it->geo); - lineSeg->setPoints(Vector3d(*Lines[it->index].p1.x, - *Lines[it->index].p1.y, - 0.0), - Vector3d(*Lines[it->index].p2.x, - *Lines[it->index].p2.y, - 0.0) - ); + GeomLineSegment* lineSeg = static_cast(it->geo); + lineSeg->setPoints(Vector3d(*Lines[it->index].p1.x, *Lines[it->index].p1.y, 0.0), + Vector3d(*Lines[it->index].p2.x, *Lines[it->index].p2.y, 0.0)); } else if (it->type == Arc) { - GCS::Arc &myArc = Arcs[it->index]; - // the following 4 lines are redundant since these equations are already included in the arc constraints -// *myArc.start.x = *myArc.center.x + *myArc.rad * cos(*myArc.startAngle); -// *myArc.start.y = *myArc.center.y + *myArc.rad * sin(*myArc.startAngle); -// *myArc.end.x = *myArc.center.x + *myArc.rad * cos(*myArc.endAngle); -// *myArc.end.y = *myArc.center.y + *myArc.rad * sin(*myArc.endAngle); - GeomArcOfCircle *aoc = static_cast(it->geo); - aoc->setCenter(Vector3d(*Points[it->midPointId].x, - *Points[it->midPointId].y, - 0.0) - ); + GCS::Arc& myArc = Arcs[it->index]; + // the following 4 lines are redundant since these equations are already included in + // the arc constraints *myArc.start.x = *myArc.center.x + *myArc.rad * + // cos(*myArc.startAngle); *myArc.start.y = *myArc.center.y + *myArc.rad * + // sin(*myArc.startAngle); *myArc.end.x = *myArc.center.x + *myArc.rad * + // cos(*myArc.endAngle); *myArc.end.y = *myArc.center.y + *myArc.rad * + // sin(*myArc.endAngle); + GeomArcOfCircle* aoc = static_cast(it->geo); + aoc->setCenter(Vector3d(*Points[it->midPointId].x, *Points[it->midPointId].y, 0.0)); aoc->setRadius(*myArc.rad); aoc->setRange(*myArc.startAngle, *myArc.endAngle, /*emulateCCW=*/true); } else if (it->type == ArcOfEllipse) { - GCS::ArcOfEllipse &myArc = ArcsOfEllipse[it->index]; + GCS::ArcOfEllipse& myArc = ArcsOfEllipse[it->index]; - GeomArcOfEllipse *aoe = static_cast(it->geo); + GeomArcOfEllipse* aoe = static_cast(it->geo); - Base::Vector3d center = Vector3d(*Points[it->midPointId].x, *Points[it->midPointId].y, 0.0); + Base::Vector3d center = + Vector3d(*Points[it->midPointId].x, *Points[it->midPointId].y, 0.0); Base::Vector3d f1 = Vector3d(*myArc.focus1.x, *myArc.focus1.y, 0.0); double radmin = *myArc.radmin; - Base::Vector3d fd=f1-center; - double radmaj = sqrt(fd*fd+radmin*radmin); + Base::Vector3d fd = f1 - center; + double radmaj = sqrt(fd * fd + radmin * radmin); aoe->setCenter(center); - if ( radmaj >= aoe->getMinorRadius() ){//ensure that ellipse's major radius is always larger than minor raduis... may still cause problems with degenerates. + // ensure that ellipse's major radius is always larger than minor radius... may + // still cause problems with degenerates. + if (radmaj >= aoe->getMinorRadius()) { aoe->setMajorRadius(radmaj); aoe->setMinorRadius(radmin); - } else { + } + else { aoe->setMinorRadius(radmin); aoe->setMajorRadius(radmaj); } @@ -3662,51 +4001,56 @@ bool Sketch::updateGeometry() aoe->setRange(*myArc.startAngle, *myArc.endAngle, /*emulateCCW=*/true); } else if (it->type == Circle) { - GeomCircle *circ = static_cast(it->geo); - circ->setCenter(Vector3d(*Points[it->midPointId].x, - *Points[it->midPointId].y, - 0.0) - ); + GeomCircle* circ = static_cast(it->geo); + circ->setCenter( + Vector3d(*Points[it->midPointId].x, *Points[it->midPointId].y, 0.0)); circ->setRadius(*Circles[it->index].rad); } else if (it->type == Ellipse) { - GeomEllipse *ellipse = static_cast(it->geo); + GeomEllipse* ellipse = static_cast(it->geo); - Base::Vector3d center = Vector3d(*Points[it->midPointId].x, *Points[it->midPointId].y, 0.0); - Base::Vector3d f1 = Vector3d(*Ellipses[it->index].focus1.x, *Ellipses[it->index].focus1.y, 0.0); + Base::Vector3d center = + Vector3d(*Points[it->midPointId].x, *Points[it->midPointId].y, 0.0); + Base::Vector3d f1 = + Vector3d(*Ellipses[it->index].focus1.x, *Ellipses[it->index].focus1.y, 0.0); double radmin = *Ellipses[it->index].radmin; - Base::Vector3d fd=f1-center; - double radmaj = sqrt(fd*fd+radmin*radmin); + Base::Vector3d fd = f1 - center; + double radmaj = sqrt(fd * fd + radmin * radmin); ellipse->setCenter(center); - if ( radmaj >= ellipse->getMinorRadius() ){//ensure that ellipse's major radius is always larger than minor raduis... may still cause problems with degenerates. + // ensure that ellipse's major radius is always larger than minor radius... may + // still cause problems with degenerates. + if (radmaj >= ellipse->getMinorRadius()) { ellipse->setMajorRadius(radmaj); ellipse->setMinorRadius(radmin); - } else { + } + else { ellipse->setMinorRadius(radmin); ellipse->setMajorRadius(radmaj); } ellipse->setMajorAxisDir(fd); } else if (it->type == ArcOfHyperbola) { - GCS::ArcOfHyperbola &myArc = ArcsOfHyperbola[it->index]; + GCS::ArcOfHyperbola& myArc = ArcsOfHyperbola[it->index]; - GeomArcOfHyperbola *aoh = static_cast(it->geo); + GeomArcOfHyperbola* aoh = static_cast(it->geo); - Base::Vector3d center = Vector3d(*Points[it->midPointId].x, *Points[it->midPointId].y, 0.0); + Base::Vector3d center = + Vector3d(*Points[it->midPointId].x, *Points[it->midPointId].y, 0.0); Base::Vector3d f1 = Vector3d(*myArc.focus1.x, *myArc.focus1.y, 0.0); double radmin = *myArc.radmin; - Base::Vector3d fd=f1-center; - double radmaj = sqrt(fd*fd-radmin*radmin); + Base::Vector3d fd = f1 - center; + double radmaj = sqrt(fd * fd - radmin * radmin); aoh->setCenter(center); - if ( radmaj >= aoh->getMinorRadius() ){ + if (radmaj >= aoh->getMinorRadius()) { aoh->setMajorRadius(radmaj); aoh->setMinorRadius(radmin); - } else { + } + else { aoh->setMinorRadius(radmin); aoh->setMajorRadius(radmaj); } @@ -3714,14 +4058,15 @@ bool Sketch::updateGeometry() aoh->setRange(*myArc.startAngle, *myArc.endAngle, /*emulateCCW=*/true); } else if (it->type == ArcOfParabola) { - GCS::ArcOfParabola &myArc = ArcsOfParabola[it->index]; + GCS::ArcOfParabola& myArc = ArcsOfParabola[it->index]; - GeomArcOfParabola *aop = static_cast(it->geo); + GeomArcOfParabola* aop = static_cast(it->geo); - Base::Vector3d vertex = Vector3d(*Points[it->midPointId].x, *Points[it->midPointId].y, 0.0); + Base::Vector3d vertex = + Vector3d(*Points[it->midPointId].x, *Points[it->midPointId].y, 0.0); Base::Vector3d f1 = Vector3d(*myArc.focus1.x, *myArc.focus1.y, 0.0); - Base::Vector3d fd=f1-vertex; + Base::Vector3d fd = f1 - vertex; aop->setXAxisDir(fd); aop->setCenter(vertex); @@ -3729,18 +4074,20 @@ bool Sketch::updateGeometry() aop->setRange(*myArc.startAngle, *myArc.endAngle, /*emulateCCW=*/true); } else if (it->type == BSpline) { - GCS::BSpline &mybsp = BSplines[it->index]; + GCS::BSpline& mybsp = BSplines[it->index]; - GeomBSplineCurve *bsp = static_cast(it->geo); + GeomBSplineCurve* bsp = static_cast(it->geo); std::vector poles; std::vector weights; std::vector::const_iterator it1; - std::vector::const_iterator it2; + std::vector::const_iterator it2; - for( it1 = mybsp.poles.begin(), it2 = mybsp.weights.begin(); it1 != mybsp.poles.end() && it2 != mybsp.weights.end(); ++it1, ++it2) { - poles.emplace_back( *(*it1).x , *(*it1).y , 0.0); + for (it1 = mybsp.poles.begin(), it2 = mybsp.weights.begin(); + it1 != mybsp.poles.end() && it2 != mybsp.weights.end(); + ++it1, ++it2) { + poles.emplace_back(*(*it1).x, *(*it1).y, 0.0); weights.push_back(*(*it2)); } @@ -3749,20 +4096,21 @@ bool Sketch::updateGeometry() std::vector knots; std::vector mult; - // This is the code that should be here when/if b-spline gets its full implementation in the solver. + // This is the code that should be here when/if b-spline gets its full + // implementation in the solver. /*std::vector::const_iterator it3; std::vector::const_iterator it4; - for( it3 = mybsp.knots.begin(), it4 = mybsp.mult.begin(); it3 != mybsp.knots.end() && it4 != mybsp.mult.end(); ++it3, ++it4) { - knots.push_back(*(*it3)); + for( it3 = mybsp.knots.begin(), it4 = mybsp.mult.begin(); it3 != mybsp.knots.end() + && it4 != mybsp.mult.end(); ++it3, ++it4) { knots.push_back(*(*it3)); mult.push_back((*it4)); } bsp->setKnots(knots,mult);*/ } - } catch (Base::Exception &e) { - Base::Console().Error("Updating geometry: Error build geometry(%d): %s\n", - i,e.what()); + } + catch (Base::Exception& e) { + Base::Console().Error("Updating geometry: Error build geometry(%d): %s\n", i, e.what()); return false; } } @@ -3771,35 +4119,35 @@ bool Sketch::updateGeometry() bool Sketch::updateNonDrivingConstraints() { - for (std::vector::iterator it = Constrs.begin();it!=Constrs.end();++it){ - if(!(*it).driving) { - if((*it).constr->Type==SnellsLaw) { + for (std::vector::iterator it = Constrs.begin(); it != Constrs.end(); ++it) { + if (!(*it).driving) { + if ((*it).constr->Type == SnellsLaw) { double n1 = *((*it).value); double n2 = *((*it).secondvalue); - (*it).constr->setValue(n2/n1); + (*it).constr->setValue(n2 / n1); } - else if((*it).constr->Type==Angle) { + else if ((*it).constr->Type == Angle) { - (*it).constr->setValue(std::fmod(*((*it).value), 2.0*M_PI)); + (*it).constr->setValue(std::fmod(*((*it).value), 2.0 * M_PI)); } - else if((*it).constr->Type==Diameter && (*it).constr->First>=0 ) { + else if ((*it).constr->Type == Diameter && (*it).constr->First >= 0) { // two cases, the geometry parameter is fixed or it is not // NOTE: This is different from being blocked, as new block constraint may fix // the parameter or not depending on whether other driving constraints are present int geoId = (*it).constr->First; - geoId = checkGeoId( geoId ); + geoId = checkGeoId(geoId); - double * rad = nullptr; + double* rad = nullptr; if (Geoms[geoId].type == Circle) { - GCS::Circle &c = Circles[Geoms[geoId].index]; + GCS::Circle& c = Circles[Geoms[geoId].index]; rad = c.rad; } else if (Geoms[geoId].type == Arc) { - GCS::Arc &a = Arcs[Geoms[geoId].index]; + GCS::Arc& a = Arcs[Geoms[geoId].index]; rad = a.rad; } @@ -3808,13 +4156,13 @@ bool Sketch::updateNonDrivingConstraints() if (pos != FixParameters.end()) (*it).constr->setValue(*((*it).value)); else - (*it).constr->setValue(2.0**((*it).value)); + (*it).constr->setValue(2.0 * *((*it).value)); } else { (*it).constr->setValue(*((*it).value)); } } - } + } return true; } @@ -3830,19 +4178,21 @@ int Sketch::solve() Base::TimeInfo end_time; - if(debugMode==GCS::Minimal || debugMode==GCS::IterationLevel){ + if (debugMode == GCS::Minimal || debugMode == GCS::IterationLevel) { - Base::Console().Log("Sketcher::Solve()-%s-T:%s\n",solvername.c_str(),Base::TimeInfo::diffTime(start_time,end_time).c_str()); + Base::Console().Log("Sketcher::Solve()-%s-T:%s\n", + solvername.c_str(), + Base::TimeInfo::diffTime(start_time, end_time).c_str()); } - SolveTime = Base::TimeInfo::diffTimeF(start_time,end_time); + SolveTime = Base::TimeInfo::diffTimeF(start_time, end_time); return result; } -int Sketch::internalSolve(std::string & solvername, int level) +int Sketch::internalSolve(std::string& solvername, int level) { - if (!isInitMove) { // make sure we are in single subsystem mode + if (!isInitMove) {// make sure we are in single subsystem mode clearTemporaryConstraints(); isFine = true; } @@ -3851,26 +4201,26 @@ int Sketch::internalSolve(std::string & solvername, int level) bool valid_solution; int defaultsoltype = -1; - if(isInitMove){ - solvername = "DogLeg"; // DogLeg is used for dragging (same as before) + if (isInitMove) { + solvername = "DogLeg";// DogLeg is used for dragging (same as before) ret = GCSsys.solve(isFine, GCS::DogLeg); } - else{ + else { switch (defaultSolver) { case 0: solvername = "BFGS"; ret = GCSsys.solve(isFine, GCS::BFGS); - defaultsoltype=2; + defaultsoltype = 2; break; - case 1: // solving with the LevenbergMarquardt solver + case 1:// solving with the LevenbergMarquardt solver solvername = "LevenbergMarquardt"; ret = GCSsys.solve(isFine, GCS::LevenbergMarquardt); - defaultsoltype=1; + defaultsoltype = 1; break; - case 2: // solving with the BFGS solver + case 2:// solving with the BFGS solver solvername = "DogLeg"; ret = GCSsys.solve(isFine, GCS::DogLeg); - defaultsoltype=0; + defaultsoltype = 0; break; } } @@ -3890,43 +4240,48 @@ int Sketch::internalSolve(std::string & solvername, int level) } else { valid_solution = false; - if(debugMode==GCS::Minimal || debugMode==GCS::IterationLevel){ + if (debugMode == GCS::Minimal || debugMode == GCS::IterationLevel) { - Base::Console().Log("Sketcher::Solve()-%s- Failed!! Falling back...\n",solvername.c_str()); + Base::Console().Log("Sketcher::Solve()-%s- Failed!! Falling back...\n", + solvername.c_str()); } } - if(!valid_solution && !isInitMove) { // Fall back to other solvers - for (int soltype=0; soltype < 4; soltype++) { + if (!valid_solution && !isInitMove) {// Fall back to other solvers + for (int soltype = 0; soltype < 4; soltype++) { - if(soltype==defaultsoltype){ - continue; // skip default solver + if (soltype == defaultsoltype) { + continue;// skip default solver } switch (soltype) { - case 0: - solvername = "DogLeg"; - ret = GCSsys.solve(isFine, GCS::DogLeg); - break; - case 1: // solving with the LevenbergMarquardt solver - solvername = "LevenbergMarquardt"; - ret = GCSsys.solve(isFine, GCS::LevenbergMarquardt); - break; - case 2: // solving with the BFGS solver - solvername = "BFGS"; - ret = GCSsys.solve(isFine, GCS::BFGS); - break; - case 3: // last resort: augment the system with a second subsystem and use the SQP solver - solvername = "SQP(augmented system)"; - InitParameters.resize(Parameters.size()); - int i=0; - for (std::vector::iterator it = Parameters.begin(); it != Parameters.end(); ++it, i++) { - InitParameters[i] = **it; - GCSsys.addConstraintEqual(*it, &InitParameters[i], GCS::DefaultTemporaryConstraint); - } - GCSsys.initSolution(); - ret = GCSsys.solve(isFine); - break; + case 0: + solvername = "DogLeg"; + ret = GCSsys.solve(isFine, GCS::DogLeg); + break; + case 1:// solving with the LevenbergMarquardt solver + solvername = "LevenbergMarquardt"; + ret = GCSsys.solve(isFine, GCS::LevenbergMarquardt); + break; + case 2:// solving with the BFGS solver + solvername = "BFGS"; + ret = GCSsys.solve(isFine, GCS::BFGS); + break; + // last resort: augment the system with a second subsystem and use the SQP solver + case 3: + solvername = "SQP(augmented system)"; + InitParameters.resize(Parameters.size()); + int i = 0; + for (std::vector::iterator it = Parameters.begin(); + it != Parameters.end(); + ++it, i++) { + InitParameters[i] = **it; + GCSsys.addConstraintEqual( + *it, &InitParameters[i], GCS::DefaultTemporaryConstraint); + } + GCSsys.initSolution(); + ret = GCSsys.solve(isFine); + break; } // if successfully solved try to write the parameters back @@ -3936,43 +4291,50 @@ int Sketch::internalSolve(std::string & solvername, int level) if (!valid_solution) { GCSsys.undoSolution(); updateGeometry(); - Base::Console().Warning("Invalid solution from %s solver.\n", solvername.c_str()); + Base::Console().Warning("Invalid solution from %s solver.\n", + solvername.c_str()); ret = GCS::SuccessfulSolutionInvalid; - }else - { + } + else { updateNonDrivingConstraints(); } } else { valid_solution = false; - if(debugMode==GCS::Minimal || debugMode==GCS::IterationLevel){ + if (debugMode == GCS::Minimal || debugMode == GCS::IterationLevel) { - Base::Console().Log("Sketcher::Solve()-%s- Failed!! Falling back...\n",solvername.c_str()); + Base::Console().Log("Sketcher::Solve()-%s- Failed!! Falling back...\n", + solvername.c_str()); } } - if (soltype == 3) // cleanup temporary constraints of the augmented system + if (soltype == 3)// cleanup temporary constraints of the augmented system clearTemporaryConstraints(); if (valid_solution) { if (soltype == 1) - Base::Console().Log("Important: the LevenbergMarquardt solver succeeded where the DogLeg solver had failed.\n"); + Base::Console().Log("Important: the LevenbergMarquardt solver succeeded where " + "the DogLeg solver had failed.\n"); else if (soltype == 2) - Base::Console().Log("Important: the BFGS solver succeeded where the DogLeg and LevenbergMarquardt solvers have failed.\n"); + Base::Console().Log("Important: the BFGS solver succeeded where the DogLeg and " + "LevenbergMarquardt solvers have failed.\n"); else if (soltype == 3) - Base::Console().Log("Important: the SQP solver succeeded where all single subsystem solvers have failed.\n"); + Base::Console().Log("Important: the SQP solver succeeded where all single " + "subsystem solvers have failed.\n"); if (soltype > 0) { - Base::Console().Log("If you see this message please report a way of reproducing this result at\n"); + Base::Console().Log("If you see this message please report a way of " + "reproducing this result at\n"); Base::Console().Log("http://www.freecad.org/tracker/main_page.php\n"); } break; } - } // soltype + }// soltype } - // For OCCT reliant geometry that needs an extra solve() for example to update non-driving constraints. + // For OCCT reliant geometry that needs an extra solve() for example to update non-driving + // constraints. if (resolveAfterGeometryUpdated && ret == GCS::Success && level == 0) { return internalSolve(solvername, 1); } @@ -3996,119 +4358,120 @@ int Sketch::initMove(int geoId, PointPos pos, bool fine) if (Geoms[geoId].type == Point) { if (pos == PointPos::start) { - GCS::Point &point = Points[Geoms[geoId].startPointId]; + GCS::Point& point = Points[Geoms[geoId].startPointId]; GCS::Point p0; - MoveParameters.resize(2); // px,py + MoveParameters.resize(2);// px,py p0.x = &MoveParameters[0]; p0.y = &MoveParameters[1]; *p0.x = *point.x; *p0.y = *point.y; - GCSsys.addConstraintP2PCoincident(p0,point,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p0, point, GCS::DefaultTemporaryConstraint); } } else if (Geoms[geoId].type == Line) { if (pos == PointPos::start || pos == PointPos::end) { - MoveParameters.resize(2); // x,y + MoveParameters.resize(2);// x,y GCS::Point p0; p0.x = &MoveParameters[0]; p0.y = &MoveParameters[1]; if (pos == PointPos::start) { - GCS::Point &p = Points[Geoms[geoId].startPointId]; + GCS::Point& p = Points[Geoms[geoId].startPointId]; *p0.x = *p.x; *p0.y = *p.y; - GCSsys.addConstraintP2PCoincident(p0,p,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p0, p, GCS::DefaultTemporaryConstraint); } else if (pos == PointPos::end) { - GCS::Point &p = Points[Geoms[geoId].endPointId]; + GCS::Point& p = Points[Geoms[geoId].endPointId]; *p0.x = *p.x; *p0.y = *p.y; - GCSsys.addConstraintP2PCoincident(p0,p,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p0, p, GCS::DefaultTemporaryConstraint); } } else if (pos == PointPos::none || pos == PointPos::mid) { - MoveParameters.resize(4); // x1,y1,x2,y2 + MoveParameters.resize(4);// x1,y1,x2,y2 GCS::Point p1, p2; p1.x = &MoveParameters[0]; p1.y = &MoveParameters[1]; p2.x = &MoveParameters[2]; p2.y = &MoveParameters[3]; - GCS::Line &l = Lines[Geoms[geoId].index]; + GCS::Line& l = Lines[Geoms[geoId].index]; *p1.x = *l.p1.x; *p1.y = *l.p1.y; *p2.x = *l.p2.x; *p2.y = *l.p2.y; - GCSsys.addConstraintP2PCoincident(p1,l.p1,GCS::DefaultTemporaryConstraint); - GCSsys.addConstraintP2PCoincident(p2,l.p2,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p1, l.p1, GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p2, l.p2, GCS::DefaultTemporaryConstraint); } } else if (Geoms[geoId].type == Circle) { - GCS::Point ¢er = Points[Geoms[geoId].midPointId]; - GCS::Point p0,p1; + GCS::Point& center = Points[Geoms[geoId].midPointId]; + GCS::Point p0, p1; if (pos == PointPos::mid) { - MoveParameters.resize(2); // cx,cy + MoveParameters.resize(2);// cx,cy p0.x = &MoveParameters[0]; p0.y = &MoveParameters[1]; *p0.x = *center.x; *p0.y = *center.y; - GCSsys.addConstraintP2PCoincident(p0,center,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p0, center, GCS::DefaultTemporaryConstraint); } else if (pos == PointPos::none) { - //bool pole = GeometryFacade::isInternalType(Geoms[geoId].geo, InternalType::BSplineControlPoint); - MoveParameters.resize(4); // x,y,cx,cy - For poles blocking the center - GCS::Circle &c = Circles[Geoms[geoId].index]; + // bool pole = GeometryFacade::isInternalType(Geoms[geoId].geo, + // InternalType::BSplineControlPoint); + MoveParameters.resize(4);// x,y,cx,cy - For poles blocking the center + GCS::Circle& c = Circles[Geoms[geoId].index]; p0.x = &MoveParameters[0]; p0.y = &MoveParameters[1]; *p0.x = *center.x; *p0.y = *center.y + *c.rad; - GCSsys.addConstraintPointOnCircle(p0,c,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintPointOnCircle(p0, c, GCS::DefaultTemporaryConstraint); p1.x = &MoveParameters[2]; p1.y = &MoveParameters[3]; *p1.x = *center.x; *p1.y = *center.y; - int i=GCSsys.addConstraintP2PCoincident(p1,center,GCS::DefaultTemporaryConstraint); - GCSsys.rescaleConstraint(i-1, 0.01); + int i = GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); + GCSsys.rescaleConstraint(i - 1, 0.01); GCSsys.rescaleConstraint(i, 0.01); } } else if (Geoms[geoId].type == Ellipse) { - GCS::Point ¢er = Points[Geoms[geoId].midPointId]; - GCS::Point p0,p1; + GCS::Point& center = Points[Geoms[geoId].midPointId]; + GCS::Point p0, p1; if (pos == PointPos::mid || pos == PointPos::none) { - MoveParameters.resize(2); // cx,cy + MoveParameters.resize(2);// cx,cy p0.x = &MoveParameters[0]; p0.y = &MoveParameters[1]; *p0.x = *center.x; *p0.y = *center.y; - GCSsys.addConstraintP2PCoincident(p0,center,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p0, center, GCS::DefaultTemporaryConstraint); } } else if (Geoms[geoId].type == ArcOfEllipse) { - GCS::Point ¢er = Points[Geoms[geoId].midPointId]; - GCS::Point p0,p1; + GCS::Point& center = Points[Geoms[geoId].midPointId]; + GCS::Point p0, p1; if (pos == PointPos::mid || pos == PointPos::none) { - MoveParameters.resize(2); // cx,cy + MoveParameters.resize(2);// cx,cy p0.x = &MoveParameters[0]; p0.y = &MoveParameters[1]; *p0.x = *center.x; *p0.y = *center.y; - GCSsys.addConstraintP2PCoincident(p0,center,GCS::DefaultTemporaryConstraint); - + GCSsys.addConstraintP2PCoincident(p0, center, GCS::DefaultTemporaryConstraint); } else if (pos == PointPos::start || pos == PointPos::end) { - MoveParameters.resize(4); // x,y,cx,cy + MoveParameters.resize(4);// x,y,cx,cy if (pos == PointPos::start || pos == PointPos::end) { - GCS::Point &p = (pos == PointPos::start) ? Points[Geoms[geoId].startPointId] - : Points[Geoms[geoId].endPointId];; + GCS::Point& p = (pos == PointPos::start) ? Points[Geoms[geoId].startPointId] + : Points[Geoms[geoId].endPointId]; + ; p0.x = &MoveParameters[0]; p0.y = &MoveParameters[1]; *p0.x = *p.x; *p0.y = *p.y; - GCSsys.addConstraintP2PCoincident(p0,p,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p0, p, GCS::DefaultTemporaryConstraint); } p1.x = &MoveParameters[2]; @@ -4116,110 +4479,111 @@ int Sketch::initMove(int geoId, PointPos pos, bool fine) *p1.x = *center.x; *p1.y = *center.y; - int i=GCSsys.addConstraintP2PCoincident(p1,center,GCS::DefaultTemporaryConstraint); - GCSsys.rescaleConstraint(i-1, 0.01); + int i = GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); + GCSsys.rescaleConstraint(i - 1, 0.01); GCSsys.rescaleConstraint(i, 0.01); } } else if (Geoms[geoId].type == ArcOfHyperbola) { - GCS::Point ¢er = Points[Geoms[geoId].midPointId]; - GCS::Point p0,p1; + GCS::Point& center = Points[Geoms[geoId].midPointId]; + GCS::Point p0, p1; if (pos == PointPos::mid || pos == PointPos::none) { - MoveParameters.resize(2); // cx,cy + MoveParameters.resize(2);// cx,cy p0.x = &MoveParameters[0]; p0.y = &MoveParameters[1]; *p0.x = *center.x; *p0.y = *center.y; - GCSsys.addConstraintP2PCoincident(p0,center,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p0, center, GCS::DefaultTemporaryConstraint); } else if (pos == PointPos::start || pos == PointPos::end) { - MoveParameters.resize(4); // x,y,cx,cy + MoveParameters.resize(4);// x,y,cx,cy if (pos == PointPos::start || pos == PointPos::end) { - GCS::Point &p = (pos == PointPos::start) ? Points[Geoms[geoId].startPointId] - : Points[Geoms[geoId].endPointId];; + GCS::Point& p = (pos == PointPos::start) ? Points[Geoms[geoId].startPointId] + : Points[Geoms[geoId].endPointId]; + ; p0.x = &MoveParameters[0]; p0.y = &MoveParameters[1]; *p0.x = *p.x; *p0.y = *p.y; - GCSsys.addConstraintP2PCoincident(p0,p,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p0, p, GCS::DefaultTemporaryConstraint); } p1.x = &MoveParameters[2]; p1.y = &MoveParameters[3]; *p1.x = *center.x; *p1.y = *center.y; - int i=GCSsys.addConstraintP2PCoincident(p1,center,GCS::DefaultTemporaryConstraint); - GCSsys.rescaleConstraint(i-1, 0.01); + int i = GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); + GCSsys.rescaleConstraint(i - 1, 0.01); GCSsys.rescaleConstraint(i, 0.01); - } } else if (Geoms[geoId].type == ArcOfParabola) { - GCS::Point ¢er = Points[Geoms[geoId].midPointId]; - GCS::Point p0,p1; + GCS::Point& center = Points[Geoms[geoId].midPointId]; + GCS::Point p0, p1; if (pos == PointPos::mid || pos == PointPos::none) { - MoveParameters.resize(2); // cx,cy + MoveParameters.resize(2);// cx,cy p0.x = &MoveParameters[0]; p0.y = &MoveParameters[1]; *p0.x = *center.x; *p0.y = *center.y; - GCSsys.addConstraintP2PCoincident(p0,center,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p0, center, GCS::DefaultTemporaryConstraint); } else if (pos == PointPos::start || pos == PointPos::end) { - MoveParameters.resize(4); // x,y,cx,cy + MoveParameters.resize(4);// x,y,cx,cy if (pos == PointPos::start || pos == PointPos::end) { - GCS::Point &p = (pos == PointPos::start) ? Points[Geoms[geoId].startPointId] - : Points[Geoms[geoId].endPointId];; + GCS::Point& p = (pos == PointPos::start) ? Points[Geoms[geoId].startPointId] + : Points[Geoms[geoId].endPointId]; + ; p0.x = &MoveParameters[0]; p0.y = &MoveParameters[1]; *p0.x = *p.x; *p0.y = *p.y; - GCSsys.addConstraintP2PCoincident(p0,p,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p0, p, GCS::DefaultTemporaryConstraint); } p1.x = &MoveParameters[2]; p1.y = &MoveParameters[3]; *p1.x = *center.x; *p1.y = *center.y; - int i=GCSsys.addConstraintP2PCoincident(p1,center,GCS::DefaultTemporaryConstraint); - GCSsys.rescaleConstraint(i-1, 0.01); + int i = GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); + GCSsys.rescaleConstraint(i - 1, 0.01); GCSsys.rescaleConstraint(i, 0.01); - } } else if (Geoms[geoId].type == BSpline) { if (pos == PointPos::start || pos == PointPos::end) { - MoveParameters.resize(2); // x,y + MoveParameters.resize(2);// x,y GCS::Point p0; p0.x = &MoveParameters[0]; p0.y = &MoveParameters[1]; if (pos == PointPos::start) { - GCS::Point &p = Points[Geoms[geoId].startPointId]; + GCS::Point& p = Points[Geoms[geoId].startPointId]; *p0.x = *p.x; *p0.y = *p.y; - GCSsys.addConstraintP2PCoincident(p0,p,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p0, p, GCS::DefaultTemporaryConstraint); } else if (pos == PointPos::end) { - GCS::Point &p = Points[Geoms[geoId].endPointId]; + GCS::Point& p = Points[Geoms[geoId].endPointId]; *p0.x = *p.x; *p0.y = *p.y; - GCSsys.addConstraintP2PCoincident(p0,p,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p0, p, GCS::DefaultTemporaryConstraint); } } else if (pos == PointPos::none || pos == PointPos::mid) { - GCS::BSpline &bsp = BSplines[Geoms[geoId].index]; - MoveParameters.resize(bsp.poles.size()*2); // x0,y0,x1,y1,....xp,yp + GCS::BSpline& bsp = BSplines[Geoms[geoId].index]; + MoveParameters.resize(bsp.poles.size() * 2);// x0,y0,x1,y1,....xp,yp int mvindex = 0; - for(std::vector::iterator it = bsp.poles.begin(); it != bsp.poles.end() ; it++, mvindex++) { + for (std::vector::iterator it = bsp.poles.begin(); it != bsp.poles.end(); + it++, mvindex++) { GCS::Point p1; p1.x = &MoveParameters[mvindex]; mvindex++; @@ -4228,47 +4592,47 @@ int Sketch::initMove(int geoId, PointPos pos, bool fine) *p1.x = *(*it).x; *p1.y = *(*it).y; - GCSsys.addConstraintP2PCoincident(p1,(*it),GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p1, (*it), GCS::DefaultTemporaryConstraint); } - } } else if (Geoms[geoId].type == Arc) { - GCS::Point ¢er = Points[Geoms[geoId].midPointId]; - GCS::Point p0,p1; + GCS::Point& center = Points[Geoms[geoId].midPointId]; + GCS::Point p0, p1; if (pos == PointPos::mid) { - MoveParameters.resize(2); // cx,cy + MoveParameters.resize(2);// cx,cy p0.x = &MoveParameters[0]; p0.y = &MoveParameters[1]; *p0.x = *center.x; *p0.y = *center.y; - GCSsys.addConstraintP2PCoincident(p0,center,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p0, center, GCS::DefaultTemporaryConstraint); } else if (pos == PointPos::start || pos == PointPos::end || pos == PointPos::none) { - MoveParameters.resize(4); // x,y,cx,cy + MoveParameters.resize(4);// x,y,cx,cy if (pos == PointPos::start || pos == PointPos::end) { - GCS::Point &p = (pos == PointPos::start) ? Points[Geoms[geoId].startPointId] - : Points[Geoms[geoId].endPointId];; + GCS::Point& p = (pos == PointPos::start) ? Points[Geoms[geoId].startPointId] + : Points[Geoms[geoId].endPointId]; + ; p0.x = &MoveParameters[0]; p0.y = &MoveParameters[1]; *p0.x = *p.x; *p0.y = *p.y; - GCSsys.addConstraintP2PCoincident(p0,p,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintP2PCoincident(p0, p, GCS::DefaultTemporaryConstraint); } else if (pos == PointPos::none) { - GCS::Arc &a = Arcs[Geoms[geoId].index]; + GCS::Arc& a = Arcs[Geoms[geoId].index]; p0.x = &MoveParameters[0]; p0.y = &MoveParameters[1]; *p0.x = *center.x; *p0.y = *center.y + *a.rad; - GCSsys.addConstraintPointOnArc(p0,a,GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintPointOnArc(p0, a, GCS::DefaultTemporaryConstraint); } p1.x = &MoveParameters[2]; p1.y = &MoveParameters[3]; *p1.x = *center.x; *p1.y = *center.y; - int i=GCSsys.addConstraintP2PCoincident(p1,center,GCS::DefaultTemporaryConstraint); - GCSsys.rescaleConstraint(i-1, 0.01); + int i = GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); + GCSsys.rescaleConstraint(i - 1, 0.01); GCSsys.rescaleConstraint(i, 0.01); } } @@ -4284,7 +4648,8 @@ void Sketch::resetInitMove() isInitMove = false; } -int Sketch::initBSplinePieceMove(int geoId, PointPos pos, const Base::Vector3d& firstPoint, bool fine) +int Sketch::initBSplinePieceMove(int geoId, PointPos pos, const Base::Vector3d& firstPoint, + bool fine) { isFine = fine; @@ -4303,7 +4668,7 @@ int Sketch::initBSplinePieceMove(int geoId, PointPos pos, const Base::Vector3d& return -1; } - GCS::BSpline &bsp = BSplines[Geoms[geoId].index]; + GCS::BSpline& bsp = BSplines[Geoms[geoId].index]; // If spline has too few poles, just move all if (bsp.poles.size() <= std::size_t(bsp.degree + 1)) @@ -4314,23 +4679,22 @@ int Sketch::initBSplinePieceMove(int geoId, PointPos pos, const Base::Vector3d& double uNear; partBsp->closestParameter(firstPoint, uNear); auto& knots = bsp.knots; - auto upperknot = std::upper_bound( - knots.begin(), knots.end(), uNear, - [](double u, double* element) { + auto upperknot = + std::upper_bound(knots.begin(), knots.end(), uNear, [](double u, double* element) { return u < *element; }); size_t idx = 0; // skipping the first knot for adjustment // TODO: ensure this works for periodic as well - for (size_t i=1; i 20*moveStep) { // I am getting too far away from the original solution so reinit the solution + // I am getting too far away from the original solution so reinit the solution + if ((toPoint - initToPoint).Length() > 20 * moveStep) { initMove(geoId, pos); initToPoint = toPoint; } @@ -4377,9 +4742,9 @@ int Sketch::movePoint(int geoId, PointPos pos, Base::Vector3d toPoint, bool rela } if (relative) { - for (int i=0; i < int(MoveParameters.size()-1); i+=2) { + for (int i = 0; i < int(MoveParameters.size() - 1); i += 2) { MoveParameters[i] = InitParameters[i] + toPoint.x; - MoveParameters[i+1] = InitParameters[i+1] + toPoint.y; + MoveParameters[i + 1] = InitParameters[i + 1] + toPoint.y; } } else if (Geoms[geoId].type == Point) { @@ -4394,8 +4759,8 @@ int Sketch::movePoint(int geoId, PointPos pos, Base::Vector3d toPoint, bool rela MoveParameters[1] = toPoint.y; } else if (pos == PointPos::none || pos == PointPos::mid) { - double dx = (InitParameters[2]-InitParameters[0])/2; - double dy = (InitParameters[3]-InitParameters[1])/2; + double dx = (InitParameters[2] - InitParameters[0]) / 2; + double dy = (InitParameters[3] - InitParameters[1]) / 2; MoveParameters[0] = toPoint.x - dx; MoveParameters[1] = toPoint.y - dy; MoveParameters[2] = toPoint.x + dx; @@ -4409,7 +4774,8 @@ int Sketch::movePoint(int geoId, PointPos pos, Base::Vector3d toPoint, bool rela } } else if (Geoms[geoId].type == Arc) { - if (pos == PointPos::start || pos == PointPos::end || pos == PointPos::mid || pos == PointPos::none) { + if (pos == PointPos::start || pos == PointPos::end || pos == PointPos::mid + || pos == PointPos::none) { MoveParameters[0] = toPoint.x; MoveParameters[1] = toPoint.y; } @@ -4421,19 +4787,22 @@ int Sketch::movePoint(int geoId, PointPos pos, Base::Vector3d toPoint, bool rela } } else if (Geoms[geoId].type == ArcOfEllipse) { - if (pos == PointPos::start || pos == PointPos::end || pos == PointPos::mid || pos == PointPos::none) { + if (pos == PointPos::start || pos == PointPos::end || pos == PointPos::mid + || pos == PointPos::none) { MoveParameters[0] = toPoint.x; MoveParameters[1] = toPoint.y; } } else if (Geoms[geoId].type == ArcOfHyperbola) { - if (pos == PointPos::start || pos == PointPos::end || pos == PointPos::mid || pos == PointPos::none) { + if (pos == PointPos::start || pos == PointPos::end || pos == PointPos::mid + || pos == PointPos::none) { MoveParameters[0] = toPoint.x; MoveParameters[1] = toPoint.y; } } else if (Geoms[geoId].type == ArcOfParabola) { - if (pos == PointPos::start || pos == PointPos::end || pos == PointPos::mid || pos == PointPos::none) { + if (pos == PointPos::start || pos == PointPos::end || pos == PointPos::mid + || pos == PointPos::none) { MoveParameters[0] = toPoint.x; MoveParameters[1] = toPoint.y; } @@ -4444,23 +4813,22 @@ int Sketch::movePoint(int geoId, PointPos pos, Base::Vector3d toPoint, bool rela MoveParameters[1] = toPoint.y; } else if (pos == PointPos::none || pos == PointPos::mid) { - GCS::BSpline &bsp = BSplines[Geoms[geoId].index]; + GCS::BSpline& bsp = BSplines[Geoms[geoId].index]; - double cx = 0, cy = 0; // geometric center - for (int i=0; i < int(InitParameters.size()-1); i+=2) { + double cx = 0, cy = 0;// geometric center + for (int i = 0; i < int(InitParameters.size() - 1); i += 2) { cx += InitParameters[i]; - cy += InitParameters[i+1]; + cy += InitParameters[i + 1]; } cx /= bsp.poles.size(); cy /= bsp.poles.size(); - for (int i=0; i < int(MoveParameters.size()-1); i+=2) { + for (int i = 0; i < int(MoveParameters.size() - 1); i += 2) { - MoveParameters[i] = toPoint.x + InitParameters[i] - cx; - MoveParameters[i+1] = toPoint.y + InitParameters[i+1] - cy; + MoveParameters[i] = toPoint.x + InitParameters[i] - cx; + MoveParameters[i + 1] = toPoint.y + InitParameters[i + 1] - cy; } - } } @@ -4478,14 +4846,14 @@ int Sketch::getPointId(int geoId, PointPos pos) const if (geoId < 0 || geoId >= (int)Geoms.size()) return -1; switch (pos) { - case PointPos::start: - return Geoms[geoId].startPointId; - case PointPos::end: - return Geoms[geoId].endPointId; - case PointPos::mid: - return Geoms[geoId].midPointId; - case PointPos::none: - break; + case PointPos::start: + return Geoms[geoId].startPointId; + case PointPos::end: + return Geoms[geoId].endPointId; + case PointPos::mid: + return Geoms[geoId].midPointId; + case PointPos::none: + break; } return -1; } @@ -4503,7 +4871,7 @@ Base::Vector3d Sketch::getPoint(int geoId, PointPos pos) const TopoShape Sketch::toShape() const { TopoShape result; - std::vector::const_iterator it=Geoms.begin(); + std::vector::const_iterator it = Geoms.begin(); #if 0 @@ -4527,13 +4895,13 @@ TopoShape Sketch::toShape() const std::list wires; // collecting all (non constructive and non external) edges out of the sketch - for (;it!=Geoms.end();++it) { + for (; it != Geoms.end(); ++it) { auto gf = GeometryFacade::getFacade(it->geo); if (!it->external && !gf->getConstruction()) { if (it->type != Point) { - auto shape =it->geo->toShape(); - if(!shape.IsNull()) + auto shape = it->geo->toShape(); + if (!shape.IsNull()) edge_list.push_back(TopoDS::Edge(shape)); } else @@ -4550,13 +4918,15 @@ TopoShape Sketch::toShape() const mkWire.Add(edge_list.front()); edge_list.pop_front(); - TopoDS_Wire new_wire = mkWire.Wire(); // current new wire + TopoDS_Wire new_wire = mkWire.Wire();// current new wire - // try to connect each edge to the wire, the wire is complete if no more edges are connectible + // try to connect each edge to the wire, the wire is complete if no more edges are + // connectible bool found = false; do { found = false; - for (std::list::iterator pE = edge_list.begin(); pE != edge_list.end(); ++pE) { + for (std::list::iterator pE = edge_list.begin(); pE != edge_list.end(); + ++pE) { mkWire.Add(*pE); if (mkWire.Error() != BRepBuilderAPI_DisconnectedWire) { // edge added ==> remove it from list @@ -4566,8 +4936,7 @@ TopoShape Sketch::toShape() const break; } } - } - while (found); + } while (found); // Fix any topological issues of the wire ShapeFix_Wire aFix; @@ -4586,7 +4955,7 @@ TopoShape Sketch::toShape() const // FIXME: The right way here would be to determine the outer and inner wires and // generate a face with holes (inner wires have to be tagged REVERSE or INNER). // that's the only way to transport a somewhat more complex sketch... - //result = *wires.begin(); + // result = *wires.begin(); // I think a compound can be used as container because it is just a collection of // shapes and doesn't need too much information about the topology. @@ -4597,7 +4966,8 @@ TopoShape Sketch::toShape() const builder.MakeCompound(comp); for (std::list::iterator wt = wires.begin(); wt != wires.end(); ++wt) builder.Add(comp, *wt); - for (std::list::iterator wt = vertex_list.begin(); wt != vertex_list.end(); ++wt) + for (std::list::iterator wt = vertex_list.begin(); wt != vertex_list.end(); + ++wt) builder.Add(comp, *wt); result.setShape(comp); } @@ -4613,13 +4983,8 @@ unsigned int Sketch::getMemSize() const return 0; } -void Sketch::Save(Writer &) const -{ - -} - -void Sketch::Restore(XMLReader &) -{ - -} +void Sketch::Save(Writer&) const +{} +void Sketch::Restore(XMLReader&) +{} diff --git a/src/Mod/Sketcher/App/Sketch.h b/src/Mod/Sketcher/App/Sketch.h index 69e6743c57..ad13f7a73c 100644 --- a/src/Mod/Sketcher/App/Sketch.h +++ b/src/Mod/Sketcher/App/Sketch.h @@ -34,10 +34,10 @@ namespace Sketcher { - // Forward declarations - class SolverGeometryExtension; +// Forward declarations +class SolverGeometryExtension; -class SketcherExport Sketch :public Base::Persistence +class SketcherExport Sketch: public Base::Persistence { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -47,52 +47,56 @@ public: // from base class unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; /// solve the actual set up sketch int solve(); /// resets the solver int resetSolver(); /// get standard (aka fine) solver precision - double getSolverPrecision(){ return GCSsys.getFinePrecision(); } + double getSolverPrecision() + { + return GCSsys.getFinePrecision(); + } /// delete all geometry and constraints, leave an empty sketch void clear(); /** set the sketch up with geoms and constraints - * - * returns the degree of freedom of a sketch and calculates a list of - * conflicting constraints - * - * 0 degrees of freedom correspond to a fully constrained sketch - * -1 degrees of freedom correspond to an over-constrained sketch - * positive degrees of freedom correspond to an under-constrained sketch - * - * an over-constrained sketch will always contain conflicting constraints - * a fully constrained or under-constrained sketch may contain conflicting - * constraints or may not - */ - int setUpSketch(const std::vector &GeoList, const std::vector &ConstraintList, - int extGeoCount=0); + * + * returns the degree of freedom of a sketch and calculates a list of + * conflicting constraints + * + * 0 degrees of freedom correspond to a fully constrained sketch + * -1 degrees of freedom correspond to an over-constrained sketch + * positive degrees of freedom correspond to an under-constrained sketch + * + * an over-constrained sketch will always contain conflicting constraints + * a fully constrained or under-constrained sketch may contain conflicting + * constraints or may not + */ + int setUpSketch(const std::vector& GeoList, + const std::vector& ConstraintList, int extGeoCount = 0); /// return the actual geometry of the sketch a TopoShape Part::TopoShape toShape() const; /// add unspecified geometry - int addGeometry(const Part::Geometry *geo, bool fixed=false); + int addGeometry(const Part::Geometry* geo, bool fixed = false); /// add unspecified geometry - int addGeometry(const std::vector &geo, bool fixed=false); - /// add unspecified geometry, where each element's "fixed" status is given by the blockedGeometry array - int addGeometry(const std::vector &geo, - const std::vector &blockedGeometry); + int addGeometry(const std::vector& geo, bool fixed = false); + /// add unspecified geometry, where each element's "fixed" status is given by the + /// blockedGeometry array + int addGeometry(const std::vector& geo, + const std::vector& blockedGeometry); /// get boolean list indicating whether the geometry is to be blocked or not - void getBlockedGeometry(std::vector & blockedGeometry, - std::vector & unenforceableConstraints, - const std::vector &ConstraintList) const; + void getBlockedGeometry(std::vector& blockedGeometry, + std::vector& unenforceableConstraints, + const std::vector& ConstraintList) const; /// returns the actual geometry - std::vector extractGeometry(bool withConstructionElements=true, - bool withExternalElements=false) const; + std::vector extractGeometry(bool withConstructionElements = true, + bool withExternalElements = false) const; GeoListFacade extractGeoListFacade() const; - void updateExtension(int geoId, std::unique_ptr && ext); + void updateExtension(int geoId, std::unique_ptr&& ext); /// get the geometry as python objects Py::Tuple getPyGeometry() const; @@ -102,39 +106,67 @@ public: Base::Vector3d getPoint(int geoId, PointPos pos) const; // Inline methods - inline bool hasConflicts() const { return !Conflicting.empty(); } - inline const std::vector &getConflicting() const { return Conflicting; } - inline bool hasRedundancies() const { return !Redundant.empty(); } - inline const std::vector &getRedundant() const { return Redundant; } - inline bool hasPartialRedundancies() const { return !PartiallyRedundant.empty(); } - inline const std::vector &getPartiallyRedundant() const { return PartiallyRedundant; } + inline bool hasConflicts() const + { + return !Conflicting.empty(); + } + inline const std::vector& getConflicting() const + { + return Conflicting; + } + inline bool hasRedundancies() const + { + return !Redundant.empty(); + } + inline const std::vector& getRedundant() const + { + return Redundant; + } + inline bool hasPartialRedundancies() const + { + return !PartiallyRedundant.empty(); + } + inline const std::vector& getPartiallyRedundant() const + { + return PartiallyRedundant; + } - inline float getSolveTime() const { return SolveTime; } + inline float getSolveTime() const + { + return SolveTime; + } + + inline bool hasMalformedConstraints() const + { + return !MalformedConstraints.empty(); + } + inline const std::vector& getMalformedConstraints() const + { + return MalformedConstraints; + } - inline bool hasMalformedConstraints() const { return !MalformedConstraints.empty(); } - inline const std::vector &getMalformedConstraints() const { return MalformedConstraints; } public: - std::set < std::pair< int, Sketcher::PointPos>> getDependencyGroup(int geoId, PointPos pos) const; + std::set> getDependencyGroup(int geoId, PointPos pos) const; std::shared_ptr getSolverExtension(int geoId) const; public: - /** set the datum of a distance or angle constraint to a certain value and solve - * This can cause the solving to fail! - */ + * This can cause the solving to fail! + */ int setDatum(int constrId, double value); /** initializes a point (or curve) drag by setting the current - * sketch status as a reference - */ - int initMove(int geoId, PointPos pos, bool fine=true); + * sketch status as a reference + */ + int initMove(int geoId, PointPos pos, bool fine = true); /** Initializes a B-spline piece drag by setting the current - * sketch status as a reference. Only moves piece around `firstPoint`. - */ - int initBSplinePieceMove(int geoId, PointPos pos, const Base::Vector3d& firstPoint, bool fine=true); + * sketch status as a reference. Only moves piece around `firstPoint`. + */ + int initBSplinePieceMove(int geoId, PointPos pos, const Base::Vector3d& firstPoint, + bool fine = true); /** Resets the initialization of a point or curve drag */ @@ -145,105 +177,112 @@ public: int limitBSplineMove(int geoId, PointPos pos, const Base::Vector3d& firstPoint); /** move this point (or curve) to a new location and solve. - * This will introduce some additional weak constraints expressing - * a condition for satisfying the new point location! - * The relative flag permits moving relatively to the current position - */ - int movePoint(int geoId, PointPos pos, Base::Vector3d toPoint, bool relative=false); + * This will introduce some additional weak constraints expressing + * a condition for satisfying the new point location! + * The relative flag permits moving relatively to the current position + */ + int movePoint(int geoId, PointPos pos, Base::Vector3d toPoint, bool relative = false); /** - * Sets whether the initial solution should be recalculated while dragging after a certain distance from the previous drag point - * for smoother dragging operation. + * Sets whether the initial solution should be recalculated while dragging after a certain + * distance from the previous drag point for smoother dragging operation. */ bool getRecalculateInitialSolutionWhileMovingPoint() const - {return RecalculateInitialSolutionWhileMovingPoint;} + { + return RecalculateInitialSolutionWhileMovingPoint; + } - void setRecalculateInitialSolutionWhileMovingPoint(bool recalculateInitialSolutionWhileMovingPoint) - {RecalculateInitialSolutionWhileMovingPoint = recalculateInitialSolutionWhileMovingPoint;} + void + setRecalculateInitialSolutionWhileMovingPoint(bool recalculateInitialSolutionWhileMovingPoint) + { + RecalculateInitialSolutionWhileMovingPoint = recalculateInitialSolutionWhileMovingPoint; + } /// add dedicated geometry //@{ /// add a point - int addPoint(const Part::GeomPoint &point, bool fixed=false); + int addPoint(const Part::GeomPoint& point, bool fixed = false); /// add an infinite line - int addLine(const Part::GeomLineSegment &line, bool fixed=false); + int addLine(const Part::GeomLineSegment& line, bool fixed = false); /// add a line segment - int addLineSegment(const Part::GeomLineSegment &lineSegment, bool fixed=false); + int addLineSegment(const Part::GeomLineSegment& lineSegment, bool fixed = false); /// add a arc (circle segment) - int addArc(const Part::GeomArcOfCircle &circleSegment, bool fixed=false); + int addArc(const Part::GeomArcOfCircle& circleSegment, bool fixed = false); /// add a circle - int addCircle(const Part::GeomCircle &circle, bool fixed=false); + int addCircle(const Part::GeomCircle& circle, bool fixed = false); /// add an ellipse - int addEllipse(const Part::GeomEllipse &ellipse, bool fixed=false); + int addEllipse(const Part::GeomEllipse& ellipse, bool fixed = false); /// add an arc of ellipse - int addArcOfEllipse(const Part::GeomArcOfEllipse &ellipseSegment, bool fixed=false); + int addArcOfEllipse(const Part::GeomArcOfEllipse& ellipseSegment, bool fixed = false); /// add an arc of hyperbola - int addArcOfHyperbola(const Part::GeomArcOfHyperbola &hyperbolaSegment, bool fixed=false); + int addArcOfHyperbola(const Part::GeomArcOfHyperbola& hyperbolaSegment, bool fixed = false); /// add an arc of parabola - int addArcOfParabola(const Part::GeomArcOfParabola ¶bolaSegment, bool fixed=false); + int addArcOfParabola(const Part::GeomArcOfParabola& parabolaSegment, bool fixed = false); /// add a BSpline - int addBSpline(const Part::GeomBSplineCurve &spline, bool fixed=false); + int addBSpline(const Part::GeomBSplineCurve& spline, bool fixed = false); //@} /// constraints //@{ /// add all constraints in the list - int addConstraints(const std::vector &ConstraintList); + int addConstraints(const std::vector& ConstraintList); /// add all constraints in the list, provided that are enforceable - int addConstraints(const std::vector &ConstraintList, - const std::vector & unenforceableConstraints); + int addConstraints(const std::vector& ConstraintList, + const std::vector& unenforceableConstraints); /// add one constraint to the sketch - int addConstraint(const Constraint *constraint); + int addConstraint(const Constraint* constraint); /** - * add a fixed X coordinate constraint to a point - * - * double * value is a pointer to double allocated in the heap, containing the - * constraint value and already inserted into either the FixParameters or - * Parameters array, as the case may be. - */ - int addCoordinateXConstraint(int geoId, PointPos pos, double * value, bool driving = true); + * add a fixed X coordinate constraint to a point + * + * double * value is a pointer to double allocated in the heap, containing the + * constraint value and already inserted into either the FixParameters or + * Parameters array, as the case may be. + */ + int addCoordinateXConstraint(int geoId, PointPos pos, double* value, bool driving = true); /** - * add a fixed Y coordinate constraint to a point - * - * double * value is a pointer to double allocated in the heap, containing the - * constraint value and already inserted into either the FixParameters or - * Parameters array, as the case may be. - */ - int addCoordinateYConstraint(int geoId, PointPos pos, double * value, bool driving = true); + * add a fixed Y coordinate constraint to a point + * + * double * value is a pointer to double allocated in the heap, containing the + * constraint value and already inserted into either the FixParameters or + * Parameters array, as the case may be. + */ + int addCoordinateYConstraint(int geoId, PointPos pos, double* value, bool driving = true); /** - * add a horizontal distance constraint to two points or line ends - * - * double * value is a pointer to double allocated in the heap, containing the - * constraint value and already inserted into either the FixParameters or - * Parameters array, as the case may be. - */ - int addDistanceXConstraint(int geoId, double * value, bool driving = true); + * add a horizontal distance constraint to two points or line ends + * + * double * value is a pointer to double allocated in the heap, containing the + * constraint value and already inserted into either the FixParameters or + * Parameters array, as the case may be. + */ + int addDistanceXConstraint(int geoId, double* value, bool driving = true); /** - * add a horizontal distance constraint to two points or line ends - * - * double * value is a pointer to double allocated in the heap, containing the - * constraint value and already inserted into either the FixParameters or - * Parameters array, as the case may be. - */ - int addDistanceXConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, double * value, bool driving = true); + * add a horizontal distance constraint to two points or line ends + * + * double * value is a pointer to double allocated in the heap, containing the + * constraint value and already inserted into either the FixParameters or + * Parameters array, as the case may be. + */ + int addDistanceXConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, double* value, + bool driving = true); /** - * add a vertical distance constraint to two points or line ends - * - * double * value is a pointer to double allocated in the heap, containing the - * constraint value and already inserted into either the FixParameters or - * Parameters array, as the case may be. - */ - int addDistanceYConstraint(int geoId, double * value, bool driving = true); + * add a vertical distance constraint to two points or line ends + * + * double * value is a pointer to double allocated in the heap, containing the + * constraint value and already inserted into either the FixParameters or + * Parameters array, as the case may be. + */ + int addDistanceYConstraint(int geoId, double* value, bool driving = true); /** - * add a vertical distance constraint to two points or line ends - * - * double * value is a pointer to double allocated in the heap, containing the - * constraint value and already inserted into either the FixParameters or - * Parameters array, as the case may be. - */ - int addDistanceYConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, double * value, bool driving = true); + * add a vertical distance constraint to two points or line ends + * + * double * value is a pointer to double allocated in the heap, containing the + * constraint value and already inserted into either the FixParameters or + * Parameters array, as the case may be. + */ + int addDistanceYConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, double* value, + bool driving = true); /// add a horizontal constraint to a geometry int addHorizontalConstraint(int geoId); int addHorizontalConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2); @@ -253,37 +292,39 @@ public: /// add a coincident constraint to two points of two geometries int addPointCoincidentConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2); /** - * add a length or distance constraint - * - * double * value is a pointer to double allocated in the heap, containing the - * constraint value and already inserted into either the FixParameters or - * Parameters array, as the case may be. - */ - int addDistanceConstraint(int geoId1, double * value, bool driving = true); + * add a length or distance constraint + * + * double * value is a pointer to double allocated in the heap, containing the + * constraint value and already inserted into either the FixParameters or + * Parameters array, as the case may be. + */ + int addDistanceConstraint(int geoId1, double* value, bool driving = true); /** - * add a length or distance constraint - * - * double * value is a pointer to double allocated in the heap, containing the - * constraint value and already inserted into either the FixParameters or - * Parameters array, as the case may be. - */ - int addDistanceConstraint(int geoId1, PointPos pos1, int geoId2, double * value, bool driving = true); + * add a length or distance constraint + * + * double * value is a pointer to double allocated in the heap, containing the + * constraint value and already inserted into either the FixParameters or + * Parameters array, as the case may be. + */ + int addDistanceConstraint(int geoId1, PointPos pos1, int geoId2, double* value, + bool driving = true); /** - * add a length or distance constraint - * - * double * value is a pointer to double allocated in the heap, containing the - * constraint value and already inserted into either the FixParameters or - * Parameters array, as the case may be. - */ - int addDistanceConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, double * value, bool driving = true); + * add a length or distance constraint + * + * double * value is a pointer to double allocated in the heap, containing the + * constraint value and already inserted into either the FixParameters or + * Parameters array, as the case may be. + */ + int addDistanceConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, double* value, + bool driving = true); /** - * add a length or distance constraint - * - * double * value is a pointer to double allocated in the heap, containing the - * constraint value and already inserted into either the FixParameters or - * Parameters array, as the case may be. - */ - int addDistanceConstraint(int geoId1, int geoId2, double * value, bool driving = true); + * add a length or distance constraint + * + * double * value is a pointer to double allocated in the heap, containing the + * constraint value and already inserted into either the FixParameters or + * Parameters array, as the case may be. + */ + int addDistanceConstraint(int geoId1, int geoId2, double* value, bool driving = true); /// add a parallel constraint between two lines int addParallelConstraint(int geoId1, int geoId2); @@ -291,22 +332,14 @@ public: int addPerpendicularConstraint(int geoId1, int geoId2); /// add a tangency constraint between two geometries int addTangentConstraint(int geoId1, int geoId2); - int addTangentLineAtBSplineKnotConstraint(int checkedlinegeoId, int checkedbsplinegeoId, int checkedknotgeoid); - int addTangentLineEndpointAtBSplineKnotConstraint(int checkedlinegeoId, PointPos endpointPos, int checkedbsplinegeoId, int checkedknotgeoid); - int addAngleAtPointConstraint( - int geoId1, PointPos pos1, - int geoId2, PointPos pos2, - int geoId3, PointPos pos3, - double * value, - ConstraintType cTyp, bool driving = true); - /** - * add a radius constraint on a circle or an arc - * - * double * value is a pointer to double allocated in the heap, containing the - * constraint value and already inserted into either the FixParameters or - * Parameters array, as the case may be. - */ - int addRadiusConstraint(int geoId, double * value, bool driving = true); + int addTangentLineAtBSplineKnotConstraint(int checkedlinegeoId, int checkedbsplinegeoId, + int checkedknotgeoid); + int addTangentLineEndpointAtBSplineKnotConstraint(int checkedlinegeoId, PointPos endpointPos, + int checkedbsplinegeoId, + int checkedknotgeoid); + int addAngleAtPointConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, int geoId3, + PointPos pos3, double* value, ConstraintType cTyp, + bool driving = true); /** * add a radius constraint on a circle or an arc * @@ -314,65 +347,75 @@ public: * constraint value and already inserted into either the FixParameters or * Parameters array, as the case may be. */ - int addDiameterConstraint(int geoId, double * value, bool driving = true); + int addRadiusConstraint(int geoId, double* value, bool driving = true); /** - * add an angle constraint on a line or between two lines - * - * double * value is a pointer to double allocated in the heap, containing the - * constraint value and already inserted into either the FixParameters or - * Parameters array, as the case may be. - */ - int addAngleConstraint(int geoId, double * value, bool driving = true); + * add a radius constraint on a circle or an arc + * + * double * value is a pointer to double allocated in the heap, containing the + * constraint value and already inserted into either the FixParameters or + * Parameters array, as the case may be. + */ + int addDiameterConstraint(int geoId, double* value, bool driving = true); /** - * add an angle constraint on a line or between two lines - * - * double * value is a pointer to double allocated in the heap, containing the - * constraint value and already inserted into either the FixParameters or - * Parameters array, as the case may be. - */ - int addAngleConstraint(int geoId1, int geoId2, double * value, bool driving = true); + * add an angle constraint on a line or between two lines + * + * double * value is a pointer to double allocated in the heap, containing the + * constraint value and already inserted into either the FixParameters or + * Parameters array, as the case may be. + */ + int addAngleConstraint(int geoId, double* value, bool driving = true); /** - * add an angle constraint on a line or between two lines - * - * double * value is a pointer to double allocated in the heap, containing the - * constraint value and already inserted into either the FixParameters or - * Parameters array, as the case may be. - */ - int addAngleConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, double * value, bool driving = true); + * add an angle constraint on a line or between two lines + * + * double * value is a pointer to double allocated in the heap, containing the + * constraint value and already inserted into either the FixParameters or + * Parameters array, as the case may be. + */ + int addAngleConstraint(int geoId1, int geoId2, double* value, bool driving = true); /** - * add angle-via-point constraint between any two curves - * - * double * value is a pointer to double allocated in the heap, containing the - * constraint value and already inserted into either the FixParameters or - * Parameters array, as the case may be. - */ - int addAngleViaPointConstraint(int geoId1, int geoId2, int geoId3, PointPos pos3, double value, bool driving = true); + * add an angle constraint on a line or between two lines + * + * double * value is a pointer to double allocated in the heap, containing the + * constraint value and already inserted into either the FixParameters or + * Parameters array, as the case may be. + */ + int addAngleConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, double* value, + bool driving = true); + /** + * add angle-via-point constraint between any two curves + * + * double * value is a pointer to double allocated in the heap, containing the + * constraint value and already inserted into either the FixParameters or + * Parameters array, as the case may be. + */ + int addAngleViaPointConstraint(int geoId1, int geoId2, int geoId3, PointPos pos3, double value, + bool driving = true); /// add an equal length or radius constraints between two lines or between circles and arcs int addEqualConstraint(int geoId1, int geoId2); /// add a point on line constraint int addPointOnObjectConstraint(int geoId1, PointPos pos1, int geoId2, bool driving = true); /// add a point on B-spline constraint: needs a parameter - int addPointOnObjectConstraint(int geoId1, PointPos pos1, int geoId2,double* pointparam, bool driving = true); + int addPointOnObjectConstraint(int geoId1, PointPos pos1, int geoId2, double* pointparam, + bool driving = true); /// add a symmetric constraint between two points with respect to a line int addSymmetricConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, int geoId3); - /// add a symmetric constraint between three points, the last point is in the middle of the first two - int addSymmetricConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, int geoId3, PointPos pos3); + /// add a symmetric constraint between three points, the last point is in the middle of the + /// first two + int addSymmetricConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, int geoId3, + PointPos pos3); /** - * add a snell's law constraint - * - * double * value and double * second are each a pointer to double - * allocated in the heap and already inserted into either the - * FixParameters or Parameters array, as the case may be. - * - * value must contain the constraint value (the ratio of n2/n1) - * second may be initialized to any value, however the solver will - * provide n1 in value and n2 in second. - */ - int addSnellsLawConstraint(int geoIdRay1, PointPos posRay1, - int geoIdRay2, PointPos posRay2, - int geoIdBnd, - double * value, - double * second, bool driving = true); + * add a snell's law constraint + * + * double * value and double * second are each a pointer to double + * allocated in the heap and already inserted into either the + * FixParameters or Parameters array, as the case may be. + * + * value must contain the constraint value (the ratio of n2/n1) + * second may be initialized to any value, however the solver will + * provide n1 in value and n2 in second. + */ + int addSnellsLawConstraint(int geoIdRay1, PointPos posRay1, int geoIdRay2, PointPos posRay2, + int geoIdBnd, double* value, double* second, bool driving = true); //@} /// Internal Alignment constraints @@ -392,29 +435,37 @@ public: int addInternalAlignmentKnotPoint(int geoId1, int geoId2, int knotindex); //@} public: - //This func is to be used during angle-via-point constraint creation. It calculates - //the angle between geoId1,geoId2 at point px,py. The point should be on both curves, - //otherwise the result will be systematically off (but smoothly approach the correct - //value as the point approaches intersection of curves). - double calculateAngleViaPoint(int geoId1, int geoId2, double px, double py ); + // This func is to be used during angle-via-point constraint creation. It calculates + // the angle between geoId1,geoId2 at point px,py. The point should be on both curves, + // otherwise the result will be systematically off (but smoothly approach the correct + // value as the point approaches intersection of curves). + double calculateAngleViaPoint(int geoId1, int geoId2, double px, double py); - //This is to be used for rendering of angle-via-point constraint. + // This is to be used for rendering of angle-via-point constraint. Base::Vector3d calculateNormalAtPoint(int geoIdCurve, double px, double py) const; - //icstr should be the value returned by addXXXXConstraint - //see more info in respective function in GCS. - double calculateConstraintError(int icstr) { return GCSsys.calculateConstraintErrorByTag(icstr);} + // icstr should be the value returned by addXXXXConstraint + // see more info in respective function in GCS. + double calculateConstraintError(int icstr) + { + return GCSsys.calculateConstraintErrorByTag(icstr); + } /// Returns the size of the Geometry - int getGeometrySize() const {return Geoms.size();} + int getGeometrySize() const + { + return Geoms.size(); + } - enum GeoType { - None = 0, - Point = 1, // 1 Point(start), 2 Parameters(x,y) - Line = 2, // 2 Points(start,end), 4 Parameters(x1,y1,x2,y2) - Arc = 3, // 3 Points(start,end,mid), (4)+5 Parameters((x1,y1,x2,y2),x,y,r,a1,a2) - Circle = 4, // 1 Point(mid), 3 Parameters(x,y,r) - Ellipse = 5, // 1 Point(mid), 5 Parameters(x,y,r1,r2,phi) phi=angle xaxis of ellipse with respect of sketch xaxis + enum GeoType + { + None = 0, + Point = 1, // 1 Point(start), 2 Parameters(x,y) + Line = 2, // 2 Points(start,end), 4 Parameters(x1,y1,x2,y2) + Arc = 3, // 3 Points(start,end,mid), (4)+5 Parameters((x1,y1,x2,y2),x,y,r,a1,a2) + Circle = 4, // 1 Point(mid), 3 Parameters(x,y,r) + Ellipse = 5,// 1 Point(mid), 5 Parameters(x,y,r1,r2,phi) + // phi=angle xaxis of ellipse with respect of sketch xaxis ArcOfEllipse = 6, ArcOfHyperbola = 7, ArcOfParabola = 8, @@ -425,33 +476,45 @@ protected: float SolveTime; bool RecalculateInitialSolutionWhileMovingPoint; - // regulates a second solve for cases where there result of having update the geometry (e.g. via OCCT) - // needs to be taken into account by the solver (for example to provide the right value of non-driving constraints) + // regulates a second solve for cases where there result of having update the geometry (e.g. via + // OCCT) needs to be taken into account by the solver (for example to provide the right value of + // non-driving constraints) bool resolveAfterGeometryUpdated; protected: /// container element to store and work with the geometric elements of this sketch - struct GeoDef { - GeoDef() : geo(nullptr),type(None),external(false),index(-1), - startPointId(-1),midPointId(-1),endPointId(-1) {} - Part::Geometry * geo; // pointer to the geometry - GeoType type; // type of the geometry - bool external; // flag for external geometries - int index; // index in the corresponding storage vector (Lines, Arcs, Circles, ...) - int startPointId; // index in Points of the start point of this geometry - int midPointId; // index in Points of the start point of this geometry - int endPointId; // index in Points of the end point of this geometry + struct GeoDef + { + GeoDef() + : geo(nullptr), + type(None), + external(false), + index(-1), + startPointId(-1), + midPointId(-1), + endPointId(-1) + {} + Part::Geometry* geo;// pointer to the geometry + GeoType type; // type of the geometry + bool external; // flag for external geometries + int index; // index in the corresponding storage vector (Lines, Arcs, Circles, ...) + int startPointId; // index in Points of the start point of this geometry + int midPointId; // index in Points of the start point of this geometry + int endPointId; // index in Points of the end point of this geometry }; /// container element to store and work with the constraints of this sketch - struct ConstrDef { - ConstrDef() : constr(nullptr) - , driving(true) - , value(nullptr) - , secondvalue(nullptr) {} - Constraint * constr; // pointer to the constraint - bool driving; - double * value; - double * secondvalue; // this is needed for SnellsLaw + struct ConstrDef + { + ConstrDef() + : constr(nullptr), + driving(true), + value(nullptr), + secondvalue(nullptr) + {} + Constraint* constr;// pointer to the constraint + bool driving; + double* value; + double* secondvalue;// this is needed for SnellsLaw }; std::vector Geoms; @@ -463,27 +526,30 @@ protected: std::vector PartiallyRedundant; std::vector MalformedConstraints; - std::vector pDependentParametersList; + std::vector pDependentParametersList; - // map of geoIds to corresponding solverextensions. This is useful when solved geometry is NOT to be assigned to the SketchObject + // map of geoIds to corresponding solverextensions. This is useful when solved geometry is NOT + // to be assigned to the SketchObject std::vector> solverExtensions; - // maps a geoid corresponding to an internalgeometry (focus,knot,pole) to the geometry it defines (ellipse, hyperbola, B-Spline) - std::map< int, int > internalAlignmentGeometryMap; + // maps a geoid corresponding to an internalgeometry (focus,knot,pole) to the geometry it + // defines (ellipse, hyperbola, B-Spline) + std::map internalAlignmentGeometryMap; - std::vector < std::set < std::pair< int, Sketcher::PointPos>>> pDependencyGroups; + std::vector>> pDependencyGroups; - // this map is intended to convert a parameter (double *) into a GeoId/PointPos and parameter number - std::map> param2geoelement; + // this map is intended to convert a parameter (double *) into a GeoId/PointPos and parameter + // number + std::map> param2geoelement; // solving parameters - std::vector Parameters; // with memory allocation - std::vector DrivenParameters; // with memory allocation - std::vector FixParameters; // with memory allocation + std::vector Parameters; // with memory allocation + std::vector DrivenParameters;// with memory allocation + std::vector FixParameters; // with memory allocation std::vector MoveParameters, InitParameters; - std::vector Points; - std::vector Lines; - std::vector Arcs; + std::vector Points; + std::vector Lines; + std::vector Arcs; std::vector Circles; std::vector Ellipses; std::vector ArcsOfEllipse; @@ -499,36 +565,108 @@ protected: public: GCS::Algorithm defaultSolver; GCS::Algorithm defaultSolverRedundant; - inline void setDogLegGaussStep(GCS::DogLegGaussStep mode){GCSsys.dogLegGaussStep=mode;} - inline void setDebugMode(GCS::DebugMode mode) {debugMode=mode;GCSsys.debugMode=mode;} - inline GCS::DebugMode getDebugMode() {return debugMode;} - inline void setMaxIter(int maxiter){GCSsys.maxIter=maxiter;} - inline void setMaxIterRedundant(int maxiter){GCSsys.maxIterRedundant=maxiter;} - inline void setSketchSizeMultiplier(bool mult){GCSsys.sketchSizeMultiplier=mult;} - inline void setSketchSizeMultiplierRedundant(bool mult){GCSsys.sketchSizeMultiplierRedundant=mult;} - inline void setConvergence(double conv){GCSsys.convergence=conv;} - inline void setConvergenceRedundant(double conv){GCSsys.convergenceRedundant=conv;} - inline void setQRAlgorithm(GCS::QRAlgorithm alg){GCSsys.qrAlgorithm=alg;} - inline GCS::QRAlgorithm getQRAlgorithm(){return GCSsys.qrAlgorithm;} - inline void setQRPivotThreshold(double val){GCSsys.qrpivotThreshold=val;} - inline void setLM_eps(double val){GCSsys.LM_eps=val;} - inline void setLM_eps1(double val){GCSsys.LM_eps1=val;} - inline void setLM_tau(double val){GCSsys.LM_tau=val;} - inline void setDL_tolg(double val){GCSsys.DL_tolg=val;} - inline void setDL_tolx(double val){GCSsys.DL_tolx=val;} - inline void setDL_tolf(double val){GCSsys.DL_tolf=val;} - inline void setLM_epsRedundant(double val){GCSsys.LM_epsRedundant=val;} - inline void setLM_eps1Redundant(double val){GCSsys.LM_eps1Redundant=val;} - inline void setLM_tauRedundant(double val){GCSsys.LM_tauRedundant=val;} - inline void setDL_tolgRedundant(double val){GCSsys.DL_tolgRedundant=val;} - inline void setDL_tolxRedundant(double val){GCSsys.DL_tolxRedundant=val;} - inline void setDL_tolfRedundant(double val){GCSsys.DL_tolfRedundant=val;} + inline void setDogLegGaussStep(GCS::DogLegGaussStep mode) + { + GCSsys.dogLegGaussStep = mode; + } + inline void setDebugMode(GCS::DebugMode mode) + { + debugMode = mode; + GCSsys.debugMode = mode; + } + inline GCS::DebugMode getDebugMode() + { + return debugMode; + } + inline void setMaxIter(int maxiter) + { + GCSsys.maxIter = maxiter; + } + inline void setMaxIterRedundant(int maxiter) + { + GCSsys.maxIterRedundant = maxiter; + } + inline void setSketchSizeMultiplier(bool mult) + { + GCSsys.sketchSizeMultiplier = mult; + } + inline void setSketchSizeMultiplierRedundant(bool mult) + { + GCSsys.sketchSizeMultiplierRedundant = mult; + } + inline void setConvergence(double conv) + { + GCSsys.convergence = conv; + } + inline void setConvergenceRedundant(double conv) + { + GCSsys.convergenceRedundant = conv; + } + inline void setQRAlgorithm(GCS::QRAlgorithm alg) + { + GCSsys.qrAlgorithm = alg; + } + inline GCS::QRAlgorithm getQRAlgorithm() + { + return GCSsys.qrAlgorithm; + } + inline void setQRPivotThreshold(double val) + { + GCSsys.qrpivotThreshold = val; + } + inline void setLM_eps(double val) + { + GCSsys.LM_eps = val; + } + inline void setLM_eps1(double val) + { + GCSsys.LM_eps1 = val; + } + inline void setLM_tau(double val) + { + GCSsys.LM_tau = val; + } + inline void setDL_tolg(double val) + { + GCSsys.DL_tolg = val; + } + inline void setDL_tolx(double val) + { + GCSsys.DL_tolx = val; + } + inline void setDL_tolf(double val) + { + GCSsys.DL_tolf = val; + } + inline void setLM_epsRedundant(double val) + { + GCSsys.LM_epsRedundant = val; + } + inline void setLM_eps1Redundant(double val) + { + GCSsys.LM_eps1Redundant = val; + } + inline void setLM_tauRedundant(double val) + { + GCSsys.LM_tauRedundant = val; + } + inline void setDL_tolgRedundant(double val) + { + GCSsys.DL_tolgRedundant = val; + } + inline void setDL_tolxRedundant(double val) + { + GCSsys.DL_tolxRedundant = val; + } + inline void setDL_tolfRedundant(double val) + { + GCSsys.DL_tolfRedundant = val; + } protected: GCS::DebugMode debugMode; private: - bool updateGeometry(); bool updateNonDrivingConstraints(); @@ -536,9 +674,9 @@ private: void clearTemporaryConstraints(); - void buildInternalAlignmentGeometryMap(const std::vector &constraintList); + void buildInternalAlignmentGeometryMap(const std::vector& constraintList); - int internalSolve(std::string & solvername, int level = 0); + int internalSolve(std::string& solvername, int level = 0); /// checks if the index bounds and converts negative indices to positive int checkGeoId(int geoId) const; @@ -555,63 +693,71 @@ private: * * This is important because 1) can be pre-fixed when creating geometry and constraints * before GCS::diagnose() via initSolution(). This is important because if no other constraint - * affect the geometry, the geometry parameters won't even appear in the Jacobian, and they won't - * be reported as dependent parameters. + * affect the geometry, the geometry parameters won't even appear in the Jacobian, and they + * won't be reported as dependent parameters. * - * On the contrary 2) cannot be pre-fixed because it would lead to redundant constraints and requires - * a post-analysis, see analyseBlockedConstraintDependentParameters, to fix just the parameters that - * fulfil the dependacy groups. + * On the contrary 2) cannot be pre-fixed because it would lead to redundant constraints and + * requires a post-analysis, see analyseBlockedConstraintDependentParameters, to fix just the + * parameters that fulfil the dependacy groups. */ - bool analyseBlockedGeometry( const std::vector &internalGeoList, - const std::vector &constraintList, - std::vector &onlyblockedGeometry, - std::vector &blockedGeoIds) const; + bool analyseBlockedGeometry(const std::vector& internalGeoList, + const std::vector& constraintList, + std::vector& onlyblockedGeometry, + std::vector& blockedGeoIds) const; - /* This function performs a post-analysis of blocked geometries (see analyseBlockedGeometry for more detail - * on the pre-analysis). + /* This function performs a post-analysis of blocked geometries (see analyseBlockedGeometry for + * more detail on the pre-analysis). * - * Basically identifies which parameters shall be fixed to make geometries having blocking constraints fixed, - * while not leading to redundant/conflicting constraints. These parameters must belong to blocked geometry. This - * is, groups may comprise parameters belonging to blocked geometry and parameters belonging to unconstrained geometry. - * It is licit that the latter remain as dependent parameters. The former are referred to as "blockable parameters". + * Basically identifies which parameters shall be fixed to make geometries having blocking + * constraints fixed, while not leading to redundant/conflicting constraints. These parameters + * must belong to blocked geometry. This is, groups may comprise parameters belonging to blocked + * geometry and parameters belonging to unconstrained geometry. It is licit that the latter + * remain as dependent parameters. The former are referred to as "blockable parameters". * - * Extending this concept, there may be unsatisfiable groups (because they do not comprise any bloackable parameter), - * and it is the desired outcome NOT to satisfy such groups. + * Extending this concept, there may be unsatisfiable groups (because they do not comprise any + * bloackable parameter), and it is the desired outcome NOT to satisfy such groups. * - * There is not a single combination of fixed parameters from the blockable parameters that satisfy all the dependency - * groups. However: + * There is not a single combination of fixed parameters from the blockable parameters that + * satisfy all the dependency groups. However: * - * 1) some combinations do not satisfy all the dependency groups that must be satisfied (e.g. fixing one - * group containing two blockable parameters with a given one may result in another group, fixable only by the former, not - * to be satisfied). This leads, in a subsequent diagnosis, to satisfiable unsatisfied groups. + * 1) some combinations do not satisfy all the dependency groups that must be satisfied (e.g. + * fixing one group containing two blockable parameters with a given one may result in another + * group, fixable only by the former, not to be satisfied). This leads, in a subsequent + * diagnosis, to satisfiable unsatisfied groups. * - * 2) some combinations lead to partially redundant constraints, that the solver will silently drop in a subsequent diagnosis, - * thereby reducing the rank of the system fixing less than it should. + * 2) some combinations lead to partially redundant constraints, that the solver will silently + * drop in a subsequent diagnosis, thereby reducing the rank of the system fixing less than it + * should. * * Implementation rationale (at this time): * - * The implementation is on the order of the groups provided by the QR decomposition used to reveal the parameters - * (see System::identifyDependentParameters in GCS). Zeros are made over the pilot of the full R matrix of the QR decomposition, - * which is a top triangular matrix.This, together with the permutation matrix, allow to know groups of dependent parameters - * (cols between rank and full size). Each group refers to a new parameter not affected by the rank in combination with other free - * parameters intervening in the rank (because of the triangular shape of the R matrix). This results in that each the first column - * between the rank and the full size, may only depend on a number of parameters, while the last full size column may be dependent on - * any amount of previously introduced parameters. + * The implementation is on the order of the groups provided by the QR decomposition used to + * reveal the parameters (see System::identifyDependentParameters in GCS). Zeros are made over + * the pilot of the full R matrix of the QR decomposition, which is a top triangular + * matrix.This, together with the permutation matrix, allow to know groups of dependent + * parameters (cols between rank and full size). Each group refers to a new parameter not + * affected by the rank in combination with other free parameters intervening in the rank + * (because of the triangular shape of the R matrix). This results in that each the first column + * between the rank and the full size, may only depend on a number of parameters, while the last + * full size column may be dependent on any amount of previously introduced parameters. * - * Thus the rationale is: start from the last group (having **potentially** the larger amount of parameters) and selecting as blocking - * for that group the latest blockable parameter. Because previous groups do not have access to the last parameter, this can never - * interfere with previous groups. However, because the last parameter may not be a blockable one, there is a risk of selecting a parameter - * common with other group, albeit the probability is reduced and probably (I have not demonstrated it though and I am not sure), it leads - * to the right solution in one iteration. + * Thus the rationale is: start from the last group (having **potentially** the larger amount of + * parameters) and selecting as blocking for that group the latest blockable parameter. Because + * previous groups do not have access to the last parameter, this can never interfere with + * previous groups. However, because the last parameter may not be a blockable one, there is a + * risk of selecting a parameter common with other group, albeit the probability is reduced and + * probably (I have not demonstrated it though and I am not sure), it leads to the right + * solution in one iteration. * */ - bool analyseBlockedConstraintDependentParameters(std::vector &blockedGeoIds, std::vector ¶ms_to_block) const; + bool analyseBlockedConstraintDependentParameters(std::vector& blockedGeoIds, + std::vector& params_to_block) const; /// utility function refactoring fixing the provided parameters and running a new diagnose - void fixParametersAndDiagnose(std::vector ¶ms_to_block); + void fixParametersAndDiagnose(std::vector& params_to_block); }; -} //namespace Part +}// namespace Sketcher -#endif // SKETCHER_SKETCH_H +#endif// SKETCHER_SKETCH_H diff --git a/src/Mod/Sketcher/App/SketchAnalysis.cpp b/src/Mod/Sketcher/App/SketchAnalysis.cpp index 031cdbbc92..84c530cb9c 100644 --- a/src/Mod/Sketcher/App/SketchAnalysis.cpp +++ b/src/Mod/Sketcher/App/SketchAnalysis.cpp @@ -23,40 +23,37 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include #endif #include #include -#include "SketchAnalysis.h" #include "GeometryFacade.h" +#include "SketchAnalysis.h" #include "SketchObject.h" using namespace Sketcher; SketchAnalysis::SketchAnalysis(Sketcher::SketchObject* Obj) - : sketch(Obj) -{ - -} + : sketch(Obj) +{} SketchAnalysis::~SketchAnalysis() +{} + +struct SketchAnalysis::VertexIds { - -} - -struct SketchAnalysis::VertexIds { Base::Vector3d v; int GeoId; Sketcher::PointPos PosId; @@ -64,98 +61,108 @@ struct SketchAnalysis::VertexIds { struct SketchAnalysis::Vertex_Less { - explicit Vertex_Less(double tolerance) : tolerance(tolerance){} - bool operator()(const VertexIds& x, - const VertexIds& y) const + explicit Vertex_Less(double tolerance) + : tolerance(tolerance) + {} + bool operator()(const VertexIds& x, const VertexIds& y) const { - if (fabs (x.v.x - y.v.x) > tolerance) + if (fabs(x.v.x - y.v.x) > tolerance) return x.v.x < y.v.x; - if (fabs (x.v.y - y.v.y) > tolerance) + if (fabs(x.v.y - y.v.y) > tolerance) return x.v.y < y.v.y; - if (fabs (x.v.z - y.v.z) > tolerance) + if (fabs(x.v.z - y.v.z) > tolerance) return x.v.z < y.v.z; - return false; // points are considered to be equal + return false;// points are considered to be equal } + private: double tolerance; }; struct SketchAnalysis::VertexID_Less { - bool operator()(const VertexIds& x, - const VertexIds& y) const + bool operator()(const VertexIds& x, const VertexIds& y) const { - return (x.GeoId < y.GeoId || ((x.GeoId == y.GeoId) && (x.PosId < y. PosId))); + return (x.GeoId < y.GeoId || ((x.GeoId == y.GeoId) && (x.PosId < y.PosId))); } }; struct SketchAnalysis::Vertex_EqualTo { - explicit Vertex_EqualTo(double tolerance) : tolerance(tolerance){} - bool operator()(const VertexIds& x, - const VertexIds& y) const + explicit Vertex_EqualTo(double tolerance) + : tolerance(tolerance) + {} + bool operator()(const VertexIds& x, const VertexIds& y) const { - if (fabs (x.v.x - y.v.x) <= tolerance) { - if (fabs (x.v.y - y.v.y) <= tolerance) { - if (fabs (x.v.z - y.v.z) <= tolerance) { + if (fabs(x.v.x - y.v.x) <= tolerance) { + if (fabs(x.v.y - y.v.y) <= tolerance) { + if (fabs(x.v.z - y.v.z) <= tolerance) { return true; } } } return false; } + private: double tolerance; }; -struct SketchAnalysis::EdgeIds { +struct SketchAnalysis::EdgeIds +{ double l; int GeoId; }; struct SketchAnalysis::Edge_Less { - explicit Edge_Less(double tolerance) : tolerance(tolerance){} - bool operator()(const EdgeIds& x, - const EdgeIds& y) const - { - if (fabs (x.l - y.l) > tolerance) - return x.l < y.l; - return false; // points are considered to be equal - } + explicit Edge_Less(double tolerance) + : tolerance(tolerance) + {} + bool operator()(const EdgeIds& x, const EdgeIds& y) const + { + if (fabs(x.l - y.l) > tolerance) + return x.l < y.l; + return false;// points are considered to be equal + } + private: double tolerance; }; struct SketchAnalysis::Edge_EqualTo { - explicit Edge_EqualTo(double tolerance) : tolerance(tolerance){} - bool operator()(const EdgeIds& x, - const EdgeIds& y) const - { - if (fabs (x.l - y.l) <= tolerance) { - return true; - } - return false; - } + explicit Edge_EqualTo(double tolerance) + : tolerance(tolerance) + {} + bool operator()(const EdgeIds& x, const EdgeIds& y) const + { + if (fabs(x.l - y.l) <= tolerance) { + return true; + } + return false; + } + private: double tolerance; }; -int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, bool includeconstruction /*=true*/) +int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, + bool includeconstruction /*=true*/) { - std::vector vertexIds; // Holds a list of all vertices in the sketch + std::vector vertexIds;// Holds a list of all vertices in the sketch // Build the list of sketch vertices - const std::vector& geom = sketch->getInternalGeometry(); - for (std::size_t i=0; i& geom = sketch->getInternalGeometry(); + for (std::size_t i = 0; i < geom.size(); i++) { auto gf = GeometryFacade::getFacade(geom[i]); - if(gf->getConstruction() && !includeconstruction) + if (gf->getConstruction() && !includeconstruction) continue; if (gf->getGeometry()->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *segm = static_cast(gf->getGeometry()); + const Part::GeomLineSegment* segm = + static_cast(gf->getGeometry()); VertexIds id; id.GeoId = (int)i; id.PosId = Sketcher::PointPos::start; @@ -167,7 +174,8 @@ int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, bool vertexIds.push_back(id); } else if (gf->getGeometry()->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *segm = static_cast(gf->getGeometry()); + const Part::GeomArcOfCircle* segm = + static_cast(gf->getGeometry()); VertexIds id; id.GeoId = (int)i; id.PosId = Sketcher::PointPos::start; @@ -179,7 +187,8 @@ int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, bool vertexIds.push_back(id); } else if (gf->getGeometry()->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { - const Part::GeomArcOfEllipse *segm = static_cast(gf->getGeometry()); + const Part::GeomArcOfEllipse* segm = + static_cast(gf->getGeometry()); VertexIds id; id.GeoId = (int)i; id.PosId = Sketcher::PointPos::start; @@ -191,7 +200,8 @@ int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, bool vertexIds.push_back(id); } else if (gf->getGeometry()->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { - const Part::GeomArcOfHyperbola *segm = static_cast(gf->getGeometry()); + const Part::GeomArcOfHyperbola* segm = + static_cast(gf->getGeometry()); VertexIds id; id.GeoId = (int)i; id.PosId = Sketcher::PointPos::start; @@ -203,7 +213,8 @@ int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, bool vertexIds.push_back(id); } else if (gf->getGeometry()->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { - const Part::GeomArcOfParabola *segm = static_cast(gf->getGeometry()); + const Part::GeomArcOfParabola* segm = + static_cast(gf->getGeometry()); VertexIds id; id.GeoId = (int)i; id.PosId = Sketcher::PointPos::start; @@ -215,7 +226,8 @@ int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, bool vertexIds.push_back(id); } else if (gf->getGeometry()->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { - const Part::GeomBSplineCurve *segm = static_cast(gf->getGeometry()); + const Part::GeomBSplineCurve* segm = + static_cast(gf->getGeometry()); VertexIds id; id.GeoId = (int)i; id.PosId = Sketcher::PointPos::start; @@ -229,22 +241,22 @@ int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, bool // TODO take into account single vertices ? } - std::sort(vertexIds.begin(), vertexIds.end(), Vertex_Less(precision)); // Sort points in geographic order + // Sort points in geographic order + std::sort(vertexIds.begin(), vertexIds.end(), Vertex_Less(precision)); // Build a list of all coincidence in the sketch std::vector coincidences = sketch->Constraints.getValues(); - for (auto &constraint:sketch->Constraints.getValues()) { - if (constraint->Type == Sketcher::Coincident || - constraint->Type == Sketcher::Tangent || - constraint->Type == Sketcher::Perpendicular) { + for (auto& constraint : sketch->Constraints.getValues()) { + if (constraint->Type == Sketcher::Coincident || constraint->Type == Sketcher::Tangent + || constraint->Type == Sketcher::Perpendicular) { coincidences.push_back(constraint); } // TODO optimizing by removing constraints not applying on vertices ? } - std::list missingCoincidences; //Holds the list of missing coincidences + std::list missingCoincidences;// Holds the list of missing coincidences std::vector::iterator vt = vertexIds.begin(); Vertex_EqualTo pred(precision); @@ -254,13 +266,14 @@ int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, bool while (vt < vertexIds.end()) { // Seeking for adjacent group of vertices vt = std::adjacent_find(vt, vertexIds.end(), pred); - if (vt < vertexIds.end()) { // If one found + if (vt < vertexIds.end()) {// If one found std::vector::iterator vn; - std::set vertexGrp; // Holds a single group of adjacent vertices + // Holds a single group of adjacent vertices + std::set vertexGrp; // Extract the group of adjacent vertices vertexGrp.insert(*vt); - for (vn = vt+1; vn < vertexIds.end(); ++vn) { - if (pred(*vt,*vn)) { + for (vn = vt + 1; vn < vertexIds.end(); ++vn) { + if (pred(*vt, *vn)) { vertexGrp.insert(*vn); } else { @@ -268,10 +281,12 @@ int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, bool } } - std::vector> coincVertexGrps; // Holds groups of coincident vertices + // Holds groups of coincident vertices + std::vector> coincVertexGrps; // Decompose the group of adjacent vertices into groups of coincident vertices - for (auto &coincidence:coincidences) { // Going through existent coincidences + // Going through existent coincidences + for (auto& coincidence : coincidences) { VertexIds v1, v2; v1.GeoId = coincidence->First; v1.PosId = coincidence->FirstPos; @@ -285,9 +300,9 @@ int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, bool // Maybe if both empty, they already have been extracted by other coincidences // We have to check in existing coincident groups and eventually merge if (nv1.empty() && nv2.empty()) { - std::set *tempGrp = nullptr; + std::set* tempGrp = nullptr; for (auto it = coincVertexGrps.begin(); it < coincVertexGrps.end(); ++it) { - if ( (it->find(v1) != it->end()) || (it->find(v2) != it->end()) ) { + if ((it->find(v1) != it->end()) || (it->find(v2) != it->end())) { if (!tempGrp) { tempGrp = &*it; } @@ -301,17 +316,21 @@ int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, bool continue; } - // Look if one of the constrained vertices is already in a group of coincident vertices - for (std::set &grp:coincVertexGrps) { - if ( (grp.find(v1) != grp.end()) || (grp.find(v2) != grp.end()) ) { + // Look if one of the constrained vertices is already in a group of coincident + // vertices + for (std::set& grp : coincVertexGrps) { + if ((grp.find(v1) != grp.end()) || (grp.find(v2) != grp.end())) { // If yes add them to the existing group - if (!nv1.empty()) grp.insert(nv1.value()); - if (!nv2.empty()) grp.insert(nv2.value()); + if (!nv1.empty()) + grp.insert(nv1.value()); + if (!nv2.empty()) + grp.insert(nv2.value()); continue; } } - if (nv1.empty() || nv2.empty()) continue; + if (nv1.empty() || nv2.empty()) + continue; // If no, create a new group of coincident vertices std::set newGrp; @@ -320,26 +339,26 @@ int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, bool coincVertexGrps.push_back(newGrp); } - // If there are remaining vertices in the adjacent group (not in any existing constraint) - // add them as being each a separate coincident group - for (auto &lonept: vertexGrp) { + // If there are remaining vertices in the adjacent group (not in any existing + // constraint) add them as being each a separate coincident group + for (auto& lonept : vertexGrp) { std::set newGrp; newGrp.insert(lonept); coincVertexGrps.push_back(newGrp); } - // If there is more than 1 coincident group into adjacent group, constraint(s) is(are) missing - // Virtually generate the missing constraint(s) + // If there is more than 1 coincident group into adjacent group, constraint(s) is(are) + // missing Virtually generate the missing constraint(s) if (coincVertexGrps.size() > 1) { std::vector>::iterator vn; // Starting from the 2nd coincident group, generate a constraint between // this group first vertex, and previous group first vertex - for (vn = coincVertexGrps.begin()+1; vn < coincVertexGrps.end(); ++vn) { + for (vn = coincVertexGrps.begin() + 1; vn < coincVertexGrps.end(); ++vn) { ConstraintIds id; - id.Type = Coincident; // default point on point restriction - id.v = (vn-1)->begin()->v; - id.First = (vn-1)->begin()->GeoId; - id.FirstPos = (vn-1)->begin()->PosId; + id.Type = Coincident;// default point on point restriction + id.v = (vn - 1)->begin()->v; + id.First = (vn - 1)->begin()->GeoId; + id.FirstPos = (vn - 1)->begin()->PosId; id.Second = vn->begin()->GeoId; id.SecondPos = vn->begin()->PosId; missingCoincidences.push_back(id); @@ -354,7 +373,7 @@ int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, bool this->vertexConstraints.clear(); this->vertexConstraints.reserve(missingCoincidences.size()); - for (auto &coincidence:missingCoincidences) { + for (auto& coincidence : missingCoincidences) { this->vertexConstraints.push_back(coincidence); } @@ -364,28 +383,31 @@ int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, bool void SketchAnalysis::analyseMissingPointOnPointCoincident(double angleprecision) { - for(auto & vc : vertexConstraints) { + for (auto& vc : vertexConstraints) { auto geo1 = sketch->getGeometry(vc.First); auto geo2 = sketch->getGeometry(vc.Second); // tangency point-on-point - const Part::GeomCurve * curve1 = dynamic_cast(geo1); - const Part::GeomCurve * curve2 = dynamic_cast(geo2); + const Part::GeomCurve* curve1 = dynamic_cast(geo1); + const Part::GeomCurve* curve2 = dynamic_cast(geo2); - if(curve1 && curve2) { + if (curve1 && curve2) { - if( geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && - geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() + && geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *segm1 = static_cast(geo1); - const Part::GeomLineSegment *segm2 = static_cast(geo2); + const Part::GeomLineSegment* segm1 = + static_cast(geo1); + const Part::GeomLineSegment* segm2 = + static_cast(geo2); Base::Vector3d dir1 = segm1->getEndPoint() - segm1->getStartPoint(); Base::Vector3d dir2 = segm2->getEndPoint() - segm2->getStartPoint(); - if( (checkVertical(dir1,angleprecision) || checkHorizontal(dir1,angleprecision)) && - (checkVertical(dir2,angleprecision) || checkHorizontal(dir2,angleprecision)) ) { + if ((checkVertical(dir1, angleprecision) || checkHorizontal(dir1, angleprecision)) + && (checkVertical(dir2, angleprecision) + || checkHorizontal(dir2, angleprecision))) { // this is a job for horizontal/vertical constraints alone continue; } @@ -394,26 +416,24 @@ void SketchAnalysis::analyseMissingPointOnPointCoincident(double angleprecision) try { double u1, u2; - curve1->closestParameter(vc.v,u1); - curve2->closestParameter(vc.v,u2); + curve1->closestParameter(vc.v, u1); + curve2->closestParameter(vc.v, u2); Base::Vector3d tgv1 = curve1->firstDerivativeAtParameter(u1).Normalize(); Base::Vector3d tgv2 = curve2->firstDerivativeAtParameter(u2).Normalize(); - if(fabs(tgv1*tgv2)>fabs(cos(angleprecision))) { + if (fabs(tgv1 * tgv2) > fabs(cos(angleprecision))) { vc.Type = Sketcher::Tangent; } - else if(fabs(tgv1*tgv2) constr; - for (std::vector::iterator it = vertexConstraints.begin(); it != vertexConstraints.end(); ++it) { + for (std::vector::iterator it = vertexConstraints.begin(); + it != vertexConstraints.end(); + ++it) { Sketcher::Constraint* c = new Sketcher::Constraint(); c->Type = it->Type; c->First = it->First; @@ -432,21 +454,24 @@ void SketchAnalysis::makeMissingPointOnPointCoincident(bool onebyone) c->FirstPos = it->FirstPos; c->SecondPos = it->SecondPos; - if(onebyone) { + if (onebyone) { // addConstraint() creates a clone sketch->addConstraint(c); delete c; - solvesketch(status,dofs,true); + solvesketch(status, dofs, true); - if(status == -2) { //redundant constraints + if (status == -2) {// redundant constraints sketch->autoRemoveRedundants(false); - solvesketch(status,dofs,false); + solvesketch(status, dofs, false); } - if(status) { - THROWMT(Base::RuntimeError, QT_TRANSLATE_NOOP("Exceptions", "Autoconstrain error: Unsolvable sketch while applying coincident constraints.")); + if (status) { + THROWMT(Base::RuntimeError, + QT_TRANSLATE_NOOP("Exceptions", + "Autoconstrain error: Unsolvable sketch while applying " + "coincident constraints.")); } } else { @@ -454,27 +479,28 @@ void SketchAnalysis::makeMissingPointOnPointCoincident(bool onebyone) } } - if(!onebyone) + if (!onebyone) sketch->addConstraints(constr); vertexConstraints.clear(); - for (std::vector::iterator it = constr.begin(); it != constr.end(); ++it) { + for (std::vector::iterator it = constr.begin(); it != constr.end(); + ++it) { delete *it; } } int SketchAnalysis::detectMissingVerticalHorizontalConstraints(double angleprecision) { - const std::vector& geom = sketch->getInternalGeometry(); + const std::vector& geom = sketch->getInternalGeometry(); verthorizConstraints.clear(); - for (std::size_t i=0; igetTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *segm = static_cast(g); + const Part::GeomLineSegment* segm = static_cast(g); Base::Vector3d dir = segm->getEndPoint() - segm->getStartPoint(); @@ -486,11 +512,11 @@ int SketchAnalysis::detectMissingVerticalHorizontalConstraints(double anglepreci id.Second = GeoEnum::GeoUndef; id.SecondPos = Sketcher::PointPos::none; - if( checkVertical(dir, angleprecision) ) { + if (checkVertical(dir, angleprecision)) { id.Type = Sketcher::Vertical; verthorizConstraints.push_back(id); } - else if (checkHorizontal(dir, angleprecision) ) { + else if (checkHorizontal(dir, angleprecision)) { id.Type = Sketcher::Horizontal; verthorizConstraints.push_back(id); } @@ -505,7 +531,9 @@ void SketchAnalysis::makeMissingVerticalHorizontal(bool onebyone) int status, dofs; std::vector constr; - for (std::vector::iterator it = verthorizConstraints.begin(); it != verthorizConstraints.end(); ++it) { + for (std::vector::iterator it = verthorizConstraints.begin(); + it != verthorizConstraints.end(); + ++it) { Sketcher::Constraint* c = new Sketcher::Constraint(); c->Type = it->Type; c->First = it->First; @@ -513,21 +541,24 @@ void SketchAnalysis::makeMissingVerticalHorizontal(bool onebyone) c->FirstPos = it->FirstPos; c->SecondPos = it->SecondPos; - if(onebyone) { + if (onebyone) { // addConstraint() creates a clone sketch->addConstraint(c); delete c; - solvesketch(status,dofs,true); + solvesketch(status, dofs, true); - if(status == -2) { //redundant constraints + if (status == -2) {// redundant constraints sketch->autoRemoveRedundants(false); - solvesketch(status,dofs,false); + solvesketch(status, dofs, false); } - if(status) { - THROWMT(Base::RuntimeError, QT_TRANSLATE_NOOP("Exceptions", "Autoconstrain error: Unsolvable sketch while applying vertical/horizontal constraints.")); + if (status) { + THROWMT(Base::RuntimeError, + QT_TRANSLATE_NOOP("Exceptions", + "Autoconstrain error: Unsolvable sketch while applying " + "vertical/horizontal constraints.")); } } else { @@ -535,24 +566,25 @@ void SketchAnalysis::makeMissingVerticalHorizontal(bool onebyone) } } - if(!onebyone) + if (!onebyone) sketch->addConstraints(constr); verthorizConstraints.clear(); - for (std::vector::iterator it = constr.begin(); it != constr.end(); ++it) { + for (std::vector::iterator it = constr.begin(); it != constr.end(); + ++it) { delete *it; } } bool SketchAnalysis::checkVertical(Base::Vector3d dir, double angleprecision) { - return (dir.x == 0. && dir.y != 0.) || ( fabs(dir.y/dir.x) > tan(M_PI/2 - angleprecision)); + return (dir.x == 0. && dir.y != 0.) || (fabs(dir.y / dir.x) > tan(M_PI / 2 - angleprecision)); } bool SketchAnalysis::checkHorizontal(Base::Vector3d dir, double angleprecision) { - return (dir.y == 0. && dir.x != 0.) || ( fabs(dir.x/dir.y) > (1/tan(angleprecision))); + return (dir.y == 0. && dir.x != 0.) || (fabs(dir.x / dir.y) > (1 / tan(angleprecision))); } int SketchAnalysis::detectMissingEqualityConstraints(double precision) @@ -560,26 +592,26 @@ int SketchAnalysis::detectMissingEqualityConstraints(double precision) std::vector lineedgeIds; std::vector radiusedgeIds; - const std::vector& geom = sketch->getInternalGeometry(); - for (std::size_t i=0; i& geom = sketch->getInternalGeometry(); + for (std::size_t i = 0; i < geom.size(); i++) { Part::Geometry* g = geom[i]; if (g->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *segm = static_cast(g); + const Part::GeomLineSegment* segm = static_cast(g); EdgeIds id; id.GeoId = (int)i; - id.l = (segm->getEndPoint()-segm->getStartPoint()).Length(); + id.l = (segm->getEndPoint() - segm->getStartPoint()).Length(); lineedgeIds.push_back(id); } else if (g->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *segm = static_cast(g); + const Part::GeomArcOfCircle* segm = static_cast(g); EdgeIds id; id.GeoId = (int)i; id.l = segm->getRadius(); radiusedgeIds.push_back(id); } else if (g->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *segm = static_cast(g); + const Part::GeomCircle* segm = static_cast(g); EdgeIds id; id.GeoId = (int)i; id.l = segm->getRadius(); @@ -598,8 +630,8 @@ int SketchAnalysis::detectMissingEqualityConstraints(double precision) vt = std::adjacent_find(vt, lineedgeIds.end(), pred); if (vt < lineedgeIds.end()) { std::vector::iterator vn; - for (vn = vt+1; vn != lineedgeIds.end(); ++vn) { - if (pred(*vt,*vn)) { + for (vn = vt + 1; vn != lineedgeIds.end(); ++vn) { + if (pred(*vt, *vn)) { ConstraintIds id; id.Type = Equal; id.v.x = vt->l; @@ -628,8 +660,8 @@ int SketchAnalysis::detectMissingEqualityConstraints(double precision) vt = std::adjacent_find(vt, radiusedgeIds.end(), pred); if (vt < radiusedgeIds.end()) { std::vector::iterator vn; - for (vn = vt+1; vn != radiusedgeIds.end(); ++vn) { - if (pred(*vt,*vn)) { + for (vn = vt + 1; vn != radiusedgeIds.end(); ++vn) { + if (pred(*vt, *vn)) { ConstraintIds id; id.Type = Equal; id.v.x = vt->l; @@ -653,26 +685,25 @@ int SketchAnalysis::detectMissingEqualityConstraints(double precision) // and check which of them is forcing two vertexes to be coincident. // If there is none but two vertexes can be considered equal a coincident constraint is missing. std::vector constraint = sketch->Constraints.getValues(); - for (std::vector::iterator it = constraint.begin(); it != constraint.end(); ++it) { + for (std::vector::iterator it = constraint.begin(); + it != constraint.end(); + ++it) { if ((*it)->Type == Sketcher::Equal) { - ConstraintIds id { - Base::Vector3d{}, - (*it)->First, - (*it)->Second, - (*it)->FirstPos, - (*it)->SecondPos, - (*it)->Type - }; + ConstraintIds id {Base::Vector3d {}, + (*it)->First, + (*it)->Second, + (*it)->FirstPos, + (*it)->SecondPos, + (*it)->Type}; - std::list::iterator pos = std::find_if - (equallines.begin(), equallines.end(), Constraint_Equal(id)); + std::list::iterator pos = + std::find_if(equallines.begin(), equallines.end(), Constraint_Equal(id)); if (pos != equallines.end()) { equallines.erase(pos); } - pos = std::find_if - (equalradius.begin(), equalradius.end(), Constraint_Equal(id)); + pos = std::find_if(equalradius.begin(), equalradius.end(), Constraint_Equal(id)); if (pos != equalradius.end()) { equalradius.erase(pos); @@ -690,7 +721,8 @@ int SketchAnalysis::detectMissingEqualityConstraints(double precision) this->radiusequalityConstraints.clear(); this->radiusequalityConstraints.reserve(equalradius.size()); - for (std::list::iterator it = equalradius.begin(); it != equalradius.end(); ++it) { + for (std::list::iterator it = equalradius.begin(); it != equalradius.end(); + ++it) { this->radiusequalityConstraints.push_back(*it); } @@ -703,9 +735,12 @@ void SketchAnalysis::makeMissingEquality(bool onebyone) std::vector constr; std::vector equalities(lineequalityConstraints); - equalities.insert(equalities.end(),radiusequalityConstraints.begin(), radiusequalityConstraints.end()); + equalities.insert( + equalities.end(), radiusequalityConstraints.begin(), radiusequalityConstraints.end()); - for (std::vector::iterator it = equalities.begin(); it != equalities.end(); ++it) { + for (std::vector::iterator it = equalities.begin(); + it != equalities.end(); + ++it) { Sketcher::Constraint* c = new Sketcher::Constraint(); c->Type = it->Type; c->First = it->First; @@ -713,21 +748,24 @@ void SketchAnalysis::makeMissingEquality(bool onebyone) c->FirstPos = it->FirstPos; c->SecondPos = it->SecondPos; - if(onebyone) { + if (onebyone) { // addConstraint() creates a clone sketch->addConstraint(c); delete c; - solvesketch(status,dofs,true); + solvesketch(status, dofs, true); - if(status == -2) { //redundant constraints + if (status == -2) {// redundant constraints sketch->autoRemoveRedundants(false); - solvesketch(status,dofs,false); + solvesketch(status, dofs, false); } - if(status) { - THROWMT(Base::RuntimeError, QT_TRANSLATE_NOOP("Exceptions", "Autoconstrain error: Unsolvable sketch while applying equality constraints.")); + if (status) { + THROWMT(Base::RuntimeError, + QT_TRANSLATE_NOOP("Exceptions", + "Autoconstrain error: Unsolvable sketch while applying " + "equality constraints.")); } } else { @@ -735,39 +773,41 @@ void SketchAnalysis::makeMissingEquality(bool onebyone) } } - if(!onebyone) + if (!onebyone) sketch->addConstraints(constr); lineequalityConstraints.clear(); radiusequalityConstraints.clear(); - for (std::vector::iterator it = constr.begin(); it != constr.end(); ++it) { + for (std::vector::iterator it = constr.begin(); it != constr.end(); + ++it) { delete *it; } } -void SketchAnalysis::solvesketch(int &status, int &dofs, bool updategeo) +void SketchAnalysis::solvesketch(int& status, int& dofs, bool updategeo) { status = sketch->solve(updategeo); - if(updategeo) + if (updategeo) dofs = sketch->setUpSketch(); else dofs = sketch->getLastDoF(); - if (sketch->getLastHasRedundancies()) { // redundant constraints + if (sketch->getLastHasRedundancies()) {// redundant constraints status = -2; } - if (dofs < 0) { // over-constrained sketch + if (dofs < 0) {// over-constrained sketch status = -4; } - else if (sketch->getLastHasConflicts()) { // conflicting constraints + else if (sketch->getLastHasConflicts()) {// conflicting constraints status = -3; } } -int SketchAnalysis::autoconstraint(double precision, double angleprecision, bool includeconstruction) +int SketchAnalysis::autoconstraint(double precision, double angleprecision, + bool includeconstruction) { App::Document* doc = sketch->getDocument(); doc->openTransaction("delete all constraints"); @@ -778,30 +818,38 @@ int SketchAnalysis::autoconstraint(double precision, double angleprecision, bool int status, dofs; - solvesketch(status,dofs,true); + solvesketch(status, dofs, true); - if(status) {// it should not be possible at this moment as we start from a clean situation - THROWMT(Base::RuntimeError, QT_TRANSLATE_NOOP("Exceptions", "Autoconstrain error: Unsolvable sketch without constraints.")); + if (status) {// it should not be possible at this moment as we start from a clean situation + THROWMT(Base::RuntimeError, + QT_TRANSLATE_NOOP("Exceptions", + "Autoconstrain error: Unsolvable sketch without constraints.")); } // STAGE 1: Vertical/Horizontal Line Segments int nhv = detectMissingVerticalHorizontalConstraints(angleprecision); // STAGE 2: Point-on-Point constraint (Coincidents, endpoint perp, endpoint tangency) - // Note: We do not apply the vertical/horizontal constraints before calculating the pointonpoint constraints + // Note: We do not apply the vertical/horizontal constraints before calculating the pointonpoint + // constraints // as the solver may move the geometry in the meantime and prevent correct detection int nc = detectMissingPointOnPointConstraints(precision, includeconstruction); - if (nc > 0) // STAGE 2a: Classify point-on-point into coincidents, endpoint perp, endpoint tangency + if (nc + > 0)// STAGE 2a: Classify point-on-point into coincidents, endpoint perp, endpoint tangency analyseMissingPointOnPointCoincident(angleprecision); // STAGE 3: Equality constraint detection int ne = detectMissingEqualityConstraints(precision); - Base::Console().Log("Constraints: Vertical/Horizontal: %d found. Point-on-point: %d. Equality: %d\n", nhv, nc, ne); + Base::Console().Log( + "Constraints: Vertical/Horizontal: %d found. Point-on-point: %d. Equality: %d\n", + nhv, + nc, + ne); // Applying STAGE 1, if any - if (nhv >0 ) { + if (nhv > 0) { App::Document* doc = sketch->getDocument(); doc->openTransaction("add vertical/horizontal constraints"); @@ -810,20 +858,23 @@ int SketchAnalysis::autoconstraint(double precision, double angleprecision, bool // finish the transaction and update doc->commitTransaction(); - solvesketch(status,dofs,true); + solvesketch(status, dofs, true); - if(status == -2) { // redundants + if (status == -2) {// redundants sketch->autoRemoveRedundants(false); - solvesketch(status,dofs,false); + solvesketch(status, dofs, false); } - if(status) { - THROWMT(Base::RuntimeError, QT_TRANSLATE_NOOP("Exceptions", "Autoconstrain error: Unsolvable sketch after applying horizontal and vertical constraints.")); + if (status) { + THROWMT(Base::RuntimeError, + QT_TRANSLATE_NOOP("Exceptions", + "Autoconstrain error: Unsolvable sketch after applying " + "horizontal and vertical constraints.")); } } // Applying STAGE 2 - if(nc > 0) { + if (nc > 0) { App::Document* doc = sketch->getDocument(); doc->openTransaction("add coincident constraint"); @@ -832,27 +883,30 @@ int SketchAnalysis::autoconstraint(double precision, double angleprecision, bool // finish the transaction and update doc->commitTransaction(); - solvesketch(status,dofs,true); + solvesketch(status, dofs, true); - if(status == -2) { // redundants + if (status == -2) {// redundants sketch->autoRemoveRedundants(false); - solvesketch(status,dofs,false); + solvesketch(status, dofs, false); } - if(status) { - THROWMT(Base::RuntimeError, QT_TRANSLATE_NOOP("Exceptions", "Autoconstrain error: Unsolvable sketch after applying point-on-point constraints.")); + if (status) { + THROWMT(Base::RuntimeError, + QT_TRANSLATE_NOOP("Exceptions", + "Autoconstrain error: Unsolvable sketch after applying " + "point-on-point constraints.")); } } // Applying STAGE 3 - if(ne > 0) { + if (ne > 0) { App::Document* doc = sketch->getDocument(); doc->openTransaction("add equality constraints"); try { makeMissingEquality(); } - catch(Base::RuntimeError &) { + catch (Base::RuntimeError&) { doc->abortTransaction(); throw; } @@ -860,15 +914,19 @@ int SketchAnalysis::autoconstraint(double precision, double angleprecision, bool // finish the transaction and update doc->commitTransaction(); - solvesketch(status,dofs,true); + solvesketch(status, dofs, true); - if(status == -2) { // redundants + if (status == -2) {// redundants sketch->autoRemoveRedundants(false); - solvesketch(status,dofs,false); + solvesketch(status, dofs, false); } - if(status) { - THROWMT(Base::RuntimeError, QT_TRANSLATE_NOOP("Exceptions", "Autoconstrain error: Unsolvable sketch after applying equality constraints.")); + if (status) { + THROWMT( + Base::RuntimeError, + QT_TRANSLATE_NOOP( + "Exceptions", + "Autoconstrain error: Unsolvable sketch after applying equality constraints.")); } } @@ -889,13 +947,13 @@ std::vector SketchAnalysis::getOpenVertices() const // build up map vertex->edge TopTools_IndexedDataMapOfShapeListOfShape vertex2Edge; TopExp::MapShapesAndAncestors(shape, TopAbs_VERTEX, TopAbs_EDGE, vertex2Edge); - for (int i=1; i<= vertex2Edge.Extent(); ++i) { + for (int i = 1; i <= vertex2Edge.Extent(); ++i) { const TopTools_ListOfShape& los = vertex2Edge.FindFromIndex(i); if (los.Extent() != 2) { const TopoDS_Vertex& vertex = TopoDS::Vertex(vertex2Edge.FindKey(i)); gp_Pnt pnt = BRep_Tool::Pnt(vertex); Base::Vector3d pos; - invPlm.multVec(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z()),pos); + invPlm.multVec(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z()), pos); points.push_back(pos); } } @@ -906,8 +964,8 @@ std::vector SketchAnalysis::getOpenVertices() const int SketchAnalysis::detectDegeneratedGeometries(double tolerance) { int countDegenerated = 0; - const std::vector& geom = sketch->getInternalGeometry(); - for (std::size_t i=0; i& geom = sketch->getInternalGeometry(); + for (std::size_t i = 0; i < geom.size(); i++) { auto gf = GeometryFacade::getFacade(geom[i]); if (gf->getConstruction()) @@ -927,9 +985,9 @@ int SketchAnalysis::detectDegeneratedGeometries(double tolerance) int SketchAnalysis::removeDegeneratedGeometries(double tolerance) { std::set delInternalGeometries; - const std::vector& geom = sketch->getInternalGeometry(); - for (std::size_t i=0; i& geom = sketch->getInternalGeometry(); + for (std::size_t i = 0; i < geom.size(); i++) { + auto gf = GeometryFacade::getFacade(geom[i]); if (gf->getConstruction()) continue; diff --git a/src/Mod/Sketcher/App/SketchAnalysis.h b/src/Mod/Sketcher/App/SketchAnalysis.h index 8ceafe19bf..f246d3f5bb 100644 --- a/src/Mod/Sketcher/App/SketchAnalysis.h +++ b/src/Mod/Sketcher/App/SketchAnalysis.h @@ -32,76 +32,110 @@ #include "Analyse.h" -namespace Sketcher { +namespace Sketcher +{ class SketchObject; class SketcherExport SketchAnalysis { public: - /// Creates an instance of the SketchAnalysis object, taking as parameter a pointer to an SketchObject. + /// Creates an instance of the SketchAnalysis object, taking as parameter a pointer to an + /// SketchObject. /// /// There is a first type of routines, simple routines, which work in the following order: /// Detect - (Analyse) - [Get] - [Set] - Make /// /// The Detect step just identifies possible missing constraints. /// - /// The Analyse, which is not available for all the routines, operates in detected constraints of the same routine, to - /// look for alternatives. For example, a general pointonpoint detection leads to a search for coincident constraints, which - /// can be later run via Analyse if it is intended to convert endpoint coincidence to endpoint perpendicular and tangent constraints. + /// The Analyse, which is not available for all the routines, operates in detected constraints + /// of the same routine, to look for alternatives. For example, a general pointonpoint detection + /// leads to a search for coincident constraints, which can be later run via Analyse if it is + /// intended to convert endpoint coincidence to endpoint perpendicular and tangent constraints. /// - /// The Get retrieves the result of the analysis as a vector of ConstraintIds, indicating the suggested constraints. This step is intended - /// for enabling the user to check the result of the analysis, rather than applying it. If only applying is intended, this step is not necessary - /// as the Make will operate on the result of the Detect - Analyse directly. + /// The Get retrieves the result of the analysis as a vector of ConstraintIds, indicating the + /// suggested constraints. This step is intended for enabling the user to check the result of + /// the analysis, rather than applying it. If only applying is intended, this step is not + /// necessary as the Make will operate on the result of the Detect - Analyse directly. /// - /// The Set changes the detected result. It modifies the SketchAnalysis object. It only modifies the SketchObject as far as the SketchAnalysis is changed. - /// It does not apply any changes to the sketch. It is intended so as to enable the user to change the result that will be applied. + /// The Set changes the detected result. It modifies the SketchAnalysis object. It only modifies + /// the SketchObject as far as the SketchAnalysis is changed. It does not apply any changes to + /// the sketch. It is intended so as to enable the user to change the result that will be + /// applied. /// /// Neither the Detect, nor the Analyse, nor the Get steps modify the Sketch geometry. /// /// Make applies the constraints stored internally in the SketchAnalysis object. /// - /// A second type of routines, complex routines, are thought for running fully automatic and they Detect, Analyse and Make. - /// They may also apply a variety of constraint types. + /// A second type of routines, complex routines, are thought for running fully automatic and + /// they Detect, Analyse and Make. They may also apply a variety of constraint types. /// - /// A third type of routines do not relate to autoconstraining at all, and include validation methods for sketches. - explicit SketchAnalysis(Sketcher::SketchObject * Obj); + /// A third type of routines do not relate to autoconstraining at all, and include validation + /// methods for sketches. + explicit SketchAnalysis(Sketcher::SketchObject* Obj); ~SketchAnalysis(); // Simple routines (see constructor) /// Point on Point constraint simple routine Detect step (see constructor) - /// Detect detects only coincident constraints, Analyse converts coincident to endpoint perpendicular/tangent where appropriate - int detectMissingPointOnPointConstraints(double precision = Precision::Confusion() * 1000, bool includeconstruction = true); + /// Detect detects only coincident constraints, Analyse converts coincident to endpoint + /// perpendicular/tangent where appropriate + int detectMissingPointOnPointConstraints(double precision = Precision::Confusion() * 1000, + bool includeconstruction = true); /// Point on Point constraint simple routine Analyse step (see constructor) - void analyseMissingPointOnPointCoincident(double angleprecision = M_PI/8); + void analyseMissingPointOnPointCoincident(double angleprecision = M_PI / 8); /// Point on Point constraint simple routine Get step (see constructor) - std::vector &getMissingPointOnPointConstraints() {return vertexConstraints;} + std::vector& getMissingPointOnPointConstraints() + { + return vertexConstraints; + } /// Vertical/Horizontal constraints simple routine Set step (see constructor) - void setMissingPointOnPointConstraints(std::vector& cl) {vertexConstraints = cl;} + void setMissingPointOnPointConstraints(std::vector& cl) + { + vertexConstraints = cl; + } /// Point on Point constraint simple routine Make step (see constructor) - /// if onebyone, then the sketch is solved after each individual constraint addition and any redundancy removed. + /// if onebyone, then the sketch is solved after each individual constraint addition and any + /// redundancy removed. void makeMissingPointOnPointCoincident(bool onebyone = false); /// Vertical/Horizontal constraints simple routine Detect step (see constructor) - int detectMissingVerticalHorizontalConstraints(double angleprecision = M_PI/8); + int detectMissingVerticalHorizontalConstraints(double angleprecision = M_PI / 8); /// Vertical/Horizontal constraints simple routine Get step (see constructor) - std::vector &getMissingVerticalHorizontalConstraints() {return verthorizConstraints;} + std::vector& getMissingVerticalHorizontalConstraints() + { + return verthorizConstraints; + } /// Vertical/Horizontal constraints simple routine Set step (see constructor) - void setMissingVerticalHorizontalConstraints(std::vector& cl) {verthorizConstraints = cl;} + void setMissingVerticalHorizontalConstraints(std::vector& cl) + { + verthorizConstraints = cl; + } /// Vertical/Horizontal constraints simple routine Make step (see constructor) void makeMissingVerticalHorizontal(bool onebyone = false); /// Equality constraints simple routine Detect step (see constructor) int detectMissingEqualityConstraints(double precision); /// Equality constraints simple routine Get step for line segments (see constructor) - std::vector &getMissingLineEqualityConstraints() {return lineequalityConstraints;} + std::vector& getMissingLineEqualityConstraints() + { + return lineequalityConstraints; + } /// Equality constraints simple routine Get step for radii (see constructor) - std::vector &getMissingRadiusConstraints() {return radiusequalityConstraints;} + std::vector& getMissingRadiusConstraints() + { + return radiusequalityConstraints; + } /// Equality constraints simple routine Set step for line segments (see constructor) - void setMissingLineEqualityConstraints(std::vector& cl) {lineequalityConstraints = cl;} + void setMissingLineEqualityConstraints(std::vector& cl) + { + lineequalityConstraints = cl; + } /// Equality constraints simple routine Set step for radii (see constructor) - void setMissingRadiusConstraints(std::vector& cl) {radiusequalityConstraints = cl;} + void setMissingRadiusConstraints(std::vector& cl) + { + radiusequalityConstraints = cl; + } /// Equality constraints simple routine Make step (see constructor) void makeMissingEquality(bool onebyone = true); @@ -114,16 +148,20 @@ public: /// Fully automated multi-constraint autoconstraining /// - /// It DELETES all the constraints currently present in the Sketcher. The reason is that it makes assumptions to avoid redundancies. + /// It DELETES all the constraints currently present in the Sketcher. The reason is that it + /// makes assumptions to avoid redundancies. /// /// It applies coincidents - vertical/horizontal constraints and equality constraints. - int autoconstraint(double precision = Precision::Confusion() * 1000, double angleprecision = M_PI/8, bool includeconstruction = true); + int autoconstraint(double precision = Precision::Confusion() * 1000, + double angleprecision = M_PI / 8, bool includeconstruction = true); - // helper functions, which may be used by more complex methods, and/or called directly by user space (python) methods + // helper functions, which may be used by more complex methods, and/or called directly by user + // space (python) methods /// solves the sketch and retrieves the error status, and the degrees of freedom. - /// It enables to solve updating the geometry (so moving the geometry to match the constraints) or preserving the geometry. - void solvesketch(int &status, int &dofs, bool updategeo); + /// It enables to solve updating the geometry (so moving the geometry to match the constraints) + /// or preserving the geometry. + void solvesketch(int& status, int& dofs, bool updategeo); // third type of routines std::vector getOpenVertices() const; @@ -146,9 +184,8 @@ protected: protected: bool checkHorizontal(Base::Vector3d dir, double angleprecision); bool checkVertical(Base::Vector3d dir, double angleprecision); - }; -} //namespace Sketcher +}// namespace Sketcher -#endif // SKETCHER_SKETCHANALYSIS_H +#endif// SKETCHER_SKETCHANALYSIS_H diff --git a/src/Mod/Sketcher/App/SketchGeometryExtension.cpp b/src/Mod/Sketcher/App/SketchGeometryExtension.cpp index b8f6663467..8d2b9312f7 100644 --- a/src/Mod/Sketcher/App/SketchGeometryExtension.cpp +++ b/src/Mod/Sketcher/App/SketchGeometryExtension.cpp @@ -32,62 +32,63 @@ using namespace Sketcher; //---------- Geometry Extension -constexpr std::array SketchGeometryExtension::internaltype2str; -constexpr std::array SketchGeometryExtension::geometrymode2str; +constexpr std::array + SketchGeometryExtension::internaltype2str; +constexpr std::array + SketchGeometryExtension::geometrymode2str; -TYPESYSTEM_SOURCE(Sketcher::SketchGeometryExtension,Part::GeometryPersistenceExtension) +TYPESYSTEM_SOURCE(Sketcher::SketchGeometryExtension, Part::GeometryPersistenceExtension) // scoped within the class, multithread ready std::atomic SketchGeometryExtension::_GeometryID; -SketchGeometryExtension::SketchGeometryExtension(): Id(++SketchGeometryExtension::_GeometryID), - InternalGeometryType(InternalType::None), - GeometryLayer(0) -{ +SketchGeometryExtension::SketchGeometryExtension() + : Id(++SketchGeometryExtension::_GeometryID), + InternalGeometryType(InternalType::None), + GeometryLayer(0) +{} -} +SketchGeometryExtension::SketchGeometryExtension(long cid) + : Id(cid), + InternalGeometryType(InternalType::None), + GeometryLayer(0) +{} -SketchGeometryExtension::SketchGeometryExtension(long cid): Id(cid), - InternalGeometryType(InternalType::None), - GeometryLayer(0) -{ - -} - -void SketchGeometryExtension::copyAttributes(Part::GeometryExtension * cpy) const +void SketchGeometryExtension::copyAttributes(Part::GeometryExtension* cpy) const { Part::GeometryPersistenceExtension::copyAttributes(cpy); - static_cast(cpy)->Id = this->Id; - static_cast(cpy)->InternalGeometryType = this->InternalGeometryType; - static_cast(cpy)->GeometryModeFlags = this->GeometryModeFlags; - static_cast(cpy)->GeometryLayer = this->GeometryLayer; + static_cast(cpy)->Id = this->Id; + static_cast(cpy)->InternalGeometryType = this->InternalGeometryType; + static_cast(cpy)->GeometryModeFlags = this->GeometryModeFlags; + static_cast(cpy)->GeometryLayer = this->GeometryLayer; } -void SketchGeometryExtension::restoreAttributes(Base::XMLReader &reader) +void SketchGeometryExtension::restoreAttributes(Base::XMLReader& reader) { Part::GeometryPersistenceExtension::restoreAttributes(reader); - if(reader.hasAttribute("id")) + if (reader.hasAttribute("id")) Id = reader.getAttributeAsInteger("id"); - InternalGeometryType = static_cast(reader.getAttributeAsInteger("internalGeometryType")); + InternalGeometryType = static_cast( + reader.getAttributeAsInteger("internalGeometryType")); GeometryModeFlags = GeometryModeFlagType(reader.getAttribute("geometryModeFlags")); - if(reader.hasAttribute("geometryLayer")) + if (reader.hasAttribute("geometryLayer")) GeometryLayer = reader.getAttributeAsInteger("geometryLayer"); - } -void SketchGeometryExtension::saveAttributes(Base::Writer &writer) const +void SketchGeometryExtension::saveAttributes(Base::Writer& writer) const { Part::GeometryPersistenceExtension::saveAttributes(writer); - writer.Stream() // << "\" id=\"" << Id // This is removed as the stored Id is not used and it may interfere with RT's future implementation - << "\" internalGeometryType=\"" << (int) InternalGeometryType - << "\" geometryModeFlags=\"" << GeometryModeFlags.to_string() - << "\" geometryLayer=\"" << GeometryLayer; + // This is removed as the stored Id is not used and it may interfere with RT's future + // implementation + writer.Stream()// << "\" id=\"" << Id + << "\" internalGeometryType=\"" << (int)InternalGeometryType << "\" geometryModeFlags=\"" + << GeometryModeFlags.to_string() << "\" geometryLayer=\"" << GeometryLayer; } std::unique_ptr SketchGeometryExtension::copy() const @@ -96,53 +97,52 @@ std::unique_ptr SketchGeometryExtension::copy() const copyAttributes(cpy.get()); -#if defined (__GNUC__) && (__GNUC__ <=4) +#if defined(__GNUC__) && (__GNUC__ <= 4) return std::move(cpy); #else return cpy; #endif } -PyObject * SketchGeometryExtension::getPyObject() +PyObject* SketchGeometryExtension::getPyObject() { return new SketchGeometryExtensionPy(new SketchGeometryExtension(*this)); } -bool SketchGeometryExtension::getInternalTypeFromName(std::string str, InternalType::InternalType &type) +bool SketchGeometryExtension::getInternalTypeFromName(std::string str, + InternalType::InternalType& type) { - auto pos = std::find_if( SketchGeometryExtension::internaltype2str.begin(), - SketchGeometryExtension::internaltype2str.end(), - [str](const char * val) { - return strcmp(val,str.c_str())==0; - } - ); + auto pos = std::find_if(SketchGeometryExtension::internaltype2str.begin(), + SketchGeometryExtension::internaltype2str.end(), + [str](const char* val) { + return strcmp(val, str.c_str()) == 0; + }); - if( pos != SketchGeometryExtension::internaltype2str.end()) { - int index = std::distance( SketchGeometryExtension::internaltype2str.begin(), pos ); + if (pos != SketchGeometryExtension::internaltype2str.end()) { + int index = std::distance(SketchGeometryExtension::internaltype2str.begin(), pos); - type = static_cast(index); - return true; + type = static_cast(index); + return true; } return false; } -bool SketchGeometryExtension::getGeometryModeFromName(std::string str, GeometryMode::GeometryMode &type) +bool SketchGeometryExtension::getGeometryModeFromName(std::string str, + GeometryMode::GeometryMode& type) { - auto pos = std::find_if( SketchGeometryExtension::geometrymode2str.begin(), - SketchGeometryExtension::geometrymode2str.end(), - [str](const char * val) { - return strcmp(val,str.c_str())==0; - } - ); + auto pos = std::find_if(SketchGeometryExtension::geometrymode2str.begin(), + SketchGeometryExtension::geometrymode2str.end(), + [str](const char* val) { + return strcmp(val, str.c_str()) == 0; + }); - if( pos != SketchGeometryExtension::geometrymode2str.end()) { - int index = std::distance( SketchGeometryExtension::geometrymode2str.begin(), pos ); + if (pos != SketchGeometryExtension::geometrymode2str.end()) { + int index = std::distance(SketchGeometryExtension::geometrymode2str.begin(), pos); - type = static_cast(index); - return true; + type = static_cast(index); + return true; } return false; } - diff --git a/src/Mod/Sketcher/App/SketchGeometryExtension.h b/src/Mod/Sketcher/App/SketchGeometryExtension.h index 54a98c71f5..160f477cc5 100644 --- a/src/Mod/Sketcher/App/SketchGeometryExtension.h +++ b/src/Mod/Sketcher/App/SketchGeometryExtension.h @@ -34,31 +34,35 @@ namespace Sketcher { - namespace InternalType { - enum InternalType { - None = 0, - EllipseMajorDiameter = 1, - EllipseMinorDiameter = 2, - EllipseFocus1 = 3, - EllipseFocus2 = 4, - HyperbolaMajor = 5, - HyperbolaMinor = 6, - HyperbolaFocus = 7, - ParabolaFocus = 8, - BSplineControlPoint = 9, - BSplineKnotPoint = 10, - ParabolaFocalAxis = 11, - NumInternalGeometryType // Must be the last - }; - } +namespace InternalType +{ +enum InternalType +{ + None = 0, + EllipseMajorDiameter = 1, + EllipseMinorDiameter = 2, + EllipseFocus1 = 3, + EllipseFocus2 = 4, + HyperbolaMajor = 5, + HyperbolaMinor = 6, + HyperbolaFocus = 7, + ParabolaFocus = 8, + BSplineControlPoint = 9, + BSplineKnotPoint = 10, + ParabolaFocalAxis = 11, + NumInternalGeometryType// Must be the last +}; +} - namespace GeometryMode { - enum GeometryMode { - Blocked = 0, - Construction = 1, - NumGeometryMode // Must be the last - }; - } +namespace GeometryMode +{ +enum GeometryMode +{ + Blocked = 0, + Construction = 1, + NumGeometryMode// Must be the last +}; +} class ISketchGeometryExtension { @@ -74,65 +78,103 @@ public: // Geometry functional mode virtual bool testGeometryMode(int flag) const = 0; - virtual void setGeometryMode(int flag, bool v=true) = 0; + virtual void setGeometryMode(int flag, bool v = true) = 0; virtual int getGeometryLayerId() const = 0; virtual void setGeometryLayerId(int geolayer) = 0; }; -class SketcherExport SketchGeometryExtension : public Part::GeometryPersistenceExtension, private ISketchGeometryExtension +class SketcherExport SketchGeometryExtension: public Part::GeometryPersistenceExtension, + private ISketchGeometryExtension { TYPESYSTEM_HEADER_WITH_OVERRIDE(); -public: +public: SketchGeometryExtension(); explicit SketchGeometryExtension(long cid); ~SketchGeometryExtension() override = default; std::unique_ptr copy() const override; - PyObject *getPyObject() override; + PyObject* getPyObject() override; - long getId() const override {return Id;} - void setId(long id) override {Id = id;} + long getId() const override + { + return Id; + } + void setId(long id) override + { + Id = id; + } - InternalType::InternalType getInternalType() const override {return InternalGeometryType;} - void setInternalType(InternalType::InternalType type) override {InternalGeometryType = type;} + InternalType::InternalType getInternalType() const override + { + return InternalGeometryType; + } + void setInternalType(InternalType::InternalType type) override + { + InternalGeometryType = type; + } - bool testGeometryMode(int flag) const override { return GeometryModeFlags.test((size_t)(flag)); }; - void setGeometryMode(int flag, bool v=true) override { GeometryModeFlags.set((size_t)(flag), v); }; + bool testGeometryMode(int flag) const override + { + return GeometryModeFlags.test((size_t)(flag)); + }; + void setGeometryMode(int flag, bool v = true) override + { + GeometryModeFlags.set((size_t)(flag), v); + }; - int getGeometryLayerId() const override { return GeometryLayer;} - void setGeometryLayerId(int geolayer) override { GeometryLayer = geolayer;} + int getGeometryLayerId() const override + { + return GeometryLayer; + } + void setGeometryLayerId(int geolayer) override + { + GeometryLayer = geolayer; + } - constexpr static std::array internaltype2str {{ "None", "EllipseMajorDiameter", "EllipseMinorDiameter","EllipseFocus1", "EllipseFocus2", "HyperbolaMajor", "HyperbolaMinor", "HyperbolaFocus", "ParabolaFocus", "BSplineControlPoint", "BSplineKnotPoint", "ParabolaFocalAxis" }}; + constexpr static std::array + internaltype2str {{"None", + "EllipseMajorDiameter", + "EllipseMinorDiameter", + "EllipseFocus1", + "EllipseFocus2", + "HyperbolaMajor", + "HyperbolaMinor", + "HyperbolaFocus", + "ParabolaFocus", + "BSplineControlPoint", + "BSplineKnotPoint", + "ParabolaFocalAxis"}}; - constexpr static std::array geometrymode2str {{ "Blocked", "Construction" }}; + constexpr static std::array geometrymode2str { + {"Blocked", "Construction"}}; - static bool getInternalTypeFromName(std::string str, InternalType::InternalType &type); + static bool getInternalTypeFromName(std::string str, InternalType::InternalType& type); - static bool getGeometryModeFromName(std::string str, GeometryMode::GeometryMode &type); + static bool getGeometryModeFromName(std::string str, GeometryMode::GeometryMode& type); protected: - void copyAttributes(Part::GeometryExtension * cpy) const override; - void restoreAttributes(Base::XMLReader &reader) override; - void saveAttributes(Base::Writer &writer) const override; + void copyAttributes(Part::GeometryExtension* cpy) const override; + void restoreAttributes(Base::XMLReader& reader) override; + void saveAttributes(Base::Writer& writer) const override; private: SketchGeometryExtension(const SketchGeometryExtension&) = default; private: using GeometryModeFlagType = std::bitset<32>; - long Id; - InternalType::InternalType InternalGeometryType; - GeometryModeFlagType GeometryModeFlags; - int GeometryLayer; + long Id; + InternalType::InternalType InternalGeometryType; + GeometryModeFlagType GeometryModeFlags; + int GeometryLayer; private: static std::atomic _GeometryID; }; -} //namespace Sketcher +}// namespace Sketcher -#endif // SKETCHER_SKETCHGEOMETRYEXTENSION_H +#endif// SKETCHER_SKETCHGEOMETRYEXTENSION_H diff --git a/src/Mod/Sketcher/App/SketchGeometryExtensionPyImp.cpp b/src/Mod/Sketcher/App/SketchGeometryExtensionPyImp.cpp index b35dda0740..e7c4de1a3b 100644 --- a/src/Mod/Sketcher/App/SketchGeometryExtensionPyImp.cpp +++ b/src/Mod/Sketcher/App/SketchGeometryExtensionPyImp.cpp @@ -23,6 +23,7 @@ #include "PreCompiled.h" #include "SketchGeometryExtensionPy.h" + #include "SketchGeometryExtensionPy.cpp" @@ -34,7 +35,7 @@ std::string SketchGeometryExtensionPy::representation() const std::stringstream str; str << "getName().empty()) + if (!getSketchGeometryExtensionPtr()->getName().empty()) str << "\'" << getSketchGeometryExtensionPtr()->getName() << "\', "; str << "\""; @@ -43,7 +44,8 @@ std::string SketchGeometryExtensionPy::representation() const return str.str(); } -PyObject *SketchGeometryExtensionPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +// Python wrapper +PyObject* SketchGeometryExtensionPy::PyMake(struct _typeobject*, PyObject*, PyObject*) { // create a new instance of PointPy and the Twin object return new SketchGeometryExtensionPy(new SketchGeometryExtension); @@ -66,10 +68,10 @@ int SketchGeometryExtensionPy::PyInit(PyObject* args, PyObject* /*kwd*/) } - - PyErr_SetString(PyExc_TypeError, "SketchGeometryExtension constructor accepts:\n" - "-- empty parameter list\n" - "-- int\n"); + PyErr_SetString(PyExc_TypeError, + "SketchGeometryExtension constructor accepts:\n" + "-- empty parameter list\n" + "-- int\n"); return -1; } @@ -87,12 +89,13 @@ Py::String SketchGeometryExtensionPy::getInternalType() const { int internaltypeindex = (int)this->getSketchGeometryExtensionPtr()->getInternalType(); - if(internaltypeindex >= InternalType::NumInternalGeometryType) + if (internaltypeindex >= InternalType::NumInternalGeometryType) throw Py::NotImplementedError("String name of enum not implemented"); - std::string typestr = this->getSketchGeometryExtensionPtr()->internaltype2str[internaltypeindex]; + std::string typestr = + this->getSketchGeometryExtensionPtr()->internaltype2str[internaltypeindex]; - return Py::String(typestr); + return Py::String(typestr); } void SketchGeometryExtensionPy::setInternalType(Py::String arg) @@ -100,7 +103,7 @@ void SketchGeometryExtensionPy::setInternalType(Py::String arg) std::string argstr = arg; InternalType::InternalType type; - if(SketchGeometryExtension::getInternalTypeFromName(argstr, type)) { + if (SketchGeometryExtension::getInternalTypeFromName(argstr, type)) { this->getSketchGeometryExtensionPtr()->setInternalType(type); return; } @@ -120,7 +123,8 @@ void SketchGeometryExtensionPy::setBlocked(Py::Boolean arg) Py::Boolean SketchGeometryExtensionPy::getConstruction() const { - return Py::Boolean(getSketchGeometryExtensionPtr()->testGeometryMode(GeometryMode::Construction)); + return Py::Boolean( + getSketchGeometryExtensionPtr()->testGeometryMode(GeometryMode::Construction)); } void SketchGeometryExtensionPy::setConstruction(Py::Boolean arg) @@ -128,15 +132,16 @@ void SketchGeometryExtensionPy::setConstruction(Py::Boolean arg) getSketchGeometryExtensionPtr()->setGeometryMode(GeometryMode::Construction, arg); } -PyObject* SketchGeometryExtensionPy::testGeometryMode(PyObject *args) +PyObject* SketchGeometryExtensionPy::testGeometryMode(PyObject* args) { char* flag; - if (PyArg_ParseTuple(args, "s",&flag)) { + if (PyArg_ParseTuple(args, "s", &flag)) { GeometryMode::GeometryMode mode; - if(getSketchGeometryExtensionPtr()->getGeometryModeFromName(flag, mode)) - return new_reference_to(Py::Boolean(getSketchGeometryExtensionPtr()->testGeometryMode(mode))); + if (getSketchGeometryExtensionPtr()->getGeometryModeFromName(flag, mode)) + return new_reference_to( + Py::Boolean(getSketchGeometryExtensionPtr()->testGeometryMode(mode))); PyErr_SetString(PyExc_TypeError, "Flag string does not exist."); return nullptr; @@ -146,15 +151,15 @@ PyObject* SketchGeometryExtensionPy::testGeometryMode(PyObject *args) return nullptr; } -PyObject* SketchGeometryExtensionPy::setGeometryMode(PyObject *args) +PyObject* SketchGeometryExtensionPy::setGeometryMode(PyObject* args) { - char * flag; - PyObject * bflag = Py_True; + char* flag; + PyObject* bflag = Py_True; if (PyArg_ParseTuple(args, "s|O!", &flag, &PyBool_Type, &bflag)) { GeometryMode::GeometryMode mode; - if(getSketchGeometryExtensionPtr()->getGeometryModeFromName(flag, mode)) { + if (getSketchGeometryExtensionPtr()->getGeometryModeFromName(flag, mode)) { getSketchGeometryExtensionPtr()->setGeometryMode(mode, Base::asBoolean(bflag)); Py_Return; } @@ -177,7 +182,7 @@ void SketchGeometryExtensionPy::setGeometryLayerId(Py::Long Id) this->getSketchGeometryExtensionPtr()->setGeometryLayerId(long(Id)); } -PyObject *SketchGeometryExtensionPy::getCustomAttributes(const char* /*attr*/) const +PyObject* SketchGeometryExtensionPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -186,4 +191,3 @@ int SketchGeometryExtensionPy::setCustomAttributes(const char* /*attr*/, PyObjec { return 0; } - diff --git a/src/Mod/Sketcher/App/SketchObject.cpp b/src/Mod/Sketcher/App/SketchObject.cpp index d181e10dba..1ee51bf747 100644 --- a/src/Mod/Sketcher/App/SketchObject.cpp +++ b/src/Mod/Sketcher/App/SketchObject.cpp @@ -22,39 +22,39 @@ #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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #endif #include @@ -80,70 +80,90 @@ #undef DEBUG -//#define DEBUG +// #define DEBUG using namespace Sketcher; using namespace Base; namespace bp = boost::placeholders; -FC_LOG_LEVEL_INIT("Sketch",true,true) +FC_LOG_LEVEL_INIT("Sketch", true, true) PROPERTY_SOURCE(Sketcher::SketchObject, Part::Part2DObject) SketchObject::SketchObject() { - ADD_PROPERTY_TYPE(Geometry, (nullptr) ,"Sketch",(App::PropertyType)(App::Prop_None),"Sketch geometry"); - ADD_PROPERTY_TYPE(Constraints, (nullptr) ,"Sketch",(App::PropertyType)(App::Prop_None),"Sketch constraints"); - ADD_PROPERTY_TYPE(ExternalGeometry,(nullptr,nullptr),"Sketch",(App::PropertyType)(App::Prop_None),"Sketch external geometry"); - ADD_PROPERTY_TYPE(FullyConstrained, (false),"Sketch",(App::PropertyType)(App::Prop_Output|App::Prop_ReadOnly |App::Prop_Hidden),"Sketch is fully constrained"); + ADD_PROPERTY_TYPE( + Geometry, (nullptr), "Sketch", (App::PropertyType)(App::Prop_None), "Sketch geometry"); + ADD_PROPERTY_TYPE(Constraints, + (nullptr), + "Sketch", + (App::PropertyType)(App::Prop_None), + "Sketch constraints"); + ADD_PROPERTY_TYPE(ExternalGeometry, + (nullptr, nullptr), + "Sketch", + (App::PropertyType)(App::Prop_None), + "Sketch external geometry"); + ADD_PROPERTY_TYPE(FullyConstrained, + (false), + "Sketch", + (App::PropertyType)(App::Prop_Output | App::Prop_ReadOnly | App::Prop_Hidden), + "Sketch is fully constrained"); Geometry.setOrderRelevant(true); allowOtherBody = true; allowUnaligned = true; - for (std::vector::iterator it=ExternalGeo.begin(); it != ExternalGeo.end(); ++it) - if (*it) delete *it; + for (std::vector::iterator it = ExternalGeo.begin(); it != ExternalGeo.end(); + ++it) + if (*it) + delete *it; ExternalGeo.clear(); auto HLine = GeometryTypedFacade::getTypedFacade(); auto VLine = GeometryTypedFacade::getTypedFacade(); - HLine->getTypedGeometry()->setPoints(Base::Vector3d(0,0,0),Base::Vector3d(1,0,0)); - VLine->getTypedGeometry()->setPoints(Base::Vector3d(0,0,0),Base::Vector3d(0,1,0)); + HLine->getTypedGeometry()->setPoints(Base::Vector3d(0, 0, 0), Base::Vector3d(1, 0, 0)); + VLine->getTypedGeometry()->setPoints(Base::Vector3d(0, 0, 0), Base::Vector3d(0, 1, 0)); HLine->setConstruction(true); VLine->setConstruction(true); ExternalGeo.push_back(HLine->getGeometry()); ExternalGeo.push_back(VLine->getGeometry()); - HLine->setOwner(false); // we have transferred the ownership to ExternalGeo - VLine->setOwner(false); // we have transferred the ownership to ExternalGeo + HLine->setOwner(false);// we have transferred the ownership to ExternalGeo + VLine->setOwner(false);// we have transferred the ownership to ExternalGeo rebuildVertexIndex(); - lastDoF=0; - lastHasConflict=false; - lastHasRedundancies=false; - lastHasPartialRedundancies=false; - lastHasMalformedConstraints=false; - lastSolverStatus=0; - lastSolveTime=0; + lastDoF = 0; + lastHasConflict = false; + lastHasRedundancies = false; + lastHasPartialRedundancies = false; + lastHasMalformedConstraints = false; + lastSolverStatus = 0; + lastSolveTime = 0; - solverNeedsUpdate=false; + solverNeedsUpdate = false; - noRecomputes=false; + noRecomputes = false; - ExpressionEngine.setValidator(boost::bind(&Sketcher::SketchObject::validateExpression, this, bp::_1, bp::_2)); + ExpressionEngine.setValidator( + boost::bind(&Sketcher::SketchObject::validateExpression, this, bp::_1, bp::_2)); - constraintsRemovedConn = Constraints.signalConstraintsRemoved.connect(boost::bind(&Sketcher::SketchObject::constraintsRemoved, this, bp::_1)); - constraintsRenamedConn = Constraints.signalConstraintsRenamed.connect(boost::bind(&Sketcher::SketchObject::constraintsRenamed, this, bp::_1)); + constraintsRemovedConn = Constraints.signalConstraintsRemoved.connect( + boost::bind(&Sketcher::SketchObject::constraintsRemoved, this, bp::_1)); + constraintsRenamedConn = Constraints.signalConstraintsRenamed.connect( + boost::bind(&Sketcher::SketchObject::constraintsRenamed, this, bp::_1)); analyser = new SketchAnalysis(this); - internaltransaction=false; - managedoperation=false; + internaltransaction = false; + managedoperation = false; } SketchObject::~SketchObject() { - for (std::vector::iterator it=ExternalGeo.begin(); it != ExternalGeo.end(); ++it) - if (*it) delete *it; + for (std::vector::iterator it = ExternalGeo.begin(); it != ExternalGeo.end(); + ++it) + if (*it) + delete *it; ExternalGeo.clear(); delete analyser; @@ -160,12 +180,12 @@ short SketchObject::mustExecute() const return Part2DObject::mustExecute(); } -App::DocumentObjectExecReturn *SketchObject::execute() +App::DocumentObjectExecReturn* SketchObject::execute() { try { - App::DocumentObjectExecReturn* rtn = Part2DObject::execute();//to positionBySupport - if(rtn!=App::DocumentObject::StdReturn) - //error + App::DocumentObjectExecReturn* rtn = Part2DObject::execute();// to positionBySupport + if (rtn != App::DocumentObject::StdReturn) + // error return rtn; } catch (const Base::Exception& e) { @@ -187,32 +207,32 @@ App::DocumentObjectExecReturn *SketchObject::execute() // ensues int err = this->solve(true); - if (err == -4) { // over-constrained sketch - std::string msg="Over-constrained sketch\n"; + if (err == -4) {// over-constrained sketch + std::string msg = "Over-constrained sketch\n"; appendConflictMsg(lastConflicting, msg); - return new App::DocumentObjectExecReturn(msg.c_str(),this); + return new App::DocumentObjectExecReturn(msg.c_str(), this); } - else if (err == -3) { // conflicting constraints - std::string msg="Sketch with conflicting constraints\n"; + else if (err == -3) {// conflicting constraints + std::string msg = "Sketch with conflicting constraints\n"; appendConflictMsg(lastConflicting, msg); - return new App::DocumentObjectExecReturn(msg.c_str(),this); + return new App::DocumentObjectExecReturn(msg.c_str(), this); } - else if (err == -2) { // redundant constraints - std::string msg="Sketch with redundant constraints\n"; + else if (err == -2) {// redundant constraints + std::string msg = "Sketch with redundant constraints\n"; appendRedundantMsg(lastRedundant, msg); - return new App::DocumentObjectExecReturn(msg.c_str(),this); + return new App::DocumentObjectExecReturn(msg.c_str(), this); } else if (err == -5) { - std::string msg="Sketch with malformed constraints\n"; + std::string msg = "Sketch with malformed constraints\n"; appendMalformedConstraintsMsg(lastMalformedConstraints, msg); - return new App::DocumentObjectExecReturn(msg.c_str(),this); + return new App::DocumentObjectExecReturn(msg.c_str(), this); } - else if (err == -1) { // Solver failed - return new App::DocumentObjectExecReturn("Solving the sketch failed",this); + else if (err == -1) {// Solver failed + return new App::DocumentObjectExecReturn("Solving the sketch failed", this); } - // this is not necessary for sketch representation in edit mode, unless we want to trigger an update of - // the objects that depend on this sketch (like pads) + // this is not necessary for sketch representation in edit mode, unless we want to trigger an + // update of the objects that depend on this sketch (like pads) Shape.setValue(solvedSketch.toShape()); return App::DocumentObject::StdReturn; @@ -220,9 +240,9 @@ App::DocumentObjectExecReturn *SketchObject::execute() int SketchObject::hasConflicts() const { - if (lastDoF < 0) // over-constrained sketch + if (lastDoF < 0)// over-constrained sketch return -2; - if (solvedSketch.hasConflicts()) // conflicting constraints + if (solvedSketch.hasConflicts())// conflicting constraints return -1; return 0; @@ -234,15 +254,16 @@ void SketchObject::retrieveSolverDiagnostics() lastHasRedundancies = solvedSketch.hasRedundancies(); lastHasPartialRedundancies = solvedSketch.hasPartialRedundancies(); lastHasMalformedConstraints = solvedSketch.hasMalformedConstraints(); - lastConflicting=solvedSketch.getConflicting(); - lastRedundant=solvedSketch.getRedundant(); - lastPartiallyRedundant=solvedSketch.getPartiallyRedundant(); - lastMalformedConstraints=solvedSketch.getMalformedConstraints(); + lastConflicting = solvedSketch.getConflicting(); + lastRedundant = solvedSketch.getRedundant(); + lastPartiallyRedundant = solvedSketch.getPartiallyRedundant(); + lastMalformedConstraints = solvedSketch.getMalformedConstraints(); } -int SketchObject::solve(bool updateGeoAfterSolving/*=true*/) +int SketchObject::solve(bool updateGeoAfterSolving /*=true*/) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); // Reset the initial movement in case of a dragging operation was ongoing on the solver. solvedSketch.resetInitMove(); @@ -251,40 +272,42 @@ int SketchObject::solve(bool updateGeoAfterSolving/*=true*/) // updated. It is useful to avoid triggering an OnChange when the goeometry did not change but // the solver needs to be updated. - // We should have an updated Sketcher (sketchobject) geometry or this solve() should not have happened - // therefore we update our sketch solver geometry with the SketchObject one. + // We should have an updated Sketcher (sketchobject) geometry or this solve() should not have + // happened therefore we update our sketch solver geometry with the SketchObject one. // // set up a sketch (including dofs counting and diagnosing of conflicts) - lastDoF = solvedSketch.setUpSketch(getCompleteGeometry(), Constraints.getValues(), - getExternalGeometryCount()); + lastDoF = solvedSketch.setUpSketch( + getCompleteGeometry(), Constraints.getValues(), getExternalGeometryCount()); - // At this point we have the solver information about conflicting/redundant/over-constrained, but the sketch is NOT solved. - // Some examples: - // Redundant: a vertical line, a horizontal line and an angle constraint of 90 degrees between the two lines - // Conflicting: a 80 degrees angle between a vertical line and another line, then adding a horizontal constraint to that other line - // OverConstrained: a conflicting constraint when all other DoF are already constrained (it has more constraints than parameters and the extra constraints are not redundant) + // At this point we have the solver information about conflicting/redundant/over-constrained, + // but the sketch is NOT solved. Some examples: Redundant: a vertical line, a horizontal line + // and an angle constraint of 90 degrees between the two lines Conflicting: a 80 degrees angle + // between a vertical line and another line, then adding a horizontal constraint to that other + // line OverConstrained: a conflicting constraint when all other DoF are already constrained (it + // has more constraints than parameters and the extra constraints are not redundant) - solverNeedsUpdate=false; + solverNeedsUpdate = false; retrieveSolverDiagnostics(); - lastSolveTime=0.0; + lastSolveTime = 0.0; - lastSolverStatus=GCS::Failed; // Failure is default for notifying the user unless otherwise proven + // Failure is default for notifying the user unless otherwise proven + lastSolverStatus = GCS::Failed; - int err=0; + int err = 0; // redundancy is a lower priority problem than conflict/over-constraint/solver error // we set it here because we are indeed going to solve, as we can. However, we still want to // provide the right error code. - if (lastHasRedundancies) { // redundant constraints + if (lastHasRedundancies) {// redundant constraints err = -2; } - if (lastDoF < 0) { // over-constrained sketch + if (lastDoF < 0) {// over-constrained sketch err = -4; } - else if (lastHasConflict) { // conflicting constraints + else if (lastHasConflict) {// conflicting constraints // The situation is exactly the same as in the over-constrained situation. err = -3; } @@ -292,36 +315,44 @@ int SketchObject::solve(bool updateGeoAfterSolving/*=true*/) err = -5; } else { - lastSolverStatus=solvedSketch.solve(); - if (lastSolverStatus != 0){ // solving + lastSolverStatus = solvedSketch.solve(); + if (lastSolverStatus != 0) {// solving err = -1; } } - if(lastHasMalformedConstraints) { - Base::Console().Error(this->getFullLabel(), QT_TRANSLATE_NOOP("Notifications","The Sketch has malformed constraints!") "\n"); + if (lastHasMalformedConstraints) { + Base::Console().Error( + this->getFullLabel(), + QT_TRANSLATE_NOOP("Notifications", "The Sketch has malformed constraints!") "\n"); } - if(lastHasPartialRedundancies) { - Base::Console().Warning(this->getFullLabel(), QT_TRANSLATE_NOOP("Notifications","The Sketch has partially redundant constraints!") "\n"); + if (lastHasPartialRedundancies) { + Base::Console().Warning( + this->getFullLabel(), + QT_TRANSLATE_NOOP("Notifications", + "The Sketch has partially redundant constraints!") "\n"); } - lastSolveTime=solvedSketch.getSolveTime(); + lastSolveTime = solvedSketch.getSolveTime(); - // In uncommon situations, the analysis of QR decomposition leads to full rank, but the result does not converge. - // We avoid marking a sketch as fully constrained when no convergence is achieved. - if(err == 0) { + // In uncommon situations, the analysis of QR decomposition leads to full rank, but the result + // does not converge. We avoid marking a sketch as fully constrained when no convergence is + // achieved. + if (err == 0) { FullyConstrained.setValue(lastDoF == 0); } - + if (err == 0 && updateGeoAfterSolving) { // set the newly solved geometry - std::vector geomlist = solvedSketch.extractGeometry(); + std::vector geomlist = solvedSketch.extractGeometry(); Geometry.setValues(geomlist); - for (std::vector::iterator it = geomlist.begin(); it != geomlist.end(); ++it) - if (*it) delete *it; + for (std::vector::iterator it = geomlist.begin(); it != geomlist.end(); + ++it) + if (*it) + delete *it; } - else if(err <0) { + else if (err < 0) { // if solver failed, invalid constraints were likely added before solving // (see solve in addConstraint), so solver information is definitely invalid. this->Constraints.touch(); @@ -332,25 +363,25 @@ int SketchObject::solve(bool updateGeoAfterSolving/*=true*/) int SketchObject::setDatum(int ConstrId, double Datum) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); // set the changed value for the constraint if (this->Constraints.hasInvalidGeometry()) return -6; - const std::vector &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); if (ConstrId < 0 || ConstrId >= int(vals.size())) return -1; ConstraintType type = vals[ConstrId]->Type; - if (!vals[ConstrId]->isDimensional() && - type != Tangent && //for tangent, value==0 is autodecide, value==Pi/2 is external and value==-Pi/2 is internal - type != Perpendicular) + // for tangent, value==0 is autodecide, value==Pi/2 is external and value==-Pi/2 is internal + if (!vals[ConstrId]->isDimensional() && type != Tangent && type != Perpendicular) return -1; if ((type == Distance || type == Radius || type == Diameter || type == Weight) && Datum <= 0) return (Datum == 0) ? -5 : -4; // copy the list - std::vector newVals(vals); + std::vector newVals(vals); double oldDatum = newVals[ConstrId]->getValue(); newVals[ConstrId] = newVals[ConstrId]->clone(); newVals[ConstrId]->setValue(Datum); @@ -360,24 +391,25 @@ int SketchObject::setDatum(int ConstrId, double Datum) int err = solve(); if (err) - this->Constraints.getValues()[ConstrId]->setValue(oldDatum); // newVals is a shell now + this->Constraints.getValues()[ConstrId]->setValue(oldDatum);// newVals is a shell now return err; } int SketchObject::setDriving(int ConstrId, bool isdriving) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); int ret = testDrivingChange(ConstrId, isdriving); - if(ret < 0) + if (ret < 0) return ret; // copy the list - std::vector newVals(vals); + std::vector newVals(vals); newVals[ConstrId] = newVals[ConstrId]->clone(); newVals[ConstrId]->isDriving = isdriving; @@ -386,15 +418,16 @@ int SketchObject::setDriving(int ConstrId, bool isdriving) if (!isdriving) setExpression(Constraints.createPath(ConstrId), std::shared_ptr()); - if(noRecomputes) // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + if (noRecomputes) solve(); return 0; } -int SketchObject::getDriving(int ConstrId, bool &isdriving) +int SketchObject::getDriving(int ConstrId, bool& isdriving) { - const std::vector &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); if (ConstrId < 0 || ConstrId >= int(vals.size())) return -1; @@ -402,13 +435,13 @@ int SketchObject::getDriving(int ConstrId, bool &isdriving) if (!vals[ConstrId]->isDimensional()) return -1; - isdriving=vals[ConstrId]->isDriving; + isdriving = vals[ConstrId]->isDriving; return 0; } int SketchObject::testDrivingChange(int ConstrId, bool isdriving) { - const std::vector &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); if (ConstrId < 0 || ConstrId >= int(vals.size())) return -1; @@ -416,38 +449,44 @@ int SketchObject::testDrivingChange(int ConstrId, bool isdriving) if (!vals[ConstrId]->isDimensional()) return -2; - if (!(vals[ConstrId]->First>=0 || vals[ConstrId]->Second>=0 || vals[ConstrId]->Third>=0) && isdriving) - return -3; // a constraint that does not have at least one element as not-external-geometry can never be driving. + if (!(vals[ConstrId]->First >= 0 || vals[ConstrId]->Second >= 0 || vals[ConstrId]->Third >= 0) + && isdriving) { + // a constraint that does not have at least one element as not-external-geometry can never + // be driving. + return -3; + } return 0; } int SketchObject::setActive(int ConstrId, bool isactive) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); if (ConstrId < 0 || ConstrId >= int(vals.size())) return -1; // copy the list - std::vector newVals(vals); + std::vector newVals(vals); // clone the changed Constraint - Constraint *constNew = vals[ConstrId]->clone(); + Constraint* constNew = vals[ConstrId]->clone(); constNew->isActive = isactive; newVals[ConstrId] = constNew; this->Constraints.setValues(std::move(newVals)); - if(noRecomputes) // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + if (noRecomputes) solve(); return 0; } -int SketchObject::getActive(int ConstrId, bool &isactive) +int SketchObject::getActive(int ConstrId, bool& isactive) { - const std::vector &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); if (ConstrId < 0 || ConstrId >= int(vals.size())) return -1; @@ -459,22 +498,24 @@ int SketchObject::getActive(int ConstrId, bool &isactive) int SketchObject::toggleActive(int ConstrId) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); if (ConstrId < 0 || ConstrId >= int(vals.size())) return -1; // copy the list - std::vector newVals(vals); + std::vector newVals(vals); // clone the changed Constraint - Constraint *constNew = vals[ConstrId]->clone(); + Constraint* constNew = vals[ConstrId]->clone(); constNew->isActive = !constNew->isActive; newVals[ConstrId] = constNew; this->Constraints.setValues(std::move(newVals)); - if(noRecomputes) // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + if (noRecomputes) solve(); return 0; @@ -484,12 +525,13 @@ int SketchObject::toggleActive(int ConstrId) /// Make all dimensionals Driving/non-Driving int SketchObject::setDatumsDriving(bool isdriving) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector &vals = this->Constraints.getValues(); - std::vector newVals(vals); + const std::vector& vals = this->Constraints.getValues(); + std::vector newVals(vals); - for(size_t i=0; iclone(); newVals[i]->isDriving = isdriving; @@ -498,14 +540,16 @@ int SketchObject::setDatumsDriving(bool isdriving) this->Constraints.setValues(std::move(newVals)); - const std::vector &uvals = this->Constraints.getValues(); // newVals is a shell now + // newVals is a shell now + const std::vector& uvals = this->Constraints.getValues(); for (size_t i = 0; i < uvals.size(); i++) { if (!isdriving && uvals[i]->isDimensional()) setExpression(Constraints.createPath(i), std::shared_ptr()); } - if (noRecomputes) // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + if (noRecomputes) solve(); return 0; @@ -513,26 +557,27 @@ int SketchObject::setDatumsDriving(bool isdriving) int SketchObject::moveDatumsToEnd() { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); - std::vector copy(vals); - std::vector newVals(vals.size()); + std::vector copy(vals); + std::vector newVals(vals.size()); - int addindex= copy.size()-1; + int addindex = copy.size() - 1; // add the dimensionals at the end - for (int i= copy.size()-1 ; i >= 0; i--) { - if(copy[i]->isDimensional()) { + for (int i = copy.size() - 1; i >= 0; i--) { + if (copy[i]->isDimensional()) { newVals[addindex] = copy[i]; addindex--; } } // add the non-dimensionals - for (int i = copy.size()-1; i >= 0; i--) { - if(!copy[i]->isDimensional()) { + for (int i = copy.size() - 1; i >= 0; i--) { + if (!copy[i]->isDimensional()) { newVals[addindex] = copy[i]; addindex--; } @@ -540,7 +585,8 @@ int SketchObject::moveDatumsToEnd() this->Constraints.setValues(std::move(newVals)); - if (noRecomputes) // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + if (noRecomputes) solve(); return 0; @@ -548,18 +594,19 @@ int SketchObject::moveDatumsToEnd() int SketchObject::setVirtualSpace(int ConstrId, bool isinvirtualspace) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); if (ConstrId < 0 || ConstrId >= int(vals.size())) return -1; // copy the list - std::vector newVals(vals); + std::vector newVals(vals); // clone the changed Constraint - Constraint *constNew = vals[ConstrId]->clone(); + Constraint* constNew = vals[ConstrId]->clone(); constNew->isInVirtualSpace = isinvirtualspace; newVals[ConstrId] = constNew; @@ -570,24 +617,25 @@ int SketchObject::setVirtualSpace(int ConstrId, bool isinvirtualspace) int SketchObject::setVirtualSpace(std::vector constrIds, bool isinvirtualspace) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); if (constrIds.empty()) return 0; - std::sort(constrIds.begin(),constrIds.end()); + std::sort(constrIds.begin(), constrIds.end()); - const std::vector< Constraint * > &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); if (constrIds.front() < 0 || constrIds.back() >= int(vals.size())) return -1; - std::vector< Constraint * > newVals(vals); + std::vector newVals(vals); - for(auto cid : constrIds) { + for (auto cid : constrIds) { // clone the changed Constraint - if(vals[cid]->isInVirtualSpace != isinvirtualspace) { - Constraint *constNew = vals[cid]->clone(); + if (vals[cid]->isInVirtualSpace != isinvirtualspace) { + Constraint* constNew = vals[cid]->clone(); constNew->isInVirtualSpace = isinvirtualspace; newVals[cid] = constNew; } @@ -599,32 +647,32 @@ int SketchObject::setVirtualSpace(std::vector constrIds, bool isinvirtualsp } - -int SketchObject::getVirtualSpace(int ConstrId, bool &isinvirtualspace) const +int SketchObject::getVirtualSpace(int ConstrId, bool& isinvirtualspace) const { - const std::vector &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); if (ConstrId < 0 || ConstrId >= int(vals.size())) return -1; - isinvirtualspace=vals[ConstrId]->isInVirtualSpace; + isinvirtualspace = vals[ConstrId]->isInVirtualSpace; return 0; } int SketchObject::toggleVirtualSpace(int ConstrId) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); if (ConstrId < 0 || ConstrId >= int(vals.size())) return -1; // copy the list - std::vector newVals(vals); + std::vector newVals(vals); // clone the changed Constraint - Constraint *constNew = vals[ConstrId]->clone(); + Constraint* constNew = vals[ConstrId]->clone(); constNew->isInVirtualSpace = !constNew->isInVirtualSpace; newVals[ConstrId] = constNew; @@ -636,60 +684,64 @@ int SketchObject::toggleVirtualSpace(int ConstrId) int SketchObject::setUpSketch() { - lastDoF = solvedSketch.setUpSketch(getCompleteGeometry(), Constraints.getValues(), - getExternalGeometryCount()); + lastDoF = solvedSketch.setUpSketch( + getCompleteGeometry(), Constraints.getValues(), getExternalGeometryCount()); retrieveSolverDiagnostics(); - if(lastHasRedundancies || lastDoF < 0 || lastHasConflict || lastHasMalformedConstraints || lastHasPartialRedundancies) + if (lastHasRedundancies || lastDoF < 0 || lastHasConflict || lastHasMalformedConstraints + || lastHasPartialRedundancies) Constraints.touch(); return lastDoF; } -int SketchObject::diagnoseAdditionalConstraints(std::vector additionalconstraints) +int SketchObject::diagnoseAdditionalConstraints( + std::vector additionalconstraints) { auto objectconstraints = Constraints.getValues(); - std::vector allconstraints; - allconstraints.reserve(objectconstraints.size()+additionalconstraints.size()); + std::vector allconstraints; + allconstraints.reserve(objectconstraints.size() + additionalconstraints.size()); std::copy(objectconstraints.begin(), objectconstraints.end(), back_inserter(allconstraints)); - std::copy(additionalconstraints.begin(), additionalconstraints.end(), back_inserter(allconstraints)); + std::copy( + additionalconstraints.begin(), additionalconstraints.end(), back_inserter(allconstraints)); - lastDoF = solvedSketch.setUpSketch(getCompleteGeometry(), allconstraints, - getExternalGeometryCount()); + lastDoF = + solvedSketch.setUpSketch(getCompleteGeometry(), allconstraints, getExternalGeometryCount()); retrieveSolverDiagnostics(); return lastDoF; - } -int SketchObject::movePoint(int GeoId, PointPos PosId, const Base::Vector3d& toPoint, bool relative, bool updateGeoBeforeMoving) +int SketchObject::movePoint(int GeoId, PointPos PosId, const Base::Vector3d& toPoint, bool relative, + bool updateGeoBeforeMoving) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); // if we are moving a point at SketchObject level, we need to start from a solved sketch // if we have conflicts we can forget about moving. However, there is the possibility that we - // need to do programmatically moves of new geometry that has not been solved yet and that because - // they were programmatically generated won't generate a conflict. This is the case of Fillet for - // example. This is why exceptionally, it may be required to update the sketch geometry to that of - // of SketchObject upon moving. => use updateGeometry parameter = true then + // need to do programmatically moves of new geometry that has not been solved yet and that + // because they were programmatically generated won't generate a conflict. This is the case of + // Fillet for example. This is why exceptionally, it may be required to update the sketch + // geometry to that of of SketchObject upon moving. => use updateGeometry parameter = true then - if(updateGeoBeforeMoving || solverNeedsUpdate) { - lastDoF = solvedSketch.setUpSketch(getCompleteGeometry(), Constraints.getValues(), - getExternalGeometryCount()); + if (updateGeoBeforeMoving || solverNeedsUpdate) { + lastDoF = solvedSketch.setUpSketch( + getCompleteGeometry(), Constraints.getValues(), getExternalGeometryCount()); retrieveSolverDiagnostics(); - solverNeedsUpdate=false; + solverNeedsUpdate = false; } - if (lastDoF < 0) // over-constrained sketch + if (lastDoF < 0)// over-constrained sketch return -1; - if (lastHasConflict) // conflicting constraints + if (lastHasConflict)// conflicting constraints return -1; // move the point and solve @@ -699,77 +751,87 @@ int SketchObject::movePoint(int GeoId, PointPos PosId, const Base::Vector3d& toP // or a redundancy that we did not have before, or a change of DoF if (lastSolverStatus == 0) { - std::vector geomlist = solvedSketch.extractGeometry(); + std::vector geomlist = solvedSketch.extractGeometry(); Geometry.setValues(geomlist); - //Constraints.acceptGeometry(getCompleteGeometry()); - for (std::vector::iterator it=geomlist.begin(); it != geomlist.end(); ++it) { - if (*it) delete *it; + // Constraints.acceptGeometry(getCompleteGeometry()); + for (std::vector::iterator it = geomlist.begin(); it != geomlist.end(); + ++it) { + if (*it) + delete *it; } } - solvedSketch.resetInitMove(); // reset solver point moving mechanism + solvedSketch.resetInitMove();// reset solver point moving mechanism return lastSolverStatus; } Base::Vector3d SketchObject::getPoint(int GeoId, PointPos PosId) const { - if(!(GeoId == H_Axis || GeoId == V_Axis - || (GeoId <= getHighestCurveIndex() && GeoId >= -getExternalGeometryCount()) )) + if (!(GeoId == H_Axis || GeoId == V_Axis + || (GeoId <= getHighestCurveIndex() && GeoId >= -getExternalGeometryCount()))) throw Base::ValueError("SketchObject::getPoint. Invalid GeoId was supplied."); - const Part::Geometry *geo = getGeometry(GeoId); + const Part::Geometry* geo = getGeometry(GeoId); if (geo->getTypeId() == Part::GeomPoint::getClassTypeId()) { - const Part::GeomPoint *p = static_cast(geo); + const Part::GeomPoint* p = static_cast(geo); if (PosId == PointPos::start || PosId == PointPos::mid || PosId == PointPos::end) return p->getPoint(); - } else if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* lineSeg = static_cast(geo); if (PosId == PointPos::start) return lineSeg->getStartPoint(); else if (PosId == PointPos::end) return lineSeg->getEndPoint(); - } else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { + const Part::GeomCircle* circle = static_cast(geo); if (PosId == PointPos::mid) return circle->getCenter(); - } else if (geo->getTypeId() == Part::GeomEllipse::getClassTypeId()) { - const Part::GeomEllipse *ellipse = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomEllipse::getClassTypeId()) { + const Part::GeomEllipse* ellipse = static_cast(geo); if (PosId == PointPos::mid) return ellipse->getCenter(); - } else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *aoc = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* aoc = static_cast(geo); if (PosId == PointPos::start) return aoc->getStartPoint(/*emulateCCW=*/true); else if (PosId == PointPos::end) return aoc->getEndPoint(/*emulateCCW=*/true); else if (PosId == PointPos::mid) return aoc->getCenter(); - } else if (geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { - const Part::GeomArcOfEllipse *aoc = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { + const Part::GeomArcOfEllipse* aoc = static_cast(geo); if (PosId == PointPos::start) return aoc->getStartPoint(/*emulateCCW=*/true); else if (PosId == PointPos::end) return aoc->getEndPoint(/*emulateCCW=*/true); else if (PosId == PointPos::mid) return aoc->getCenter(); - } else if (geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { - const Part::GeomArcOfHyperbola *aoh = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + const Part::GeomArcOfHyperbola* aoh = static_cast(geo); if (PosId == PointPos::start) return aoh->getStartPoint(); else if (PosId == PointPos::end) return aoh->getEndPoint(); else if (PosId == PointPos::mid) return aoh->getCenter(); - } else if (geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { - const Part::GeomArcOfParabola *aop = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + const Part::GeomArcOfParabola* aop = static_cast(geo); if (PosId == PointPos::start) return aop->getStartPoint(); else if (PosId == PointPos::end) return aop->getEndPoint(); else if (PosId == PointPos::mid) return aop->getCenter(); - } else if (geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { - const Part::GeomBSplineCurve *bsp = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { + const Part::GeomBSplineCurve* bsp = static_cast(geo); if (PosId == PointPos::start) return bsp->getStartPoint(); else if (PosId == PointPos::end) @@ -781,13 +843,12 @@ Base::Vector3d SketchObject::getPoint(int GeoId, PointPos PosId) const int SketchObject::getAxisCount() const { - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); - int count=0; - for (std::vector::const_iterator geo=vals.begin(); - geo != vals.end(); geo++) - if ((*geo) && GeometryFacade::getConstruction(*geo) && - (*geo)->getTypeId() == Part::GeomLineSegment::getClassTypeId()) + int count = 0; + for (std::vector::const_iterator geo = vals.begin(); geo != vals.end(); geo++) + if ((*geo) && GeometryFacade::getConstruction(*geo) + && (*geo)->getTypeId() == Part::GeomLineSegment::getClassTypeId()) count++; return count; @@ -798,17 +859,16 @@ Base::Axis SketchObject::getAxis(int axId) const if (axId == H_Axis || axId == V_Axis || axId == N_Axis) return Part::Part2DObject::getAxis(axId); - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); - int count=0; - for (std::vector::const_iterator geo=vals.begin(); - geo != vals.end(); geo++) - if ((*geo) && GeometryFacade::getConstruction(*geo) && - (*geo)->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const std::vector& vals = getInternalGeometry(); + int count = 0; + for (std::vector::const_iterator geo = vals.begin(); geo != vals.end(); geo++) + if ((*geo) && GeometryFacade::getConstruction(*geo) + && (*geo)->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { if (count == axId) { - Part::GeomLineSegment *lineSeg = static_cast(*geo); + Part::GeomLineSegment* lineSeg = static_cast(*geo); Base::Vector3d start = lineSeg->getStartPoint(); Base::Vector3d end = lineSeg->getEndPoint(); - return Base::Axis(start, end-start); + return Base::Axis(start, end - start); } count++; } @@ -822,17 +882,17 @@ void SketchObject::acceptGeometry() rebuildVertexIndex(); } -bool SketchObject::isSupportedGeometry(const Part::Geometry *geo) const +bool SketchObject::isSupportedGeometry(const Part::Geometry* geo) const { - if (geo->getTypeId() == Part::GeomPoint::getClassTypeId() || - geo->getTypeId() == Part::GeomCircle::getClassTypeId() || - geo->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() || - geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() || - geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + if (geo->getTypeId() == Part::GeomPoint::getClassTypeId() + || geo->getTypeId() == Part::GeomCircle::getClassTypeId() + || geo->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() + || geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() + || geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { return true; } if (geo->getTypeId() == Part::GeomTrimmedCurve::getClassTypeId()) { @@ -846,12 +906,14 @@ bool SketchObject::isSupportedGeometry(const Part::Geometry *geo) const return false; } -std::vector SketchObject::supportedGeometry(const std::vector &geoList) const +std::vector +SketchObject::supportedGeometry(const std::vector& geoList) const { - std::vector supportedGeoList; + std::vector supportedGeoList; supportedGeoList.reserve(geoList.size()); // read-in geometry that the sketcher cannot handle - for (std::vector::const_iterator it = geoList.begin(); it != geoList.end(); ++it) { + for (std::vector::const_iterator it = geoList.begin(); it != geoList.end(); + ++it) { if (isSupportedGeometry(*it)) { supportedGeoList.push_back(*it); } @@ -860,86 +922,92 @@ std::vector SketchObject::supportedGeometry(const std::vector< return supportedGeoList; } -int SketchObject::addGeometry(const std::vector &geoList, bool construction/*=false*/) +int SketchObject::addGeometry(const std::vector& geoList, + bool construction /*=false*/) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); - std::vector< Part::Geometry * > newVals(vals); + std::vector newVals(vals); newVals.reserve(newVals.size() + geoList.size()); - for( auto & v : geoList) { + for (auto& v : geoList) { Part::Geometry* copy = v->copy(); - if( copy->getTypeId() == Part::GeomPoint::getClassTypeId()) { + if (copy->getTypeId() == Part::GeomPoint::getClassTypeId()) { // creation mode for points is always construction not to // break legacy code GeometryFacade::setConstruction(copy, true); } - else if(construction) { + else if (construction) { GeometryFacade::setConstruction(copy, construction); } newVals.push_back(copy); } - // On setting geometry the onChanged method will call acceptGeometry(), thereby updating constraint geometry indices and rebuilding the vertex index + // On setting geometry the onChanged method will call acceptGeometry(), thereby updating + // constraint geometry indices and rebuilding the vertex index Geometry.setValues(std::move(newVals)); - return Geometry.getSize()-1; + return Geometry.getSize() - 1; } -int SketchObject::addGeometry(const Part::Geometry *geo, bool construction/*=false*/) +int SketchObject::addGeometry(const Part::Geometry* geo, bool construction /*=false*/) { // this copy has a new random tag (see copy() vs clone()) auto geoNew = std::unique_ptr(geo->copy()); - return addGeometry(std::move(geoNew),construction); + return addGeometry(std::move(geoNew), construction); } -int SketchObject::addGeometry(std::unique_ptr newgeo, bool construction/*=false*/) +int SketchObject::addGeometry(std::unique_ptr newgeo, bool construction /*=false*/) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); - std::vector< Part::Geometry * > newVals(vals); + std::vector newVals(vals); - auto *geoNew = newgeo.release(); + auto* geoNew = newgeo.release(); - if( geoNew->getTypeId() == Part::GeomPoint::getClassTypeId()) { + if (geoNew->getTypeId() == Part::GeomPoint::getClassTypeId()) { // creation mode for points is always construction not to // break legacy code GeometryFacade::setConstruction(geoNew, true); } - else if(construction) { + else if (construction) { GeometryFacade::setConstruction(geoNew, construction); } newVals.push_back(geoNew); - // On setting geometry the onChanged method will call acceptGeometry(), thereby updating constraint geometry indices and rebuilding the vertex index + // On setting geometry the onChanged method will call acceptGeometry(), thereby updating + // constraint geometry indices and rebuilding the vertex index Geometry.setValues(std::move(newVals)); - return Geometry.getSize()-1; + return Geometry.getSize() - 1; } int SketchObject::delGeometry(int GeoId, bool deleteinternalgeo) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); if (GeoId < 0 || GeoId >= int(vals.size())) return -1; if (deleteinternalgeo) { - const Part::Geometry *geo = getGeometry(GeoId); + const Part::Geometry* geo = getGeometry(GeoId); // Only for supported types - if ((geo->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() || - geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId())) { + if ((geo->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() + || geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId())) { this->deleteUnusedInternalGeometry(GeoId, true); @@ -947,23 +1015,24 @@ int SketchObject::delGeometry(int GeoId, bool deleteinternalgeo) } } - std::vector< Part::Geometry * > newVals(vals); - newVals.erase(newVals.begin()+GeoId); + std::vector newVals(vals); + newVals.erase(newVals.begin() + GeoId); // Find coincident points to replace the points of the deleted geometry std::vector GeoIdList; std::vector PosIdList; - for (PointPos PosId = PointPos::start; PosId != PointPos::mid; ) { + for (PointPos PosId = PointPos::start; PosId != PointPos::mid;) { getDirectlyCoincidentPoints(GeoId, PosId, GeoIdList, PosIdList); if (GeoIdList.size() > 1) { delConstraintOnPoint(GeoId, PosId, true /* only coincidence */); transferConstraints(GeoIdList[0], PosIdList[0], GeoIdList[1], PosIdList[1]); } - PosId = (PosId == PointPos::start) ? PointPos::end : PointPos::mid; // loop through [start, end, mid] + // loop through [start, end, mid] + PosId = (PosId == PointPos::start) ? PointPos::end : PointPos::mid; } - const std::vector< Constraint * > &constraints = this->Constraints.getValues(); - std::vector< Constraint * > newConstraints; + const std::vector& constraints = this->Constraints.getValues(); + std::vector newConstraints; newConstraints.reserve(constraints.size()); for (auto cstr : constraints) { if (cstr->First == GeoId || cstr->Second == GeoId || cstr->Third == GeoId) @@ -987,10 +1056,12 @@ int SketchObject::delGeometry(int GeoId, bool deleteinternalgeo) this->Constraints.setValues(std::move(newConstraints)); } - // Update geometry indices and rebuild vertexindex now via onChanged, so that ViewProvider::UpdateData is triggered. + // Update geometry indices and rebuild vertexindex now via onChanged, so that + // ViewProvider::UpdateData is triggered. Geometry.touch(); - if(noRecomputes) // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + if (noRecomputes) solve(); return 0; @@ -1002,11 +1073,11 @@ int SketchObject::delGeometries(const std::vector& GeoIds) std::vector sGeoIds(GeoIds); // if a GeoId has internal geometry, it must delete internal geometries too - for(auto c : Constraints.getValues()) { - if( c->Type == InternalAlignment ) { + for (auto c : Constraints.getValues()) { + if (c->Type == InternalAlignment) { auto pos = std::find(sGeoIds.begin(), sGeoIds.end(), c->Second); - if(pos != sGeoIds.end()) { + if (pos != sGeoIds.end()) { sGeoIds.push_back(c->First); } } @@ -1028,14 +1099,15 @@ int SketchObject::delGeometriesExclusiveList(const std::vector& GeoIds) if (sGeoIds.empty()) return 0; - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); if (sGeoIds.front() < 0 || sGeoIds.back() >= int(vals.size())) return -1; - std::vector< Part::Geometry * > newVals(vals); + std::vector newVals(vals); for (auto it = sGeoIds.rbegin(); it != sGeoIds.rend(); ++it) { int GeoId = *it; newVals.erase(newVals.begin() + GeoId); @@ -1043,25 +1115,27 @@ int SketchObject::delGeometriesExclusiveList(const std::vector& GeoIds) // Find coincident points to replace the points of the deleted geometry std::vector GeoIdList; std::vector PosIdList; - for (PointPos PosId = PointPos::start; PosId != PointPos::mid; ) { + for (PointPos PosId = PointPos::start; PosId != PointPos::mid;) { getDirectlyCoincidentPoints(GeoId, PosId, GeoIdList, PosIdList); if (GeoIdList.size() > 1) { delConstraintOnPoint(GeoId, PosId, true /* only coincidence */); transferConstraints(GeoIdList[0], PosIdList[0], GeoIdList[1], PosIdList[1]); } - PosId = (PosId == PointPos::start) ? PointPos::end : PointPos::mid; // loop through [start, end, mid] + // loop through [start, end, mid] + PosId = (PosId == PointPos::start) ? PointPos::end : PointPos::mid; } } // Copy the original constraints - std::vector< Constraint* > constraints; + std::vector constraints; for (const auto ptr : this->Constraints.getValues()) constraints.push_back(ptr->clone()); - std::vector< Constraint* > filteredConstraints(0); + std::vector filteredConstraints(0); for (auto itGeo = sGeoIds.rbegin(); itGeo != sGeoIds.rend(); ++itGeo) { int GeoId = *itGeo; for (std::vector::const_iterator it = constraints.begin(); - it != constraints.end(); ++it) { + it != constraints.end(); + ++it) { Constraint* copiedConstr(*it); if ((*it)->First != GeoId && (*it)->Second != GeoId && (*it)->Third != GeoId) { @@ -1088,10 +1162,12 @@ int SketchObject::delGeometriesExclusiveList(const std::vector& GeoIds) this->Geometry.setValues(newVals); this->Constraints.setValues(std::move(constraints)); } - // Update geometry indices and rebuild vertexindex now via onChanged, so that ViewProvider::UpdateData is triggered. + // Update geometry indices and rebuild vertexindex now via onChanged, so that + // ViewProvider::UpdateData is triggered. Geometry.touch(); - if (noRecomputes) // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + if (noRecomputes) solve(); return 0; @@ -1099,10 +1175,11 @@ int SketchObject::delGeometriesExclusiveList(const std::vector& GeoIds) int SketchObject::deleteAllGeometry() { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - std::vector< Part::Geometry * > newVals(0); - std::vector< Constraint * > newConstraints(0); + std::vector newVals(0); + std::vector newConstraints(0); // Avoid unnecessary updates and checks as this is a transaction { @@ -1110,10 +1187,12 @@ int SketchObject::deleteAllGeometry() this->Geometry.setValues(newVals); this->Constraints.setValues(newConstraints); } - // Update geometry indices and rebuild vertexindex now via onChanged, so that ViewProvider::UpdateData is triggered. + // Update geometry indices and rebuild vertexindex now via onChanged, so that + // ViewProvider::UpdateData is triggered. Geometry.touch(); - if(noRecomputes) // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + if (noRecomputes) solve(); return 0; @@ -1121,13 +1200,15 @@ int SketchObject::deleteAllGeometry() int SketchObject::deleteAllConstraints() { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - std::vector< Constraint * > newConstraints(0); + std::vector newConstraints(0); this->Constraints.setValues(newConstraints); - if(noRecomputes) // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + if (noRecomputes) solve(); return 0; @@ -1135,54 +1216,58 @@ int SketchObject::deleteAllConstraints() int SketchObject::toggleConstruction(int GeoId) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); if (GeoId < 0 || GeoId >= int(vals.size())) return -1; - if(getGeometryFacade(GeoId)->isInternalAligned()) + if (getGeometryFacade(GeoId)->isInternalAligned()) return -1; - // While it may seem that there is not a need to trigger an update at this time, because the solver has its own copy of the geometry, - // and updateColors of the viewprovider may be triggered by the clearselection of the UI command, this won't update the elements widget, - // in the accumulative of actions it is judged that it is worth to trigger an update here. + // While it may seem that there is not a need to trigger an update at this time, because the + // solver has its own copy of the geometry, and updateColors of the viewprovider may be + // triggered by the clearselection of the UI command, this won't update the elements widget, in + // the accumulative of actions it is judged that it is worth to trigger an update here. std::unique_ptr geo(vals[GeoId]->clone()); auto gft = GeometryFacade::getFacade(geo.get()); gft->setConstruction(!gft->getConstruction()); this->Geometry.set1Value(GeoId, std::move(geo)); - solverNeedsUpdate=true; + solverNeedsUpdate = true; return 0; } int SketchObject::setConstruction(int GeoId, bool on) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); if (GeoId < 0 || GeoId >= int(vals.size())) return -1; - if(getGeometryFacade(GeoId)->isInternalAligned()) + if (getGeometryFacade(GeoId)->isInternalAligned()) return -1; - // While it may seem that there is not a need to trigger an update at this time, because the solver has its own copy of the geometry, - // and updateColors of the viewprovider may be triggered by the clearselection of the UI command, this won't update the elements widget, - // in the accumulative of actions it is judged that it is worth to trigger an update here. + // While it may seem that there is not a need to trigger an update at this time, because the + // solver has its own copy of the geometry, and updateColors of the viewprovider may be + // triggered by the clearselection of the UI command, this won't update the elements widget, in + // the accumulative of actions it is judged that it is worth to trigger an update here. std::unique_ptr geo(vals[GeoId]->clone()); GeometryFacade::setConstruction(geo.get(), on); this->Geometry.set1Value(GeoId, std::move(geo)); - solverNeedsUpdate=true; + solverNeedsUpdate = true; return 0; } void SketchObject::addGeometryState(const Constraint* cstr) const { - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); Sketcher::InternalType::InternalType constraintInternalAlignment = InternalType::None; bool constraintBlockedState = false; @@ -1199,35 +1284,36 @@ void SketchObject::addGeometryState(const Constraint* cstr) const void SketchObject::removeGeometryState(const Constraint* cstr) const { - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); // Assign correct Internal Geometry Type (see SketchGeometryExtension) - if(cstr->Type == InternalAlignment) { + if (cstr->Type == InternalAlignment) { auto gf = GeometryFacade::getFacade(vals[cstr->First]); gf->setInternalType(InternalType::None); } // Assign Blocked geometry mode (see SketchGeometryExtension) - if(cstr->Type == Block){ + if (cstr->Type == Block) { auto gf = GeometryFacade::getFacade(vals[cstr->First]); gf->setBlocked(false); } } -//ConstraintList is used only to make copies. -int SketchObject::addConstraints(const std::vector &ConstraintList) +// ConstraintList is used only to make copies. +int SketchObject::addConstraints(const std::vector& ConstraintList) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector< Constraint * > &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); - std::vector< Constraint * > newVals(vals); + std::vector newVals(vals); newVals.insert(newVals.end(), ConstraintList.begin(), ConstraintList.end()); - for(std::size_t i = newVals.size()-ConstraintList.size(); iclone(); + for (std::size_t i = newVals.size() - ConstraintList.size(); i < newVals.size(); i++) { + Constraint* cnew = newVals[i]->clone(); newVals[i] = cnew; - if( cnew->Type == Tangent || cnew->Type == Perpendicular ){ + if (cnew->Type == Tangent || cnew->Type == Perpendicular) { AutoLockTangencyAndPerpty(cnew); } @@ -1236,48 +1322,50 @@ int SketchObject::addConstraints(const std::vector &ConstraintList this->Constraints.setValues(std::move(newVals)); - return this->Constraints.getSize()-1; + return this->Constraints.getSize() - 1; } -int SketchObject::addCopyOfConstraints(const SketchObject &orig) +int SketchObject::addCopyOfConstraints(const SketchObject& orig) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector< Constraint * > &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); - const std::vector< Constraint * > &origvals = orig.Constraints.getValues(); + const std::vector& origvals = orig.Constraints.getValues(); - std::vector< Constraint * > newVals(vals); + std::vector newVals(vals); - newVals.reserve(vals.size()+origvals.size()); + newVals.reserve(vals.size() + origvals.size()); - for( auto & v : origvals ) + for (auto& v : origvals) newVals.push_back(v->copy()); this->Constraints.setValues(std::move(newVals)); - auto & uvals = this->Constraints.getValues(); + auto& uvals = this->Constraints.getValues(); std::size_t uvalssize = uvals.size(); - for(std::size_t i = uvalssize, j = 0; iisDriving && uvals[i]->isDimensional()) { + for (std::size_t i = uvalssize, j = 0; i < uvals.size(); i++, j++) { + if (uvals[i]->isDriving && uvals[i]->isDimensional()) { App::ObjectIdentifier spath = orig.Constraints.createPath(j); App::PropertyExpressionEngine::ExpressionInfo expr_info = orig.getExpression(spath); - if (expr_info.expression) { // if there is an expression on the source dimensional + if (expr_info.expression) {// if there is an expression on the source dimensional App::ObjectIdentifier dpath = this->Constraints.createPath(i); - setExpression(dpath, std::shared_ptr(expr_info.expression->copy())); + setExpression(dpath, + std::shared_ptr(expr_info.expression->copy())); } } } - return this->Constraints.getSize()-1; + return this->Constraints.getSize() - 1; } -int SketchObject::addConstraint(const Constraint *constraint) +int SketchObject::addConstraint(const Constraint* constraint) { auto constraint_ptr = std::unique_ptr(constraint->clone()); @@ -1286,41 +1374,44 @@ int SketchObject::addConstraint(const Constraint *constraint) int SketchObject::addConstraint(std::unique_ptr constraint) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector< Constraint * > &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); - std::vector< Constraint * > newVals(vals); + std::vector newVals(vals); - Constraint *constNew = constraint.release(); + Constraint* constNew = constraint.release(); if (constNew->Type == Tangent || constNew->Type == Perpendicular) AutoLockTangencyAndPerpty(constNew); addGeometryState(constNew); - newVals.push_back(constNew); // add new constraint at the back + newVals.push_back(constNew);// add new constraint at the back this->Constraints.setValues(std::move(newVals)); - return this->Constraints.getSize()-1; + return this->Constraints.getSize() - 1; } int SketchObject::delConstraint(int ConstrId) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector< Constraint * > &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); if (ConstrId < 0 || ConstrId >= int(vals.size())) return -1; - std::vector< Constraint * > newVals(vals); - auto ctriter = newVals.begin()+ConstrId; + std::vector newVals(vals); + auto ctriter = newVals.begin() + ConstrId; removeGeometryState(*ctriter); newVals.erase(ctriter); this->Constraints.setValues(std::move(newVals)); - if(noRecomputes) // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + if (noRecomputes) solve(); return 0; @@ -1328,28 +1419,30 @@ int SketchObject::delConstraint(int ConstrId) int SketchObject::delConstraints(std::vector ConstrIds, bool updategeometry) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); if (ConstrIds.empty()) return 0; - const std::vector< Constraint * > &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); - std::vector< Constraint * > newVals(vals); + std::vector newVals(vals); - std::sort(ConstrIds.begin(),ConstrIds.end()); + std::sort(ConstrIds.begin(), ConstrIds.end()); if (ConstrIds.front() < 0 || ConstrIds.back() >= int(vals.size())) return -1; - for(auto rit = ConstrIds.rbegin(); rit!=ConstrIds.rend(); rit++) { - auto ctriter = newVals.begin()+*rit; + for (auto rit = ConstrIds.rbegin(); rit != ConstrIds.rend(); rit++) { + auto ctriter = newVals.begin() + *rit; removeGeometryState(*ctriter); newVals.erase(ctriter); } this->Constraints.setValues(std::move(newVals)); - if(noRecomputes) // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + if (noRecomputes) solve(updategeometry); return 0; @@ -1359,10 +1452,11 @@ int SketchObject::delConstraintOnPoint(int VertexId, bool onlyCoincident) { int GeoId; PointPos PosId; - if (VertexId == GeoEnum::RtPnt) { // RootPoint + if (VertexId == GeoEnum::RtPnt) {// RootPoint GeoId = Sketcher::GeoEnum::RtPnt; PosId = PointPos::start; - } else + } + else getGeoVertexIndex(VertexId, GeoId, PosId); return delConstraintOnPoint(GeoId, PosId, onlyCoincident); @@ -1370,15 +1464,16 @@ int SketchObject::delConstraintOnPoint(int VertexId, bool onlyCoincident) int SketchObject::delConstraintOnPoint(int GeoId, PointPos PosId, bool onlyCoincident) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); // check if constraints can be redirected to some other point - int replaceGeoId=GeoEnum::GeoUndef; - PointPos replacePosId=Sketcher::PointPos::none; + int replaceGeoId = GeoEnum::GeoUndef; + PointPos replacePosId = Sketcher::PointPos::none; if (!onlyCoincident) { - for (std::vector::const_iterator it = vals.begin(); it != vals.end(); ++it) { + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); ++it) { if ((*it)->Type == Sketcher::Coincident) { if ((*it)->First == GeoId && (*it)->FirstPos == PosId) { replaceGeoId = (*it)->Second; @@ -1395,82 +1490,84 @@ int SketchObject::delConstraintOnPoint(int GeoId, PointPos PosId, bool onlyCoinc } // remove or redirect any constraints associated with the given point - std::vector newVals(0); - for (std::vector::const_iterator it = vals.begin(); it != vals.end(); ++it) { + std::vector newVals(0); + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); ++it) { if ((*it)->Type == Sketcher::Coincident) { if ((*it)->First == GeoId && (*it)->FirstPos == PosId) { - if (replaceGeoId != GeoEnum::GeoUndef && - (replaceGeoId != (*it)->Second || replacePosId != (*it)->SecondPos)) { // redirect this constraint + // redirect this constraint + if (replaceGeoId != GeoEnum::GeoUndef + && (replaceGeoId != (*it)->Second || replacePosId != (*it)->SecondPos)) { (*it)->First = replaceGeoId; (*it)->FirstPos = replacePosId; } else - continue; // skip this constraint + continue;// skip this constraint } else if ((*it)->Second == GeoId && (*it)->SecondPos == PosId) { - if (replaceGeoId != GeoEnum::GeoUndef && - (replaceGeoId != (*it)->First || replacePosId != (*it)->FirstPos)) { // redirect this constraint + // redirect this constraint + if (replaceGeoId != GeoEnum::GeoUndef + && (replaceGeoId != (*it)->First || replacePosId != (*it)->FirstPos)) { (*it)->Second = replaceGeoId; (*it)->SecondPos = replacePosId; } else - continue; // skip this constraint + continue;// skip this constraint } } else if (!onlyCoincident) { - if ((*it)->Type == Sketcher::Distance || - (*it)->Type == Sketcher::DistanceX || (*it)->Type == Sketcher::DistanceY) { - if ((*it)->First == GeoId && (*it)->FirstPos == PointPos::none && - (PosId == PointPos::start || PosId == PointPos::end)) { + if ((*it)->Type == Sketcher::Distance || (*it)->Type == Sketcher::DistanceX + || (*it)->Type == Sketcher::DistanceY) { + if ((*it)->First == GeoId && (*it)->FirstPos == PointPos::none + && (PosId == PointPos::start || PosId == PointPos::end)) { // remove the constraint even if it is not directly associated // with the given point - continue; // skip this constraint + continue;// skip this constraint } else if ((*it)->First == GeoId && (*it)->FirstPos == PosId) { - if (replaceGeoId != GeoEnum::GeoUndef) { // redirect this constraint + if (replaceGeoId != GeoEnum::GeoUndef) {// redirect this constraint (*it)->First = replaceGeoId; (*it)->FirstPos = replacePosId; } else - continue; // skip this constraint + continue;// skip this constraint } else if ((*it)->Second == GeoId && (*it)->SecondPos == PosId) { - if (replaceGeoId != GeoEnum::GeoUndef) { // redirect this constraint + if (replaceGeoId != GeoEnum::GeoUndef) {// redirect this constraint (*it)->Second = replaceGeoId; (*it)->SecondPos = replacePosId; } else - continue; // skip this constraint + continue;// skip this constraint } } else if ((*it)->Type == Sketcher::PointOnObject) { if ((*it)->First == GeoId && (*it)->FirstPos == PosId) { - if (replaceGeoId != GeoEnum::GeoUndef) { // redirect this constraint + if (replaceGeoId != GeoEnum::GeoUndef) {// redirect this constraint (*it)->First = replaceGeoId; (*it)->FirstPos = replacePosId; } else - continue; // skip this constraint + continue;// skip this constraint } } else if ((*it)->Type == Sketcher::Tangent || (*it)->Type == Sketcher::Perpendicular) { - if (((*it)->First == GeoId && (*it)->FirstPos == PosId) || - ((*it)->Second == GeoId && (*it)->SecondPos == PosId)) { + if (((*it)->First == GeoId && (*it)->FirstPos == PosId) + || ((*it)->Second == GeoId && (*it)->SecondPos == PosId)) { // we could keep the tangency constraint by converting it // to a simple one but it is not really worth - continue; // skip this constraint + continue;// skip this constraint } } else if ((*it)->Type == Sketcher::Symmetric) { - if (((*it)->First == GeoId && (*it)->FirstPos == PosId) || - ((*it)->Second == GeoId && (*it)->SecondPos == PosId)) { - continue; // skip this constraint + if (((*it)->First == GeoId && (*it)->FirstPos == PosId) + || ((*it)->Second == GeoId && (*it)->SecondPos == PosId)) { + continue;// skip this constraint } } else if ((*it)->Type == Sketcher::Vertical || (*it)->Type == Sketcher::Horizontal) { - if (((*it)->First == GeoId && (*it)->FirstPos == PosId) || - ((*it)->Second == GeoId && (*it)->SecondPos == PosId)) { - continue; // skip this constraint + if (((*it)->First == GeoId && (*it)->FirstPos == PosId) + || ((*it)->Second == GeoId && (*it)->SecondPos == PosId)) { + continue;// skip this constraint } } } @@ -1482,10 +1579,12 @@ int SketchObject::delConstraintOnPoint(int GeoId, PointPos PosId, bool onlyCoinc return 0; } - return -1; // no such constraint + return -1;// no such constraint } -void SketchObject::transferFilletConstraints(int geoId1, PointPos posId1, int geoId2, PointPos posId2) { +void SketchObject::transferFilletConstraints(int geoId1, PointPos posId1, int geoId2, + PointPos posId2) +{ // If the lines don't intersect, there's no original corner to work with so // don't try to transfer the constraints. But we should delete line length and equal // constraints and constraints on the affected endpoints because they're about @@ -1496,15 +1595,15 @@ void SketchObject::transferFilletConstraints(int geoId1, PointPos posId1, int ge delConstraintOnPoint(geoId2, posId2, false); // Delete line length and equal constraints - const std::vector &constraints = this->Constraints.getValues(); + const std::vector& constraints = this->Constraints.getValues(); std::vector deleteme; - for (int i=0; i < int(constraints.size()); i++) { - const Constraint *c = constraints[i]; + for (int i = 0; i < int(constraints.size()); i++) { + const Constraint* c = constraints[i]; if (c->Type == Sketcher::Distance || c->Type == Sketcher::Equal) { bool line1 = c->First == geoId1 && c->FirstPos == PointPos::none; bool line2 = c->First == geoId2 && c->FirstPos == PointPos::none; if (line1 || line2) { - deleteme.push_back(i); + deleteme.push_back(i); } } } @@ -1514,22 +1613,22 @@ void SketchObject::transferFilletConstraints(int geoId1, PointPos posId1, int ge // If the lines aren't straight, don't try to transfer the constraints. // TODO: Add support for curved lines. - const Part::Geometry *geo1 = getGeometry(geoId1); - const Part::Geometry *geo2 = getGeometry(geoId2); - if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() || - geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId() ) { + const Part::Geometry* geo1 = getGeometry(geoId1); + const Part::Geometry* geo2 = getGeometry(geoId2); + if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() + || geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { delConstraintOnPoint(geoId1, posId1, false); delConstraintOnPoint(geoId2, posId2, false); return; } // Add a vertex to preserve the original intersection of the filleted lines - Part::GeomPoint *originalCorner = new Part::GeomPoint(getPoint(geoId1, posId1)); + Part::GeomPoint* originalCorner = new Part::GeomPoint(getPoint(geoId1, posId1)); int originalCornerId = addGeometry(originalCorner); delete originalCorner; // Constrain the vertex to the two lines - Sketcher::Constraint *cornerToLine1 = new Sketcher::Constraint(); + Sketcher::Constraint* cornerToLine1 = new Sketcher::Constraint(); cornerToLine1->Type = Sketcher::PointOnObject; cornerToLine1->First = originalCornerId; cornerToLine1->FirstPos = PointPos::start; @@ -1537,7 +1636,7 @@ void SketchObject::transferFilletConstraints(int geoId1, PointPos posId1, int ge cornerToLine1->SecondPos = PointPos::none; addConstraint(cornerToLine1); delete cornerToLine1; - Sketcher::Constraint *cornerToLine2 = new Sketcher::Constraint(); + Sketcher::Constraint* cornerToLine2 = new Sketcher::Constraint(); cornerToLine2->Type = Sketcher::PointOnObject; cornerToLine2->First = originalCornerId; cornerToLine2->FirstPos = PointPos::start; @@ -1549,7 +1648,7 @@ void SketchObject::transferFilletConstraints(int geoId1, PointPos posId1, int ge Base::StateLocker lock(managedoperation, true); // Loop through all the constraints and try to do reasonable things with the affected ones - std::vector newConstraints; + std::vector newConstraints; for (auto c : this->Constraints.getValues()) { // Keep track of whether the affected lines and endpoints appear in this constraint bool point1First = c->First == geoId1 && c->FirstPos == posId1; @@ -1565,8 +1664,9 @@ void SketchObject::transferFilletConstraints(int geoId1, PointPos posId1, int ge if (c->Type == Sketcher::Coincident) { if ((point1First && point2Second) || (point2First && point1Second)) { - // This is the constraint holding the two edges together that are about to be filleted. This constraint - // goes away because the edges will touch the fillet instead. + // This is the constraint holding the two edges together that are about to be + // filleted. This constraint goes away because the edges will touch the fillet + // instead. continue; } if (point1First || point2First) { @@ -1579,7 +1679,8 @@ void SketchObject::transferFilletConstraints(int geoId1, PointPos posId1, int ge c->Second = originalCornerId; c->SecondPos = PointPos::start; } - } else if (c->Type == Sketcher::Horizontal || c->Type == Sketcher::Vertical) { + } + else if (c->Type == Sketcher::Horizontal || c->Type == Sketcher::Vertical) { // Point-to-point horizontal or vertical constraint, move to new corner point if (point1First || point2First) { c->First = originalCornerId; @@ -1589,7 +1690,9 @@ void SketchObject::transferFilletConstraints(int geoId1, PointPos posId1, int ge c->Second = originalCornerId; c->SecondPos = PointPos::start; } - } else if (c->Type == Sketcher::Distance || c->Type == Sketcher::DistanceX || c->Type == Sketcher::DistanceY) { + } + else if (c->Type == Sketcher::Distance || c->Type == Sketcher::DistanceX + || c->Type == Sketcher::DistanceY) { // Point-to-point distance constraint. Move it to the new corner point if (point1First || point2First) { c->First = originalCornerId; @@ -1600,8 +1703,8 @@ void SketchObject::transferFilletConstraints(int geoId1, PointPos posId1, int ge c->SecondPos = PointPos::start; } - // Distance constraint on the line itself. Change it to point-point between the far end of the line - // and the new corner + // Distance constraint on the line itself. Change it to point-point between the far end + // of the line and the new corner if (line1First) { c->FirstPos = (posId1 == PointPos::start) ? PointPos::end : PointPos::start; c->Second = originalCornerId; @@ -1612,37 +1715,45 @@ void SketchObject::transferFilletConstraints(int geoId1, PointPos posId1, int ge c->Second = originalCornerId; c->SecondPos = PointPos::start; } - } else if (c->Type == Sketcher::PointOnObject) { + } + else if (c->Type == Sketcher::PointOnObject) { // The corner to be filleted was touching some other object. if (point1First || point2First) { c->First = originalCornerId; c->FirstPos = PointPos::start; } - } else if (c->Type == Sketcher::Equal) { + } + else if (c->Type == Sketcher::Equal) { // Equal length constraints are dicey because the lines are getting shorter. Safer to // delete them and let the user notice the underconstraint. if (line1First || line2First || line1Second || line2Second) { continue; } - } else if (c->Type == Sketcher::Symmetric) { + } + else if (c->Type == Sketcher::Symmetric) { // Symmetries should probably be preserved relative to the original corner if (point1First || point2First) { c->First = originalCornerId; c->FirstPos = PointPos::start; - } else if (point1Second || point2Second) { + } + else if (point1Second || point2Second) { c->Second = originalCornerId; c->SecondPos = PointPos::start; - } else if (point1Third || point2Third) { + } + else if (point1Third || point2Third) { c->Third = originalCornerId; c->ThirdPos = PointPos::start; } - } else if (c->Type == Sketcher::SnellsLaw) { - // Can't imagine any cases where you'd fillet a vertex going through a lens, so let's - // delete to be safe. - continue; - } else if (point1First || point2First || point1Second || point2Second || point1Third || point2Third) { - // Delete any other point-based constraints on the relevant points - continue; + } + else if (c->Type == Sketcher::SnellsLaw) { + // Can't imagine any cases where you'd fillet a vertex going through a lens, so let's + // delete to be safe. + continue; + } + else if (point1First || point2First || point1Second || point2Second || point1Third + || point2Third) { + // Delete any other point-based constraints on the relevant points + continue; } // Default: keep all other constraints @@ -1651,37 +1762,41 @@ void SketchObject::transferFilletConstraints(int geoId1, PointPos posId1, int ge this->Constraints.setValues(std::move(newConstraints)); } -int SketchObject::transferConstraints(int fromGeoId, PointPos fromPosId, int toGeoId, PointPos toPosId, bool doNotTransformTangencies) +int SketchObject::transferConstraints(int fromGeoId, PointPos fromPosId, int toGeoId, + PointPos toPosId, bool doNotTransformTangencies) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector &vals = this->Constraints.getValues(); - std::vector newVals(vals); + const std::vector& vals = this->Constraints.getValues(); + std::vector newVals(vals); bool changed = false; - for (int i=0; i < int(newVals.size()); i++) { - if (vals[i]->First == fromGeoId && vals[i]->FirstPos == fromPosId && - !(vals[i]->Second == toGeoId && vals[i]->SecondPos == toPosId) && - !(toGeoId < 0 && vals[i]->Second <0) ) { + for (int i = 0; i < int(newVals.size()); i++) { + if (vals[i]->First == fromGeoId && vals[i]->FirstPos == fromPosId + && !(vals[i]->Second == toGeoId && vals[i]->SecondPos == toPosId) + && !(toGeoId < 0 && vals[i]->Second < 0)) { std::unique_ptr constNew(newVals[i]->clone()); constNew->First = toGeoId; constNew->FirstPos = toPosId; - // If not explicitly confirmed, nothing guarantees that a tangent can be freely transferred to another coincident - // point, as the transfer destination edge most likely won't be intended to be tangent. However, if it is - // an end to end point tangency, the user expects it to be substituted by a coincidence constraint. + // If not explicitly confirmed, nothing guarantees that a tangent can be freely + // transferred to another coincident point, as the transfer destination edge most likely + // won't be intended to be tangent. However, if it is an end to end point tangency, the + // user expects it to be substituted by a coincidence constraint. if (vals[i]->Type == Sketcher::Tangent || vals[i]->Type == Sketcher::Perpendicular) { if (!doNotTransformTangencies) { constNew->Type = Sketcher::Coincident; } } - // With respect to angle constraints, if it is a DeepSOIC style angle constraint (segment+segment+point), - // then no problem arises as the segments are PosId=none. In this case there is no call to this function. + // With respect to angle constraints, if it is a DeepSOIC style angle constraint + // (segment+segment+point), then no problem arises as the segments are PosId=none. In + // this case there is no call to this function. // - // However, other angle constraints are problematic because they are created on segments, but internally - // operate on vertices, PosId=start - // Such constraint may not be successfully transferred on deletion of the segments. - else if(vals[i]->Type == Sketcher::Angle) { + // However, other angle constraints are problematic because they are created on + // segments, but internally operate on vertices, PosId=start Such constraint may not be + // successfully transferred on deletion of the segments. + else if (vals[i]->Type == Sketcher::Angle) { continue; } @@ -1689,22 +1804,23 @@ int SketchObject::transferConstraints(int fromGeoId, PointPos fromPosId, int toG newVals[i] = constPtr; changed = true; } - else if (vals[i]->Second == fromGeoId && vals[i]->SecondPos == fromPosId && - !(vals[i]->First == toGeoId && vals[i]->FirstPos == toPosId) && - !(toGeoId < 0 && vals[i]->First< 0)) { + else if (vals[i]->Second == fromGeoId && vals[i]->SecondPos == fromPosId + && !(vals[i]->First == toGeoId && vals[i]->FirstPos == toPosId) + && !(toGeoId < 0 && vals[i]->First < 0)) { std::unique_ptr constNew(newVals[i]->clone()); constNew->Second = toGeoId; constNew->SecondPos = toPosId; - // If not explicitly confirmed, nothing guarantees that a tangent can be freely transferred to another coincident - // point, as the transfer destination edge most likely won't be intended to be tangent. However, if it is - // an end to end point tangency, the user expects it to be substituted by a coincidence constraint. + // If not explicitly confirmed, nothing guarantees that a tangent can be freely + // transferred to another coincident point, as the transfer destination edge most likely + // won't be intended to be tangent. However, if it is an end to end point tangency, the + // user expects it to be substituted by a coincidence constraint. if (vals[i]->Type == Sketcher::Tangent || vals[i]->Type == Sketcher::Perpendicular) { if (!doNotTransformTangencies) { constNew->Type = Sketcher::Coincident; } } - else if(vals[i]->Type == Sketcher::Angle) { + else if (vals[i]->Type == Sketcher::Angle) { continue; } @@ -1733,15 +1849,15 @@ int SketchObject::fillet(int GeoId, PointPos PosId, double radius, bool trim, bo // only coincident points between two (non-external) edges can be filleted if (GeoIdList.size() == 2 && GeoIdList[0] >= 0 && GeoIdList[1] >= 0) { - const Part::Geometry *geo1 = getGeometry(GeoIdList[0]); - const Part::Geometry *geo2 = getGeometry(GeoIdList[1]); - if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && - geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId() ) { - const Part::GeomLineSegment *lineSeg1 = static_cast(geo1); - const Part::GeomLineSegment *lineSeg2 = static_cast(geo2); + const Part::Geometry* geo1 = getGeometry(GeoIdList[0]); + const Part::Geometry* geo2 = getGeometry(GeoIdList[1]); + if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() + && geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* lineSeg1 = static_cast(geo1); + const Part::GeomLineSegment* lineSeg2 = static_cast(geo2); - Base::Vector3d midPnt1 = (lineSeg1->getStartPoint() + lineSeg1->getEndPoint()) / 2 ; - Base::Vector3d midPnt2 = (lineSeg2->getStartPoint() + lineSeg2->getEndPoint()) / 2 ; + Base::Vector3d midPnt1 = (lineSeg1->getStartPoint() + lineSeg1->getEndPoint()) / 2; + Base::Vector3d midPnt2 = (lineSeg2->getStartPoint() + lineSeg2->getEndPoint()) / 2; return fillet(GeoIdList[0], GeoIdList[1], midPnt1, midPnt2, radius, trim, createCorner); } } @@ -1749,25 +1865,24 @@ int SketchObject::fillet(int GeoId, PointPos PosId, double radius, bool trim, bo return -1; } -int SketchObject::fillet(int GeoId1, int GeoId2, - const Base::Vector3d& refPnt1, const Base::Vector3d& refPnt2, - double radius, bool trim, bool createCorner) +int SketchObject::fillet(int GeoId1, int GeoId2, const Base::Vector3d& refPnt1, + const Base::Vector3d& refPnt2, double radius, bool trim, bool createCorner) { - if (GeoId1 < 0 || GeoId1 > getHighestCurveIndex() || - GeoId2 < 0 || GeoId2 > getHighestCurveIndex()) + if (GeoId1 < 0 || GeoId1 > getHighestCurveIndex() || GeoId2 < 0 + || GeoId2 > getHighestCurveIndex()) return -1; // If either of the two input lines are locked, don't try to trim since it won't work anyway - const Part::Geometry *geo1 = getGeometry(GeoId1); - const Part::Geometry *geo2 = getGeometry(GeoId2); + const Part::Geometry* geo1 = getGeometry(GeoId1); + const Part::Geometry* geo2 = getGeometry(GeoId2); if (trim && (GeometryFacade::getBlocked(geo1) || GeometryFacade::getBlocked(geo2))) { trim = false; } - if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && - geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId() ) { - const Part::GeomLineSegment *lineSeg1 = static_cast(geo1); - const Part::GeomLineSegment *lineSeg2 = static_cast(geo2); + if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() + && geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* lineSeg1 = static_cast(geo1); + const Part::GeomLineSegment* lineSeg2 = static_cast(geo2); Base::Vector3d filletCenter; if (!Part::findFilletCenter(lineSeg1, lineSeg2, radius, refPnt1, refPnt2, filletCenter)) @@ -1775,7 +1890,8 @@ int SketchObject::fillet(int GeoId1, int GeoId2, Base::Vector3d dir1 = lineSeg1->getEndPoint() - lineSeg1->getStartPoint(); Base::Vector3d dir2 = lineSeg2->getEndPoint() - lineSeg2->getStartPoint(); - // the intersection point will and two distances will be necessary later for trimming the lines + // the intersection point will and two distances will be necessary later for trimming the + // lines Base::Vector3d intersection, dist1, dist2; // create arc from known parameters and lines @@ -1790,18 +1906,21 @@ int SketchObject::fillet(int GeoId1, int GeoId2, return -1; } - dist1.ProjectToLine(arc->getStartPoint(/*emulateCCW=*/true)-intersection, dir1); - dist2.ProjectToLine(arc->getStartPoint(/*emulateCCW=*/true)-intersection, dir2); - Part::Geometry *newgeo = arc.get(); + dist1.ProjectToLine(arc->getStartPoint(/*emulateCCW=*/true) - intersection, dir1); + dist2.ProjectToLine(arc->getStartPoint(/*emulateCCW=*/true) - intersection, dir2); + Part::Geometry* newgeo = arc.get(); filletId = addGeometry(newgeo); if (trim) { - PointPos PosId1 = (filletCenter-intersection)*dir1 > 0 ? PointPos::start : PointPos::end; - PointPos PosId2 = (filletCenter-intersection)*dir2 > 0 ? PointPos::start : PointPos::end; + PointPos PosId1 = + (filletCenter - intersection) * dir1 > 0 ? PointPos::start : PointPos::end; + PointPos PosId2 = + (filletCenter - intersection) * dir2 > 0 ? PointPos::start : PointPos::end; if (createCorner) { transferFilletConstraints(GeoId1, PosId1, GeoId2, PosId2); - } else { + } + else { delConstraintOnPoint(GeoId1, PosId1, false); delConstraintOnPoint(GeoId2, PosId2, false); } @@ -1822,196 +1941,219 @@ int SketchObject::fillet(int GeoId1, int GeoId2, if (dist1.Length() < dist2.Length()) { tangent1->SecondPos = PointPos::start; tangent2->SecondPos = PointPos::end; - movePoint(GeoId1, PosId1, arc->getStartPoint(/*emulateCCW=*/true),false,true); - movePoint(GeoId2, PosId2, arc->getEndPoint(/*emulateCCW=*/true),false,true); + movePoint(GeoId1, PosId1, arc->getStartPoint(/*emulateCCW=*/true), false, true); + movePoint(GeoId2, PosId2, arc->getEndPoint(/*emulateCCW=*/true), false, true); } else { tangent1->SecondPos = PointPos::end; tangent2->SecondPos = PointPos::start; - movePoint(GeoId1, PosId1, arc->getEndPoint(/*emulateCCW=*/true),false,true); - movePoint(GeoId2, PosId2, arc->getStartPoint(/*emulateCCW=*/true),false,true); + movePoint(GeoId1, PosId1, arc->getEndPoint(/*emulateCCW=*/true), false, true); + movePoint(GeoId2, PosId2, arc->getStartPoint(/*emulateCCW=*/true), false, true); } addConstraint(std::move(tangent1)); addConstraint(std::move(tangent2)); } - if (noRecomputes) // if we do not have a recompute after the geometry creation, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute after the geometry creation, the sketch must be solved to + // update the DoF of the solver + if (noRecomputes) solve(); return 0; } - else if(geo1->isDerivedFrom(Part::GeomBoundedCurve::getClassTypeId()) && - geo2->isDerivedFrom(Part::GeomBoundedCurve::getClassTypeId())) { + else if (geo1->isDerivedFrom(Part::GeomBoundedCurve::getClassTypeId()) + && geo2->isDerivedFrom(Part::GeomBoundedCurve::getClassTypeId())) { - auto distancetorefpoints = [](Base::Vector3d ip1, Base::Vector3d ip2, Base::Vector3d ref1, Base::Vector3d ref2) { - return (ip1 - ref1).Length() + (ip2 - ref2).Length(); - }; + auto distancetorefpoints = + [](Base::Vector3d ip1, Base::Vector3d ip2, Base::Vector3d ref1, Base::Vector3d ref2) { + return (ip1 - ref1).Length() + (ip2 - ref2).Length(); + }; - auto selectintersection = [&distancetorefpoints](std::vector> & points, - std::pair& interpoints, - const Base::Vector3d& refPnt1, const Base::Vector3d& refPnt2) { + auto selectintersection = + [&distancetorefpoints](std::vector>& points, + std::pair& interpoints, + const Base::Vector3d& refPnt1, + const Base::Vector3d& refPnt2) { + if (points.empty()) { + return -1; + } + else { + double dist = + distancetorefpoints(points[0].first, points[0].second, refPnt1, refPnt2); + int i = 0, si = 0; - if (points.empty()) { - return -1; - } - else { - double dist = distancetorefpoints(points[0].first, points[0].second, refPnt1, refPnt2); - int i = 0, si = 0; + for (auto ipoints : points) { + double d = + distancetorefpoints(ipoints.first, ipoints.second, refPnt1, refPnt2); - for (auto ipoints : points) { - double d = distancetorefpoints(ipoints.first, ipoints.second, refPnt1, refPnt2); + if (d < dist) { + si = i; + dist = d; + } - if (d(geo1); - const Part::GeomCurve *curve2 = static_cast(geo2); + const Part::GeomCurve* curve1 = static_cast(geo1); + const Part::GeomCurve* curve2 = static_cast(geo2); double refparam1; double refparam2; try { - if(!curve1->closestParameter(refPnt1,refparam1)) + if (!curve1->closestParameter(refPnt1, refparam1)) return -1; } - catch (Base::CADKernelError &e) { + catch (Base::CADKernelError& e) { e.ReportException(); - THROWM(Base::CADKernelError, "Unable to determine the parameter of the first selected curve at the reference point.") + THROWM(Base::CADKernelError, + "Unable to determine the parameter of the first selected curve at the reference " + "point.") } try { - if(!curve2->closestParameter(refPnt2,refparam2)) + if (!curve2->closestParameter(refPnt2, refparam2)) return -1; } - catch (Base::CADKernelError &e) { + catch (Base::CADKernelError& e) { e.ReportException(); - THROWM(Base::CADKernelError, "Unable to determine the parameter of the second selected curve at the reference point.") + THROWM(Base::CADKernelError, + "Unable to determine the parameter of the second selected curve at the " + "reference point.") } #ifdef DEBUG Base::Console().Log("\n\nFILLET DEBUG\n\n"); - Base::Console().Log("Ref param: (%f);(%f)",refparam1,refparam2); + Base::Console().Log("Ref param: (%f);(%f)", refparam1, refparam2); #endif std::pair interpoints; std::vector> points; - // look for coincident constraints between curves, take the coincident closest to the refpoints + // look for coincident constraints between curves, take the coincident closest to the + // refpoints Sketcher::PointPos curve1PosId = Sketcher::PointPos::none; Sketcher::PointPos curve2PosId = Sketcher::PointPos::none; - double dist=INFINITY; + double dist = INFINITY; - const std::vector &constraints = this->Constraints.getValues(); + const std::vector& constraints = this->Constraints.getValues(); - for (std::vector::const_iterator it=constraints.begin(); it != constraints.end(); ++it) { - if ((*it)->Type == Sketcher::Coincident || (*it)->Type == Sketcher::Perpendicular || (*it)->Type == Sketcher::Tangent) { - if ((*it)->First == GeoId1 && (*it)->Second == GeoId2 && - (*it)->FirstPos != Sketcher::PointPos::none && (*it)->SecondPos != Sketcher::PointPos::none ) { - Base::Vector3d tmpp1 = getPoint((*it)->First,(*it)->FirstPos); - Base::Vector3d tmpp2 = getPoint((*it)->Second,(*it)->SecondPos); - double tmpdist = distancetorefpoints(tmpp1, - tmpp2, - refPnt1, - refPnt2); - if(tmpdist < dist) { + for (std::vector::const_iterator it = constraints.begin(); + it != constraints.end(); + ++it) { + if ((*it)->Type == Sketcher::Coincident || (*it)->Type == Sketcher::Perpendicular + || (*it)->Type == Sketcher::Tangent) { + if ((*it)->First == GeoId1 && (*it)->Second == GeoId2 + && (*it)->FirstPos != Sketcher::PointPos::none + && (*it)->SecondPos != Sketcher::PointPos::none) { + Base::Vector3d tmpp1 = getPoint((*it)->First, (*it)->FirstPos); + Base::Vector3d tmpp2 = getPoint((*it)->Second, (*it)->SecondPos); + double tmpdist = distancetorefpoints(tmpp1, tmpp2, refPnt1, refPnt2); + if (tmpdist < dist) { curve1PosId = (*it)->FirstPos; curve2PosId = (*it)->SecondPos; dist = tmpdist; - interpoints = std::make_pair(tmpp1,tmpp2); + interpoints = std::make_pair(tmpp1, tmpp2); } } - else if ((*it)->First == GeoId2 && (*it)->Second == GeoId1 && - (*it)->FirstPos != Sketcher::PointPos::none && (*it)->SecondPos != Sketcher::PointPos::none ) { - Base::Vector3d tmpp2 = getPoint((*it)->First,(*it)->FirstPos); - Base::Vector3d tmpp1 = getPoint((*it)->Second,(*it)->SecondPos); - double tmpdist = distancetorefpoints(tmpp1, - tmpp2, - refPnt1, - refPnt2); - if(tmpdist < dist) { + else if ((*it)->First == GeoId2 && (*it)->Second == GeoId1 + && (*it)->FirstPos != Sketcher::PointPos::none + && (*it)->SecondPos != Sketcher::PointPos::none) { + Base::Vector3d tmpp2 = getPoint((*it)->First, (*it)->FirstPos); + Base::Vector3d tmpp1 = getPoint((*it)->Second, (*it)->SecondPos); + double tmpdist = distancetorefpoints(tmpp1, tmpp2, refPnt1, refPnt2); + if (tmpdist < dist) { curve2PosId = (*it)->FirstPos; curve1PosId = (*it)->SecondPos; dist = tmpdist; - interpoints = std::make_pair(tmpp1,tmpp2); + interpoints = std::make_pair(tmpp1, tmpp2); } } } } - if( curve1PosId == Sketcher::PointPos::none ) { + if (curve1PosId == Sketcher::PointPos::none) { // no coincident was found, try basis curve intersection if GeomTrimmedCurve - if( geo1->isDerivedFrom(Part::GeomTrimmedCurve::getClassTypeId()) && - geo2->isDerivedFrom(Part::GeomTrimmedCurve::getClassTypeId())) { + if (geo1->isDerivedFrom(Part::GeomTrimmedCurve::getClassTypeId()) + && geo2->isDerivedFrom(Part::GeomTrimmedCurve::getClassTypeId())) { - const Part::GeomTrimmedCurve *tcurve1 = static_cast(geo1); - const Part::GeomTrimmedCurve *tcurve2 = static_cast(geo2); + const Part::GeomTrimmedCurve* tcurve1 = + static_cast(geo1); + const Part::GeomTrimmedCurve* tcurve2 = + static_cast(geo2); try { - if(!tcurve1->intersectBasisCurves(tcurve2,points)) + if (!tcurve1->intersectBasisCurves(tcurve2, points)) return -1; } - catch (Base::CADKernelError &e) { + catch (Base::CADKernelError& e) { e.ReportException(); - THROWMT(Base::CADKernelError,QT_TRANSLATE_NOOP("Exceptions", "Unable to guess intersection of curves. Try adding a coincident constraint between the vertices of the curves you are intending to fillet.")) + THROWMT(Base::CADKernelError, + QT_TRANSLATE_NOOP("Exceptions", + "Unable to guess intersection of curves. Try adding " + "a coincident constraint between the vertices of the " + "curves you are intending to fillet.")) } - int res = selectintersection(points,interpoints,refPnt1, refPnt2); + int res = selectintersection(points, interpoints, refPnt1, refPnt2); if (res != 0) return res; } else - return -1; // not a GeomTrimmedCurve and no coincident point. + return -1;// not a GeomTrimmedCurve and no coincident point. } - // Now that we know where the curves intersect, get the parameters in the curves of those points + // Now that we know where the curves intersect, get the parameters in the curves of those + // points double intparam1; double intparam2; try { - if(!curve1->closestParameter(interpoints.first,intparam1)) + if (!curve1->closestParameter(interpoints.first, intparam1)) return -1; } - catch (Base::CADKernelError &e) { + catch (Base::CADKernelError& e) { e.ReportException(); - THROWM(Base::CADKernelError,"Unable to determine the parameter of the first selected curve at the intersection of the curves.") + THROWM(Base::CADKernelError, + "Unable to determine the parameter of the first selected curve at the " + "intersection of the curves.") } try { - if(!curve2->closestParameter(interpoints.second,intparam2)) + if (!curve2->closestParameter(interpoints.second, intparam2)) return -1; } - catch (Base::CADKernelError &e) { + catch (Base::CADKernelError& e) { e.ReportException(); - THROWM(Base::CADKernelError,"Unable to determine the parameter of the second selected curve at the intersection of the curves.") + THROWM(Base::CADKernelError, + "Unable to determine the parameter of the second selected curve at the " + "intersection of the curves.") } // get the starting parameters of each curve @@ -2028,88 +2170,119 @@ int SketchObject::fillet(int GeoId1, int GeoId2, // We do not know the actual tangency points until we intersect the offset curves, but // we do not have offset curves before with decide on a radius. // - // This estimation guesses a radius as the average of the distances from the reference points - // with respect to the intersection of the normals at those reference points. + // This estimation guesses a radius as the average of the distances from the reference + // points with respect to the intersection of the normals at those reference points. try { Base::Vector3d tdir1; Base::Vector3d tdir2; - // We want normals, but OCCT normals require curves to be 2 times derivable, and lines are not - // tangency calculation requires 1 time derivable. + // We want normals, but OCCT normals require curves to be 2 times derivable, and + // lines are not tangency calculation requires 1 time derivable. - if(!curve1->tangent(refparam1, tdir1)) + if (!curve1->tangent(refparam1, tdir1)) return -1; - if(!curve2->tangent(refparam2, tdir2)) + if (!curve2->tangent(refparam2, tdir2)) return -1; - Base::Vector3d dir1(tdir1.y,-tdir1.x,0); - Base::Vector3d dir2(tdir2.y,-tdir2.x,0); + Base::Vector3d dir1(tdir1.y, -tdir1.x, 0); + Base::Vector3d dir2(tdir2.y, -tdir2.x, 0); - double det = -dir1.x*dir2.y + dir2.x*dir1.y; + double det = -dir1.x * dir2.y + dir2.x * dir1.y; - if (std::abs(det) < Precision::Confusion()) - throw Base::RuntimeError("No intersection of normals"); // no intersection of normals + if (std::abs(det) < Precision::Confusion()) { + // no intersection of normals + throw Base::RuntimeError("No intersection of normals"); + } Base::Vector3d refp1 = curve1->pointAtParameter(refparam1); Base::Vector3d refp2 = curve2->pointAtParameter(refparam2); - //Base::Console().Log("refpoints: (%f,%f,%f);(%f,%f,%f)",refp1.x,refp1.y,refp1.z,refp2.x,refp2.y,refp2.z); + // Base::Console().Log("refpoints: + // (%f,%f,%f);(%f,%f,%f)",refp1.x,refp1.y,refp1.z,refp2.x,refp2.y,refp2.z); Base::Vector3d normalintersect( - (-dir1.x*dir2.x*refp1.y + dir1.x*dir2.x*refp2.y - dir1.x*dir2.y*refp2.x + dir2.x*dir1.y*refp1.x)/det, - (-dir1.x*dir2.y*refp1.y + dir2.x*dir1.y*refp2.y + dir1.y*dir2.y*refp1.x - dir1.y*dir2.y*refp2.x)/det,0); + (-dir1.x * dir2.x * refp1.y + dir1.x * dir2.x * refp2.y + - dir1.x * dir2.y * refp2.x + dir2.x * dir1.y * refp1.x) + / det, + (-dir1.x * dir2.y * refp1.y + dir2.x * dir1.y * refp2.y + + dir1.y * dir2.y * refp1.x - dir1.y * dir2.y * refp2.x) + / det, + 0); - radius = ((refp1 - normalintersect).Length() + (refp2 - normalintersect).Length())/2; + radius = + ((refp1 - normalintersect).Length() + (refp2 - normalintersect).Length()) / 2; } - catch(const Base::Exception&) { - radius = ref21.Length(); // fall-back to simplest estimation. + catch (const Base::Exception&) { + radius = ref21.Length();// fall-back to simplest estimation. } } #ifdef DEBUG - Base::Console().Log("Start param: (%f);(%f)\n",spc1,spc2); + Base::Console().Log("Start param: (%f);(%f)\n", spc1, spc2); Base::Vector3d c1pf = curve1->pointAtParameter(spc1); Base::Vector3d c2pf = curve2->pointAtParameter(spc2); - Base::Console().Log("start point curves: (%f,%f,%f);(%f,%f,%f)\n",c1pf.x,c1pf.y,c1pf.z,c2pf.x,c2pf.y,c2pf.z); + Base::Console().Log("start point curves: (%f,%f,%f);(%f,%f,%f)\n", + c1pf.x, + c1pf.y, + c1pf.z, + c2pf.x, + c2pf.y, + c2pf.z); #endif - // We create Offset curves at the suggested radius, the direction of offset is estimated from the tangency vector + // We create Offset curves at the suggested radius, the direction of offset is estimated + // from the tangency vector Base::Vector3d tdir1 = curve1->firstDerivativeAtParameter(refparam1); Base::Vector3d tdir2 = curve2->firstDerivativeAtParameter(refparam2); #ifdef DEBUG - Base::Console().Log("tangent vectors: (%f,%f,%f);(%f,%f,%f)\n",tdir1.x,tdir1.y,tdir1.z,tdir2.x,tdir2.y,tdir2.z); - Base::Console().Log("inter-ref vector: (%f,%f,%f)\n",ref21.x,ref21.y,ref21.z); + Base::Console().Log("tangent vectors: (%f,%f,%f);(%f,%f,%f)\n", + tdir1.x, + tdir1.y, + tdir1.z, + tdir2.x, + tdir2.y, + tdir2.z); + Base::Console().Log("inter-ref vector: (%f,%f,%f)\n", ref21.x, ref21.y, ref21.z); #endif - Base::Vector3d vn(0,0,1); + Base::Vector3d vn(0, 0, 1); double sdir1 = tdir1.Cross(ref21).Dot(vn); double sdir2 = tdir2.Cross(-ref21).Dot(vn); #ifdef DEBUG - Base::Console().Log("sign of offset: (%f,%f)\n",sdir1,sdir2); - Base::Console().Log("radius: %f\n",radius); + Base::Console().Log("sign of offset: (%f,%f)\n", sdir1, sdir2); + Base::Console().Log("radius: %f\n", radius); #endif - Part::GeomOffsetCurve * ocurve1 = new Part::GeomOffsetCurve(Handle(Geom_Curve)::DownCast(curve1->handle()), (sdir1<0)?radius:-radius, vn); + Part::GeomOffsetCurve* ocurve1 = new Part::GeomOffsetCurve( + Handle(Geom_Curve)::DownCast(curve1->handle()), (sdir1 < 0) ? radius : -radius, vn); - Part::GeomOffsetCurve * ocurve2 = new Part::GeomOffsetCurve(Handle(Geom_Curve)::DownCast(curve2->handle()), (sdir2<0)?radius:-radius, vn); + Part::GeomOffsetCurve* ocurve2 = new Part::GeomOffsetCurve( + Handle(Geom_Curve)::DownCast(curve2->handle()), (sdir2 < 0) ? radius : -radius, vn); #ifdef DEBUG Base::Vector3d oc1pf = ocurve1->pointAtParameter(ocurve1->getFirstParameter()); Base::Vector3d oc2pf = ocurve2->pointAtParameter(ocurve2->getFirstParameter()); - Base::Console().Log("start point offset curves: (%f,%f,%f);(%f,%f,%f)\n",oc1pf.x,oc1pf.y,oc1pf.z,oc2pf.x,oc2pf.y,oc2pf.z); + Base::Console().Log("start point offset curves: (%f,%f,%f);(%f,%f,%f)\n", + oc1pf.x, + oc1pf.y, + oc1pf.z, + oc2pf.x, + oc2pf.y, + oc2pf.z); /*auto printoffsetcurve = [](Part::GeomOffsetCurve *c) { - for(double param = c->getFirstParameter(); param < c->getLastParameter(); param = param + (c->getLastParameter()-c->getFirstParameter())/10) - Base::Console().Log("\n%f: (%f,%f,0)\n", param, c->pointAtParameter(param).x,c->pointAtParameter(param).y); + for(double param = c->getFirstParameter(); param < c->getLastParameter(); param = param + + (c->getLastParameter()-c->getFirstParameter())/10) Base::Console().Log("\n%f: + (%f,%f,0)\n", param, c->pointAtParameter(param).x,c->pointAtParameter(param).y); }; @@ -2122,61 +2295,68 @@ int SketchObject::fillet(int GeoId1, int GeoId2, std::vector> offsetintersectionpoints; try { - if(!ocurve1->intersect(ocurve2,offsetintersectionpoints)) { + if (!ocurve1->intersect(ocurve2, offsetintersectionpoints)) { #ifdef DEBUG Base::Console().Log("No intersection between offset curves\n"); #endif return -1; - } } - catch (Base::CADKernelError &e) { + catch (Base::CADKernelError& e) { e.ReportException(); - THROWM(Base::CADKernelError,"Unable to find intersection between offset curves.") + THROWM(Base::CADKernelError, "Unable to find intersection between offset curves.") } #ifdef DEBUG - for(auto inter:offsetintersectionpoints) { - Base::Console().Log("offset int(%f,%f,0)\n",inter.first.x,inter.first.y); + for (auto inter : offsetintersectionpoints) { + Base::Console().Log("offset int(%f,%f,0)\n", inter.first.x, inter.first.y); } #endif - int res = selectintersection(offsetintersectionpoints,filletcenterpoint,refPnt1, refPnt2); + int res = selectintersection(offsetintersectionpoints, filletcenterpoint, refPnt1, refPnt2); - if(res != 0) + if (res != 0) return res; #ifdef DEBUG - Base::Console().Log("selected offset int(%f,%f,0)\n",filletcenterpoint.first.x,filletcenterpoint.first.y); + Base::Console().Log( + "selected offset int(%f,%f,0)\n", filletcenterpoint.first.x, filletcenterpoint.first.y); #endif double refoparam1; double refoparam2; try { - if(!curve1->closestParameter(filletcenterpoint.first,refoparam1)) + if (!curve1->closestParameter(filletcenterpoint.first, refoparam1)) return -1; } - catch (Base::CADKernelError &e) { + catch (Base::CADKernelError& e) { e.ReportException(); - THROWM(Base::CADKernelError,"Unable to determine the starting point of the arc.") + THROWM(Base::CADKernelError, "Unable to determine the starting point of the arc.") } try { - if(!curve2->closestParameter(filletcenterpoint.second,refoparam2)) + if (!curve2->closestParameter(filletcenterpoint.second, refoparam2)) return -1; } - catch (Base::CADKernelError &e) { + catch (Base::CADKernelError& e) { e.ReportException(); - THROWM(Base::CADKernelError,"Unable to determine the end point of the arc.") + THROWM(Base::CADKernelError, "Unable to determine the end point of the arc.") } - // Next we calculate the closest points to the fillet center, so the points where tangency is to be applied + // Next we calculate the closest points to the fillet center, so the points where tangency + // is to be applied Base::Vector3d refp1 = curve1->pointAtParameter(refoparam1); Base::Vector3d refp2 = curve2->pointAtParameter(refoparam2); #ifdef DEBUG - Base::Console().Log("refpoints: (%f,%f,%f);(%f,%f,%f)",refp1.x,refp1.y,refp1.z,refp2.x,refp2.y,refp2.z); + Base::Console().Log("refpoints: (%f,%f,%f);(%f,%f,%f)", + refp1.x, + refp1.y, + refp1.z, + refp2.x, + refp2.y, + refp2.z); #endif // Now we create arc for the fillet double startAngle, endAngle, range; @@ -2186,29 +2366,29 @@ int SketchObject::fillet(int GeoId1, int GeoId2, startAngle = atan2(radDir1.y, radDir1.x); - range = atan2(-radDir1.y*radDir2.x+radDir1.x*radDir2.y, - radDir1.x*radDir2.x+radDir1.y*radDir2.y); + range = atan2(-radDir1.y * radDir2.x + radDir1.x * radDir2.y, + radDir1.x * radDir2.x + radDir1.y * radDir2.y); endAngle = startAngle + range; if (endAngle < startAngle) std::swap(startAngle, endAngle); - if (endAngle > 2*M_PI ) - endAngle -= 2*M_PI; + if (endAngle > 2 * M_PI) + endAngle -= 2 * M_PI; - if (startAngle < 0 ) - endAngle += 2*M_PI; + if (startAngle < 0) + endAngle += 2 * M_PI; // Create Arc Segment - Part::GeomArcOfCircle *arc = new Part::GeomArcOfCircle(); + Part::GeomArcOfCircle* arc = new Part::GeomArcOfCircle(); arc->setRadius(radDir1.Length()); arc->setCenter(filletcenterpoint.first); arc->setRange(startAngle, endAngle, /*emulateCCWXY=*/true); // add arc to sketch geometry int filletId; - Part::Geometry *newgeo = arc; + Part::Geometry* newgeo = arc; filletId = addGeometry(newgeo); if (filletId < 0) { delete arc; @@ -2217,12 +2397,12 @@ int SketchObject::fillet(int GeoId1, int GeoId2, if (trim) { auto selectend = [](double intparam, double refparam, double startparam) { - if( (intparam>refparam && startparam >= refparam) || - (intparam refparam && startparam >= refparam) + || (intparam < refparam && startparam <= refparam)) { + return PointPos::start; } else { - return PointPos::end; + return PointPos::end; } }; @@ -2231,9 +2411,9 @@ int SketchObject::fillet(int GeoId1, int GeoId2, // b) we used the basis curve intersection - if( curve1PosId == Sketcher::PointPos::none ) { - curve1PosId = selectend(intparam1,refoparam1,spc1); - curve2PosId = selectend(intparam2,refoparam2,spc2); + if (curve1PosId == Sketcher::PointPos::none) { + curve1PosId = selectend(intparam1, refoparam1, spc1); + curve2PosId = selectend(intparam2, refoparam2, spc2); } @@ -2241,8 +2421,8 @@ int SketchObject::fillet(int GeoId1, int GeoId2, delConstraintOnPoint(GeoId2, curve2PosId, false); - Sketcher::Constraint *tangent1 = new Sketcher::Constraint(); - Sketcher::Constraint *tangent2 = new Sketcher::Constraint(); + Sketcher::Constraint* tangent1 = new Sketcher::Constraint(); + Sketcher::Constraint* tangent2 = new Sketcher::Constraint(); tangent1->Type = Sketcher::Tangent; tangent1->First = GeoId1; @@ -2257,19 +2437,19 @@ int SketchObject::fillet(int GeoId1, int GeoId2, double dist1 = (refp1 - arc->getStartPoint(true)).Length(); double dist2 = (refp1 - arc->getEndPoint(true)).Length(); - //Base::Console().Log("dists_refpoint_to_arc_sp_ep: (%f);(%f)",dist1,dist2); + // Base::Console().Log("dists_refpoint_to_arc_sp_ep: (%f);(%f)",dist1,dist2); if (dist1 < dist2) { tangent1->SecondPos = PointPos::start; tangent2->SecondPos = PointPos::end; - movePoint(GeoId1, curve1PosId, arc->getStartPoint(true),false,true); - movePoint(GeoId2, curve2PosId, arc->getEndPoint(true),false,true); + movePoint(GeoId1, curve1PosId, arc->getStartPoint(true), false, true); + movePoint(GeoId2, curve2PosId, arc->getEndPoint(true), false, true); } else { tangent1->SecondPos = PointPos::end; tangent2->SecondPos = PointPos::start; - movePoint(GeoId1, curve1PosId, arc->getEndPoint(true),false,true); - movePoint(GeoId2, curve2PosId, arc->getStartPoint(true),false,true); + movePoint(GeoId1, curve1PosId, arc->getEndPoint(true), false, true); + movePoint(GeoId2, curve2PosId, arc->getStartPoint(true), false, true); } addConstraint(tangent1); @@ -2285,7 +2465,9 @@ int SketchObject::fillet(int GeoId1, int GeoId2, Base::Console().Log("\n\nEND OF FILLET DEBUG\n\n"); #endif - if(noRecomputes) // if we do not have a recompute after the geometry creation, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute after the geometry creation, the sketch must be solved to + // update the DoF of the solver + if (noRecomputes) solve(); return 0; @@ -2293,15 +2475,16 @@ int SketchObject::fillet(int GeoId1, int GeoId2, return -1; } -int SketchObject::extend(int GeoId, double increment, PointPos endpoint) { +int SketchObject::extend(int GeoId, double increment, PointPos endpoint) +{ if (GeoId < 0 || GeoId > getHighestCurveIndex()) return -1; - const std::vector &geomList = getInternalGeometry(); - Part::Geometry *geom = geomList[GeoId]; + const std::vector& geomList = getInternalGeometry(); + Part::Geometry* geom = geomList[GeoId]; int retcode = -1; if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - Part::GeomLineSegment *seg = static_cast(geom); + Part::GeomLineSegment* seg = static_cast(geom); Base::Vector3d startVec = seg->getStartPoint(); Base::Vector3d endVec = seg->getEndPoint(); if (endpoint == PointPos::start) { @@ -2311,7 +2494,8 @@ int SketchObject::extend(int GeoId, double increment, PointPos endpoint) { newPoint.Scale(scaleFactor, scaleFactor, scaleFactor); newPoint = newPoint + endVec; retcode = movePoint(GeoId, Sketcher::PointPos::start, newPoint, false, true); - } else if (endpoint == PointPos::end) { + } + else if (endpoint == PointPos::end) { Base::Vector3d newPoint = endVec - startVec; double scaleFactor = newPoint.Length() + increment; newPoint.Normalize(); @@ -2319,14 +2503,16 @@ int SketchObject::extend(int GeoId, double increment, PointPos endpoint) { newPoint = newPoint + startVec; retcode = movePoint(GeoId, Sketcher::PointPos::end, newPoint, false, true); } - } else if (geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - Part::GeomArcOfCircle *arc = static_cast(geom); + } + else if (geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + Part::GeomArcOfCircle* arc = static_cast(geom); double startArc, endArc; arc->getRange(startArc, endArc, true); if (endpoint == PointPos::start) { arc->setRange(startArc - increment, endArc, true); retcode = 0; - } else if (endpoint == PointPos::end) { + } + else if (endpoint == PointPos::end) { arc->setRange(startArc, endArc + increment, true); retcode = 0; } @@ -2337,13 +2523,9 @@ int SketchObject::extend(int GeoId, double increment, PointPos endpoint) { return retcode; } -std::unique_ptr SketchObject::createConstraint( Sketcher::ConstraintType constrType, - int firstGeoId, - Sketcher::PointPos firstPos, - int secondGeoId, - Sketcher::PointPos secondPos, - int thirdGeoId, - Sketcher::PointPos thirdPos) +std::unique_ptr SketchObject::createConstraint( + Sketcher::ConstraintType constrType, int firstGeoId, Sketcher::PointPos firstPos, + int secondGeoId, Sketcher::PointPos secondPos, int thirdGeoId, Sketcher::PointPos thirdPos) { auto newConstr = std::make_unique(); @@ -2357,37 +2539,38 @@ std::unique_ptr SketchObject::createConstraint( Sketcher::Constraint return newConstr; } -void SketchObject::addConstraint(Sketcher::ConstraintType constrType, - int firstGeoId, - Sketcher::PointPos firstPos, - int secondGeoId, - Sketcher::PointPos secondPos, - int thirdGeoId, - Sketcher::PointPos thirdPos) +void SketchObject::addConstraint(Sketcher::ConstraintType constrType, int firstGeoId, + Sketcher::PointPos firstPos, int secondGeoId, + Sketcher::PointPos secondPos, int thirdGeoId, + Sketcher::PointPos thirdPos) { - auto newConstr = createConstraint(constrType, firstGeoId, firstPos, secondGeoId, secondPos, thirdGeoId, thirdPos); + auto newConstr = createConstraint( + constrType, firstGeoId, firstPos, secondGeoId, secondPos, thirdGeoId, thirdPos); this->addConstraint(std::move(newConstr)); } -bool SketchObject::seekTrimPoints(int GeoId, const Base::Vector3d &point, - int &GeoId1, Base::Vector3d &intersect1, - int &GeoId2, Base::Vector3d &intersect2) +bool SketchObject::seekTrimPoints(int GeoId, const Base::Vector3d& point, int& GeoId1, + Base::Vector3d& intersect1, int& GeoId2, + Base::Vector3d& intersect2) { if (GeoId < 0 || GeoId > getHighestCurveIndex()) return false; - auto geos = getCompleteGeometry(); // this includes the axes too + auto geos = getCompleteGeometry();// this includes the axes too - geos.resize(geos.size()-2); // remove the axes to avoid intersections with the axes + geos.resize(geos.size() - 2);// remove the axes to avoid intersections with the axes int localindex1, localindex2; - // Not found in will be returned as -1, not as GeoUndef, Part WB is agnostic to the concept of GeoUndef - if(!Part2DObject::seekTrimPoints(geos, GeoId, point, localindex1, intersect1, localindex2, intersect2)) + // Not found in will be returned as -1, not as GeoUndef, Part WB is agnostic to the concept of + // GeoUndef + if (!Part2DObject::seekTrimPoints( + geos, GeoId, point, localindex1, intersect1, localindex2, intersect2)) return false; - GeoId1 = getGeoIdFromCompleteGeometryIndex(localindex1); // invalid complete geometry indices are mapped to GeoUndef + // invalid complete geometry indices are mapped to GeoUndef + GeoId1 = getGeoIdFromCompleteGeometryIndex(localindex1); GeoId2 = getGeoIdFromCompleteGeometryIndex(localindex2); return true; @@ -2395,44 +2578,49 @@ bool SketchObject::seekTrimPoints(int GeoId, const Base::Vector3d &point, int SketchObject::trim(int GeoId, const Base::Vector3d& point) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - //******************* Basic checks rejecting the operation ****************************************// + //******************* Basic checks rejecting the operation + //****************************************// if (GeoId < 0 || GeoId > getHighestCurveIndex()) return -1; auto geo = getGeometry(GeoId); - if (!GeometryFacade::isInternalType(geo,InternalType::None)) - return -1; // internal alignment geometry is not trimmable + if (!GeometryFacade::isInternalType(geo, InternalType::None)) + return -1;// internal alignment geometry is not trimmable - //******************* Lambdas - common functions for different intersections ****************************************// + //******************* Lambdas - common functions for different intersections + //****************************************// - // returns true if the point defined by (GeoId1, pos1) can be considered to be coincident with point. - auto arePointsWithinPrecision = [] (Base::Vector3d point1, Base::Vector3d point2) { - // From testing: 500x (or 0.000050) is needed in order to not falsely distinguish points calculated with seekTrimPoints - if( (point1-point2).Length() < 500*Precision::Confusion()) + // returns true if the point defined by (GeoId1, pos1) can be considered to be coincident with + // point. + auto arePointsWithinPrecision = [](Base::Vector3d point1, Base::Vector3d point2) { + // From testing: 500x (or 0.000050) is needed in order to not falsely distinguish points + // calculated with seekTrimPoints + if ((point1 - point2).Length() < 500 * Precision::Confusion()) return true; return false; }; - auto isPointAtPosition = [this, arePointsWithinPrecision] (int GeoId1, PointPos pos1, Base::Vector3d point) { + auto isPointAtPosition = + [this, arePointsWithinPrecision](int GeoId1, PointPos pos1, Base::Vector3d point) { + Base::Vector3d pp = getPoint(GeoId1, pos1); - Base::Vector3d pp = getPoint(GeoId1,pos1); - - return arePointsWithinPrecision(point, pp); - }; + return arePointsWithinPrecision(point, pp); + }; // Helper function to remove Equal constraints from a chosen edge (e.g Line segment). - auto delEqualConstraintsOnGeoId = [this] (int GeoId) { - + auto delEqualConstraintsOnGeoId = [this](int GeoId) { std::vector delete_list; int index = 0; - const std::vector &constraints = this->Constraints.getValues(); - for (std::vector::const_iterator it=constraints.begin(); - it != constraints.end(); ++it, ++index) { - Constraint *constr = *(it); + const std::vector& constraints = this->Constraints.getValues(); + for (std::vector::const_iterator it = constraints.begin(); + it != constraints.end(); + ++it, ++index) { + Constraint* constr = *(it); if (constr->First == GeoId && constr->Type == Sketcher::Equal) { delete_list.push_back(index); } @@ -2444,19 +2632,26 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) }; // Checks whether preexisting constraints must be converted to new constraints. - // Preexisting point on object constraints get converted to coincidents, unless an end-to-end tangency is more relevant. - // returns by reference: + // Preexisting point on object constraints get converted to coincidents, unless an end-to-end + // tangency is more relevant. returns by reference: // - The type of constraint that should be used to constraint GeoId1 and GeoId // - The element of GeoId1 to which the constraint should be applied. - auto transformPreexistingConstraints = [this, isPointAtPosition] ( int GeoId, int GeoId1, Base::Vector3d point1, - ConstraintType &constrType, PointPos &secondPos ) { - const std::vector &constraints = this->Constraints.getValues(); - int constrId=0; + auto transformPreexistingConstraints = [this, isPointAtPosition](int GeoId, + int GeoId1, + Base::Vector3d point1, + ConstraintType& constrType, + PointPos& secondPos) { + const std::vector& constraints = this->Constraints.getValues(); + int constrId = 0; std::vector delete_list; - for (std::vector::const_iterator it=constraints.begin(); it != constraints.end(); ++it) { - Constraint *constr = *(it); - // There is a preexisting PointOnObject constraint, see if it must be converted to a coincident - if (constr->Type == Sketcher::PointOnObject && constr->First == GeoId1 && constr->Second == GeoId) { + for (std::vector::const_iterator it = constraints.begin(); + it != constraints.end(); + ++it) { + Constraint* constr = *(it); + // There is a preexisting PointOnObject constraint, see if it must be converted to a + // coincident + if (constr->Type == Sketcher::PointOnObject && constr->First == GeoId1 + && constr->Second == GeoId) { if (isPointAtPosition(constr->First, constr->FirstPos, point1)) { constrType = Sketcher::Coincident; secondPos = constr->FirstPos; @@ -2465,20 +2660,25 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) } constrId++; } - /* It is possible that the trimming entity has both a PointOnObject constraint to the trimmed entity, and a simple Tangent contstrait - * to the trimmed entity. In this case we want to change to a single end-to-end tangency, i.e we want to ensure that constrType1 is - * set to Sketcher::Tangent, that the secondPos1 is captured from the PointOnObject, and also make sure that the PointOnObject constraint - * is deleted. The below loop ensures this, also in case the ordering of the constraints is first Tangent and then PointOnObject. */ - constrId=0; - for (std::vector::const_iterator it=constraints.begin(); it != constraints.end(); ++it) { - Constraint *constr = *(it); + /* It is possible that the trimming entity has both a PointOnObject constraint to the + * trimmed entity, and a simple Tangent contstrait to the trimmed entity. In this case we + * want to change to a single end-to-end tangency, i.e we want to ensure that constrType1 is + * set to Sketcher::Tangent, that the secondPos1 is captured from the PointOnObject, and + * also make sure that the PointOnObject constraint is deleted. The below loop ensures this, + * also in case the ordering of the constraints is first Tangent and then PointOnObject. */ + constrId = 0; + for (std::vector::const_iterator it = constraints.begin(); + it != constraints.end(); + ++it) { + Constraint* constr = *(it); if (constr->Type == Sketcher::Tangent) { if (constr->First == GeoId1 && constr->Second == GeoId) { constrType = Sketcher::Tangent; if (secondPos == Sketcher::PointPos::none) secondPos = constr->FirstPos; delete_list.push_back(constrId); - } else if (constr->First == GeoId && constr->Second == GeoId1) { + } + else if (constr->First == GeoId && constr->Second == GeoId1) { constrType = Sketcher::Tangent; if (secondPos == Sketcher::PointPos::none) secondPos = constr->SecondPos; @@ -2491,7 +2691,8 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) if (secondPos == Sketcher::PointPos::none) secondPos = constr->FirstPos; delete_list.push_back(constrId); - } else if (constr->First == GeoId && constr->Second == GeoId1) { + } + else if (constr->First == GeoId && constr->Second == GeoId1) { constrType = Sketcher::Perpendicular; if (secondPos == Sketcher::PointPos::none) secondPos = constr->SecondPos; @@ -2505,7 +2706,7 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) }; // makes an equality constraint between GeoId1 and GeoId2 - auto constrainAsEqual = [this] (int GeoId1, int GeoId2) { + auto constrainAsEqual = [this](int GeoId1, int GeoId2) { auto newConstr = std::make_unique(); // Build Constraints associated with new pair of arcs @@ -2518,12 +2719,12 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) }; // Removes all internal geometry of a BSplineCurve and updates the GeoId index after removal - auto ifBSplineRemoveInternalAlignmentGeometry = [this](int &GeoId) - { + auto ifBSplineRemoveInternalAlignmentGeometry = [this](int& GeoId) { const Part::Geometry* geo = getGeometry(GeoId); - if(geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { - // We need to remove the internal geometry of the BSpline, as BSplines change in number of poles and knots - // We save the tags of the relevant geometry to retrieve the new GeoIds later on. + if (geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { + // We need to remove the internal geometry of the BSpline, as BSplines change in number + // of poles and knots We save the tags of the relevant geometry to retrieve the new + // GeoIds later on. boost::uuids::uuid GeoIdTag; GeoIdTag = geo->getTag(); @@ -2532,30 +2733,32 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) auto vals = getCompleteGeometry(); - for(size_t i = 0; i < vals.size(); i++) { - if(vals[i]->getTag() == GeoIdTag) { + for (size_t i = 0; i < vals.size(); i++) { + if (vals[i]->getTag() == GeoIdTag) { GeoId = getGeoIdFromCompleteGeometryIndex(i); break; } - } } }; - // given a geometry and tree points, returns the corresponding parameters of the geometry points closest to them - auto getIntersectionParameters = [](const Part::Geometry * geo, - const Base::Vector3d point, double &pointParam, - const Base::Vector3d point1, double &point1Param, - const Base::Vector3d point2, double &point2Param) { - + // given a geometry and tree points, returns the corresponding parameters of the geometry points + // closest to them + auto getIntersectionParameters = [](const Part::Geometry* geo, + const Base::Vector3d point, + double& pointParam, + const Base::Vector3d point1, + double& point1Param, + const Base::Vector3d point2, + double& point2Param) { auto curve = static_cast(geo); try { - curve->closestParameter(point, pointParam); - curve->closestParameter(point1, point1Param); - curve->closestParameter(point2, point2Param); + curve->closestParameter(point, pointParam); + curve->closestParameter(point1, point1Param); + curve->closestParameter(point2, point2Param); } - catch(Base::CADKernelError & e) { + catch (Base::CADKernelError& e) { e.ReportException(); return false; } @@ -2563,17 +2766,21 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) return true; }; - //******************* Step A => Detection of intersection - Common to all Geometries ****************************************// - int GeoId1=GeoEnum::GeoUndef, GeoId2=GeoEnum::GeoUndef; + //******************* Step A => Detection of intersection - Common to all Geometries + //****************************************// + int GeoId1 = GeoEnum::GeoUndef, GeoId2 = GeoEnum::GeoUndef; Base::Vector3d point1, point2; - // Using SketchObject wrapper, as Part2DObject version returns GeoId = -1 when intersection not found, which is wrong for a GeoId (axis). - // seekTrimPoints returns: - // - For a parameter associated with "point" between an intersection and the end point (non-periodic case) GeoId1 != GeoUndef and GeoId2 == GeoUndef - // - For a parameter associated with "point" between the start point and an intersection (non-periodic case) GeoId2 != GeoUndef and GeoId1 == GeoUndef - // - For a parameter associated with "point" between two intersection points, GeoId1 != GeoUndef and GeoId2 != GeoUndef + // Using SketchObject wrapper, as Part2DObject version returns GeoId = -1 when intersection not + // found, which is wrong for a GeoId (axis). seekTrimPoints returns: + // - For a parameter associated with "point" between an intersection and the end point + // (non-periodic case) GeoId1 != GeoUndef and GeoId2 == GeoUndef + // - For a parameter associated with "point" between the start point and an intersection + // (non-periodic case) GeoId2 != GeoUndef and GeoId1 == GeoUndef + // - For a parameter associated with "point" between two intersection points, GeoId1 != GeoUndef + // and GeoId2 != GeoUndef // // FirstParam < point1param < point2param < LastParam - if(!SketchObject::seekTrimPoints(GeoId, point, GeoId1, point1, GeoId2, point2)) { + if (!SketchObject::seekTrimPoints(GeoId, point, GeoId1, point1, GeoId2, point2)) { // If no suitable trim points are found, then trim defaults to deleting the geometry delGeometry(GeoId); return 0; @@ -2584,31 +2791,34 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) geo = getGeometry(GeoId); auto isBSpline = geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId(); - auto isPeriodicBSpline = isBSpline && static_cast(geo)->isPeriodic(); - auto isNonPeriodicBSpline = isBSpline && !static_cast(geo)->isPeriodic(); + auto isPeriodicBSpline = + isBSpline && static_cast(geo)->isPeriodic(); + auto isNonPeriodicBSpline = + isBSpline && !static_cast(geo)->isPeriodic(); auto isLineSegment = geo->getTypeId() == Part::GeomLineSegment::getClassTypeId(); auto isDerivedFromTrimmedCurve = geo->isDerivedFrom(Part::GeomTrimmedCurve::getClassTypeId()); auto isCircle = geo->getTypeId() == Part::GeomCircle::getClassTypeId(); auto isEllipse = geo->getTypeId() == Part::GeomEllipse::getClassTypeId(); - if(isBSpline) { + if (isBSpline) { // Two options, it is a periodic bspline and we need two intersections or // it is a non-periodic bspline and one intersection is enough. - auto bspline = static_cast(geo); + auto bspline = static_cast(geo); - if(bspline->isPeriodic() && (GeoId1 == GeoEnum::GeoUndef || GeoId2 == GeoEnum::GeoUndef)) + if (bspline->isPeriodic() && (GeoId1 == GeoEnum::GeoUndef || GeoId2 == GeoEnum::GeoUndef)) return -1; - ifBSplineRemoveInternalAlignmentGeometry(GeoId); // GeoId gets updated here + ifBSplineRemoveInternalAlignmentGeometry(GeoId);// GeoId gets updated here // When internal alignment geometry is removed from a bspline, it moves slightly // this causes that small segments are detected near the endpoints. // // The alternative to this re-detection, is to remove the internal alignment geometry - // before the detection. However, that would cause the lost of the internal alignment geometry - // in a case where trimming does not succeed because seekTrimPoints fails to find (suitable) intersection(s) - if(!SketchObject::seekTrimPoints(GeoId, point, GeoId1, point1, GeoId2, point2)) { + // before the detection. However, that would cause the lost of the internal alignment + // geometry in a case where trimming does not succeed because seekTrimPoints fails to find + // (suitable) intersection(s) + if (!SketchObject::seekTrimPoints(GeoId, point, GeoId1, point1, GeoId2, point2)) { // If no suitable trim points are found, then trim defaults to deleting the geometry delGeometry(GeoId); return 0; @@ -2617,21 +2827,23 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) geo = getGeometry(GeoId); } - if( GeoId1 != GeoEnum::GeoUndef && - GeoId2 != GeoEnum::GeoUndef && - arePointsWithinPrecision(point1, point2) ) { // If both points are detected and are coincident, deletion is the only option. + if (GeoId1 != GeoEnum::GeoUndef && GeoId2 != GeoEnum::GeoUndef + && arePointsWithinPrecision(point1, point2)) { + // If both points are detected and are coincident, deletion is the only option. delGeometry(GeoId); return 0; } - //******************* Step B.1 => Trimming for GeomTrimmedCurves (line segment and arcs) ****************************************// - if (isDerivedFromTrimmedCurve || isNonPeriodicBSpline ) { + //******************* Step B.1 => Trimming for GeomTrimmedCurves (line segment and arcs) + //****************************************// + if (isDerivedFromTrimmedCurve || isNonPeriodicBSpline) { - if(geo->isDerivedFrom(Part::GeomConic::getClassTypeId())) { - auto *tc = static_cast(geo); - if(tc->isReversed()) { - const_cast(tc)->reverse(); // reversing does not change the curve as seen by the sketcher. + if (geo->isDerivedFrom(Part::GeomConic::getClassTypeId())) { + auto* tc = static_cast(geo); + if (tc->isReversed()) { + // reversing does not change the curve as seen by the sketcher. + const_cast(tc)->reverse(); } } @@ -2642,25 +2854,30 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) auto aoc = static_cast(geo); aoc->getRange(firstParam, lastParam); } - else if(isNonPeriodicBSpline) { + else if (isNonPeriodicBSpline) { auto bsp = static_cast(geo); firstParam = bsp->getFirstParameter(); lastParam = bsp->getLastParameter(); } double pointParam, point1Param, point2Param; - if(!getIntersectionParameters(geo, point, pointParam, point1, point1Param, point2, point2Param)) + if (!getIntersectionParameters( + geo, point, pointParam, point1, point1Param, point2, point2Param)) return -1; #ifdef DEBUG - Base::Console().Log("Trim sought: GeoId1=%d (%f), GeoId2=%d (%f)\n",GeoId1, point1Param, GeoId2, point2Param); + Base::Console().Log("Trim sought: GeoId1=%d (%f), GeoId2=%d (%f)\n", + GeoId1, + point1Param, + GeoId2, + point2Param); #endif // seekTrimPoints enforces that firstParam < point1Param < point2Param < lastParam auto paramDistance = [](double param1, double param2) { double distance = fabs(param1 - param2); - if(distance < Precision::Confusion()) + if (distance < Precision::Confusion()) return 0.; else return distance; @@ -2669,17 +2886,27 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) //****** Step B.1 (2) => Determine trimmable sections and trim operation ******// // Determine if there is something trimmable - double startDistance = GeoId1 != GeoEnum::GeoUndef?paramDistance(firstParam, point1Param):paramDistance(firstParam, point2Param); - double endDistance = GeoId2 != GeoEnum::GeoUndef?paramDistance(lastParam, point2Param):paramDistance(lastParam, point1Param); - double middleDistance = (GeoId1 != GeoEnum::GeoUndef && GeoId2 != GeoEnum::GeoUndef)?paramDistance(point1Param, point2Param):0.0; + double startDistance = GeoId1 != GeoEnum::GeoUndef ? paramDistance(firstParam, point1Param) + : paramDistance(firstParam, point2Param); + double endDistance = GeoId2 != GeoEnum::GeoUndef ? paramDistance(lastParam, point2Param) + : paramDistance(lastParam, point1Param); + double middleDistance = (GeoId1 != GeoEnum::GeoUndef && GeoId2 != GeoEnum::GeoUndef) + ? paramDistance(point1Param, point2Param) + : 0.0; bool trimmableStart = startDistance > 0.; bool trimmableMiddle = middleDistance > 0.; bool trimmableEnd = endDistance > 0.; - struct Operation { - Operation():Type(trim_none), actingParam(0.), intersectingGeoId(GeoEnum::GeoUndef){} - enum { + struct Operation + { + Operation() + : Type(trim_none), + actingParam(0.), + intersectingGeoId(GeoEnum::GeoUndef) + {} + enum + { trim_none, trim_start, trim_middle, @@ -2694,33 +2921,34 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) Operation op; - if ( GeoId1!=GeoEnum::GeoUndef && - GeoId2!=GeoEnum::GeoUndef && - pointParam > point1Param && pointParam < point2Param ) { // Trim Point between intersection points + if (GeoId1 != GeoEnum::GeoUndef && GeoId2 != GeoEnum::GeoUndef && pointParam > point1Param + && pointParam < point2Param) { + // Trim Point between intersection points - if( (!trimmableStart && !trimmableEnd) || !trimmableMiddle) { // if after trimming nothing would be left or if there is nothing to trim + if ((!trimmableStart && !trimmableEnd) || !trimmableMiddle) { + // if after trimming nothing would be left or if there is nothing to trim op.Type = Operation::trim_delete; } - else if(trimmableStart && trimmableEnd) { - op.Type = Operation::trim_middle; // trim between point1Param and point2Param + else if (trimmableStart && trimmableEnd) { + op.Type = Operation::trim_middle;// trim between point1Param and point2Param } else if (trimmableStart /*&&!trimmableEnd*/) { op.Type = Operation::trim_end; - op.actingParam = point1Param; // trim from point1Param until lastParam + op.actingParam = point1Param;// trim from point1Param until lastParam op.actingPoint = point1; op.intersectingGeoId = GeoId1; } - else { // !trimmableStart && trimmableEnd + else {// !trimmableStart && trimmableEnd op.Type = Operation::trim_start; - op.actingParam = point2Param; // trim from firstParam until point2Param + op.actingParam = point2Param;// trim from firstParam until point2Param op.actingPoint = point2; op.intersectingGeoId = GeoId2; } } - else if (GeoId2!=GeoEnum::GeoUndef && pointParam < point2Param) { - if(trimmableEnd) { + else if (GeoId2 != GeoEnum::GeoUndef && pointParam < point2Param) { + if (trimmableEnd) { op.Type = Operation::trim_start; - op.actingParam = point2Param; // trim from firstParam until point2Param + op.actingParam = point2Param;// trim from firstParam until point2Param op.actingPoint = point2; op.intersectingGeoId = GeoId2; } @@ -2728,10 +2956,10 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) op.Type = Operation::trim_delete; } } - else if (GeoId1!=GeoEnum::GeoUndef && pointParam > point1Param) { - if(trimmableStart) { + else if (GeoId1 != GeoEnum::GeoUndef && pointParam > point1Param) { + if (trimmableStart) { op.Type = Operation::trim_end; - op.actingParam = point1Param; // trim from point1Param until lastParam + op.actingParam = point1Param;// trim from point1Param until lastParam op.actingPoint = point1; op.intersectingGeoId = GeoId1; } @@ -2745,13 +2973,14 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) //****** Step B.1 (3) => Execute Trimming operation ******// - if( op.Type == Operation::trim_delete) { + if (op.Type == Operation::trim_delete) { delGeometry(GeoId); return 0; } - else if ( op.Type == Operation::trim_middle ) { - // We need to create new curve, this new curve will represent the segment comprising the end + else if (op.Type == Operation::trim_middle) { + // We need to create new curve, this new curve will represent the segment comprising the + // end auto vals = getInternalGeometry(); auto newVals(vals); newVals[GeoId] = newVals[GeoId]->clone(); @@ -2759,12 +2988,14 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) int newGeoId = newVals.size() - 1; if (isDerivedFromTrimmedCurve) { - static_cast(newVals[GeoId])->setRange(firstParam, point1Param); - static_cast(newVals.back())->setRange(point2Param, lastParam); + static_cast(newVals[GeoId]) + ->setRange(firstParam, point1Param); + static_cast(newVals.back()) + ->setRange(point2Param, lastParam); } - else if(isNonPeriodicBSpline) { - static_cast(newVals[GeoId])->Trim( firstParam, point1Param); - static_cast(newVals.back())->Trim( point2Param, lastParam); + else if (isNonPeriodicBSpline) { + static_cast(newVals[GeoId])->Trim(firstParam, point1Param); + static_cast(newVals.back())->Trim(point2Param, lastParam); } Geometry.setValues(std::move(newVals)); @@ -2772,14 +3003,15 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) // go through all constraints and replace the point (GeoId,end) with (newGeoId,end) transferConstraints(GeoId, PointPos::end, newGeoId, PointPos::end); - // For a trimmed line segment, if it had an equality constraint, it must be removed as the segment length is not equal - // For the rest of trimmed curves, the proportion shall be constrain to be equal. - if(isLineSegment) { + // For a trimmed line segment, if it had an equality constraint, it must be removed as + // the segment length is not equal For the rest of trimmed curves, the proportion shall + // be constrain to be equal. + if (isLineSegment) { delEqualConstraintsOnGeoId(GeoId); delEqualConstraintsOnGeoId(newGeoId); } - if(!isLineSegment && !isNonPeriodicBSpline) { + if (!isLineSegment && !isNonPeriodicBSpline) { constrainAsEqual(GeoId, newGeoId); } @@ -2787,80 +3019,94 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) // constrain the trimming points on the corresponding geometries PointPos secondPos1 = Sketcher::PointPos::none, secondPos2 = Sketcher::PointPos::none; - ConstraintType constrType1 = Sketcher::PointOnObject, constrType2 = Sketcher::PointOnObject; + ConstraintType constrType1 = Sketcher::PointOnObject, + constrType2 = Sketcher::PointOnObject; // Segment comprising the start - transformPreexistingConstraints (GeoId, GeoId1, point1, constrType1, secondPos1); + transformPreexistingConstraints(GeoId, GeoId1, point1, constrType1, secondPos1); - addConstraint (constrType1, GeoId, Sketcher::PointPos::end, GeoId1, secondPos1); + addConstraint(constrType1, GeoId, Sketcher::PointPos::end, GeoId1, secondPos1); // Segment comprising the end - transformPreexistingConstraints (GeoId, GeoId2, point2, constrType2, secondPos2); + transformPreexistingConstraints(GeoId, GeoId2, point2, constrType2, secondPos2); - addConstraint (constrType2, newGeoId, Sketcher::PointPos::start, GeoId2, secondPos2); + addConstraint(constrType2, newGeoId, Sketcher::PointPos::start, GeoId2, secondPos2); // Both segments have a coincident center - if(!isLineSegment && !isBSpline) { - addConstraint(Sketcher::Coincident, GeoId, Sketcher::PointPos::mid, newGeoId, Sketcher::PointPos::mid); + if (!isLineSegment && !isBSpline) { + addConstraint(Sketcher::Coincident, + GeoId, + Sketcher::PointPos::mid, + newGeoId, + Sketcher::PointPos::mid); } if (isNonPeriodicBSpline) exposeInternalGeometry(GeoId); - if(noRecomputes) // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute, the sketch must be solved to update the DoF of the + // solver + if (noRecomputes) solve(); return 0; } - else if ( op.Type == Operation::trim_start || op.Type == Operation::trim_end ) { // drop the second/first intersection point + else if (op.Type == Operation::trim_start || op.Type == Operation::trim_end) { + // drop the second/first intersection point geo = getGeometry(GeoId); if (isDerivedFromTrimmedCurve) { - auto newGeo = std::unique_ptr(static_cast( geo->clone())); + auto newGeo = std::unique_ptr( + static_cast(geo->clone())); if (op.Type == Operation::trim_start) - newGeo->setRange( op.actingParam, lastParam); + newGeo->setRange(op.actingParam, lastParam); else if (op.Type == Operation::trim_end) - newGeo->setRange( firstParam, op.actingParam); + newGeo->setRange(firstParam, op.actingParam); Geometry.set1Value(GeoId, std::move(newGeo)); } - else if(isNonPeriodicBSpline) { - auto newGeo = std::unique_ptr(static_cast( geo->clone())); + else if (isNonPeriodicBSpline) { + auto newGeo = std::unique_ptr( + static_cast(geo->clone())); if (op.Type == Operation::trim_start) - newGeo->Trim( op.actingParam, lastParam); + newGeo->Trim(op.actingParam, lastParam); else if (op.Type == Operation::trim_end) - newGeo->Trim( firstParam, op.actingParam); + newGeo->Trim(firstParam, op.actingParam); Geometry.set1Value(GeoId, std::move(newGeo)); } // After trimming it, a line segment won't have the same length - if( isLineSegment) { + if (isLineSegment) { delEqualConstraintsOnGeoId(GeoId); } //****** Step B.1 (4) => Constraint end points ******// - ConstraintType constrType = Sketcher::PointOnObject; // So this is the fallback constraint type here. + // So this is the fallback constraint type here. + ConstraintType constrType = Sketcher::PointOnObject; PointPos secondPos = Sketcher::PointPos::none; - transformPreexistingConstraints (GeoId, op.intersectingGeoId, op.actingPoint, constrType, secondPos); + transformPreexistingConstraints( + GeoId, op.intersectingGeoId, op.actingPoint, constrType, secondPos); if (op.Type == Operation::trim_start) { delConstraintOnPoint(GeoId, PointPos::start, false); // constrain the trimming point on the corresponding geometry - addConstraint (constrType, GeoId, PointPos::start, op.intersectingGeoId, secondPos); + addConstraint(constrType, GeoId, PointPos::start, op.intersectingGeoId, secondPos); } else if (op.Type == Operation::trim_end) { delConstraintOnPoint(GeoId, PointPos::end, false); // constrain the trimming point on the corresponding geometry - addConstraint (constrType, GeoId, PointPos::end, op.intersectingGeoId, secondPos); + addConstraint(constrType, GeoId, PointPos::end, op.intersectingGeoId, secondPos); } if (isNonPeriodicBSpline) exposeInternalGeometry(GeoId); - if(noRecomputes) // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute, the sketch must be solved to update the DoF of the + // solver + if (noRecomputes) solve(); return 0; @@ -2869,19 +3115,25 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) return -1; } } - //******************* Step B.2 => Trimming for unbounded periodic geometries ****************************************// - else if ( isCircle || isEllipse || isPeriodicBSpline) { + //******************* Step B.2 => Trimming for unbounded periodic geometries + //****************************************// + else if (isCircle || isEllipse || isPeriodicBSpline) { //****** STEP A(2) => Common tests *****// - if( GeoId1==GeoEnum::GeoUndef || GeoId2==GeoEnum::GeoUndef) + if (GeoId1 == GeoEnum::GeoUndef || GeoId2 == GeoEnum::GeoUndef) return -1; //****** Step B.2 (1) => Determine intersection parameters ******// double pointParam, point1Param, point2Param; - if(!getIntersectionParameters(geo, point, pointParam, point1, point1Param, point2, point2Param)) + if (!getIntersectionParameters( + geo, point, pointParam, point1, point1Param, point2, point2Param)) return -1; #ifdef DEBUG - Base::Console().Log("Trim sought: GeoId1=%d (%f), GeoId2=%d (%f)\n",GeoId1, point1Param, GeoId2, point2Param); + Base::Console().Log("Trim sought: GeoId1=%d (%f), GeoId2=%d (%f)\n", + GeoId1, + point1Param, + GeoId2, + point2Param); #endif //****** Step B.2 (3) => Execute Trimming operation ******// @@ -2893,7 +3145,7 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) auto aoc = std::make_unique(); aoc->setCenter(circle->getCenter()); aoc->setRadius(circle->getRadius()); - aoc->setRange(point2Param, point1Param,/*emulateCCW=*/false); + aoc->setRange(point2Param, point1Param, /*emulateCCW=*/false); geoNew = std::move(aoc); } else if (isEllipse) { @@ -2903,13 +3155,15 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) aoe->setMajorRadius(ellipse->getMajorRadius()); aoe->setMinorRadius(ellipse->getMinorRadius()); aoe->setMajorAxisDir(ellipse->getMajorAxisDir()); - aoe->setRange(point2Param, point1Param,/*emulateCCW=*/false); // CCW curve goes from point2 (start) to point1 (end) - geoNew = std::move( aoe ); + // CCW curve goes from point2 (start) to point1 (end) + aoe->setRange(point2Param, point1Param, /*emulateCCW=*/false); + geoNew = std::move(aoe); } else if (isPeriodicBSpline) { - auto bspline = std::unique_ptr(static_cast(geo->clone())); + auto bspline = std::unique_ptr( + static_cast(geo->clone())); bspline->Trim(point2Param, point1Param); - geoNew = std::move( bspline ); + geoNew = std::move(bspline); } this->Geometry.set1Value(GeoId, std::move(geoNew)); @@ -2920,40 +3174,43 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) ConstraintType constrType1 = Sketcher::PointOnObject, constrType2 = Sketcher::PointOnObject; // check first if start and end points are within a confusion tolerance - if(isPointAtPosition(GeoId1, Sketcher::PointPos::start, point1)) { - constrType1 = Sketcher::Coincident; - secondPos1 = Sketcher::PointPos::start; + if (isPointAtPosition(GeoId1, Sketcher::PointPos::start, point1)) { + constrType1 = Sketcher::Coincident; + secondPos1 = Sketcher::PointPos::start; } - else if(isPointAtPosition(GeoId1, Sketcher::PointPos::end, point1)) { - constrType1 = Sketcher::Coincident; - secondPos1 = Sketcher::PointPos::end; + else if (isPointAtPosition(GeoId1, Sketcher::PointPos::end, point1)) { + constrType1 = Sketcher::Coincident; + secondPos1 = Sketcher::PointPos::end; } - if(isPointAtPosition(GeoId2, Sketcher::PointPos::start, point2)) { - constrType2 = Sketcher::Coincident; - secondPos2 = Sketcher::PointPos::start; + if (isPointAtPosition(GeoId2, Sketcher::PointPos::start, point2)) { + constrType2 = Sketcher::Coincident; + secondPos2 = Sketcher::PointPos::start; } - else if(isPointAtPosition(GeoId2, Sketcher::PointPos::end, point2)) { - constrType2 = Sketcher::Coincident; - secondPos2 = Sketcher::PointPos::end; + else if (isPointAtPosition(GeoId2, Sketcher::PointPos::end, point2)) { + constrType2 = Sketcher::Coincident; + secondPos2 = Sketcher::PointPos::end; } - transformPreexistingConstraints (GeoId, GeoId1, point1, constrType1, secondPos1); - transformPreexistingConstraints (GeoId, GeoId2, point2, constrType2, secondPos2); + transformPreexistingConstraints(GeoId, GeoId1, point1, constrType1, secondPos1); + transformPreexistingConstraints(GeoId, GeoId2, point2, constrType2, secondPos2); - if( (constrType1 == Sketcher::Coincident && secondPos1 == Sketcher::PointPos::none) || - (constrType2 == Sketcher::Coincident && secondPos2 == Sketcher::PointPos::none)) - THROWM(ValueError,"Invalid position Sketcher::PointPos::none when creating a Coincident constraint") + if ((constrType1 == Sketcher::Coincident && secondPos1 == Sketcher::PointPos::none) + || (constrType2 == Sketcher::Coincident && secondPos2 == Sketcher::PointPos::none)) + THROWM( + ValueError, + "Invalid position Sketcher::PointPos::none when creating a Coincident constraint") // constrain the trimming points on the corresponding geometries - addConstraint (constrType1, GeoId, PointPos::end, GeoId1, secondPos1); + addConstraint(constrType1, GeoId, PointPos::end, GeoId1, secondPos1); - addConstraint (constrType2, GeoId, PointPos::start, GeoId2, secondPos2); + addConstraint(constrType2, GeoId, PointPos::start, GeoId2, secondPos2); if (isBSpline) exposeInternalGeometry(GeoId); - if(noRecomputes) // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + if (noRecomputes) solve(); return 0; @@ -2962,7 +3219,7 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) return -1; } -int SketchObject::split(int GeoId, const Base::Vector3d &point) +int SketchObject::split(int GeoId, const Base::Vector3d& point) { // No need to check input data validity as this is an sketchobject managed operation @@ -2972,97 +3229,96 @@ int SketchObject::split(int GeoId, const Base::Vector3d &point) return -1; } - const Part::Geometry *geo = getGeometry(GeoId); + const Part::Geometry* geo = getGeometry(GeoId); std::vector newIds; - std::vector newConstraints; + std::vector newConstraints; Base::Vector3d startPoint, endPoint, splitPoint; - double startParam, endParam, splitParam=0.0; + double startParam, endParam, splitParam = 0.0; unsigned int longestPart = 0; - auto createGeosFromPeriodic = - [&](const Part::GeomCurve* curve, - auto getCurveWithLimitParams, - auto createAndTransferConstraints) { - // find split point - curve->closestParameter(point, splitParam); - double period = curve->getLastParameter() - curve->getFirstParameter(); - startParam = splitParam; - endParam = splitParam + period; + auto createGeosFromPeriodic = [&](const Part::GeomCurve* curve, + auto getCurveWithLimitParams, + auto createAndTransferConstraints) { + // find split point + curve->closestParameter(point, splitParam); + double period = curve->getLastParameter() - curve->getFirstParameter(); + startParam = splitParam; + endParam = splitParam + period; - // create new arc and restrict it - auto newCurve = getCurveWithLimitParams(curve, startParam, endParam); - int newId(GeoEnum::GeoUndef); - newId = addGeometry(std::move(newCurve)); // after here newCurve is a shell - if (newId >= 0) { - newIds.push_back(newId); - setConstruction(newId, GeometryFacade::getConstruction(curve)); - exposeInternalGeometry(newId); + // create new arc and restrict it + auto newCurve = getCurveWithLimitParams(curve, startParam, endParam); + int newId(GeoEnum::GeoUndef); + newId = addGeometry(std::move(newCurve));// after here newCurve is a shell + if (newId >= 0) { + newIds.push_back(newId); + setConstruction(newId, GeometryFacade::getConstruction(curve)); + exposeInternalGeometry(newId); - // transfer any constraints - createAndTransferConstraints(GeoId, newId); - return true; - } + // transfer any constraints + createAndTransferConstraints(GeoId, newId); + return true; + } - return false; - }; + return false; + }; - auto createGeosFromNonPeriodic = - [&](const Part::GeomBoundedCurve* curve, - auto getCurveWithLimitParams, - auto createAndTransferConstraints) { - startPoint = curve->getStartPoint(); - endPoint = curve->getEndPoint(); + auto createGeosFromNonPeriodic = [&](const Part::GeomBoundedCurve* curve, + auto getCurveWithLimitParams, + auto createAndTransferConstraints) { + startPoint = curve->getStartPoint(); + endPoint = curve->getEndPoint(); - // find split point - curve->closestParameter(point, splitParam); - startParam = curve->getFirstParameter(); - endParam = curve->getLastParameter(); - // TODO: Using parameter difference as a poor substitute of length. - // Computing length of an arc of a generic conic would be expensive. - if (endParam - splitParam < Precision::PConfusion() || - splitParam - startParam < Precision::PConfusion()) { - THROWM(ValueError, "Split point is at one of the end points of the curve."); - } - if (endParam - splitParam > splitParam - startParam) { - longestPart = 1; - } + // find split point + curve->closestParameter(point, splitParam); + startParam = curve->getFirstParameter(); + endParam = curve->getLastParameter(); + // TODO: Using parameter difference as a poor substitute of length. + // Computing length of an arc of a generic conic would be expensive. + if (endParam - splitParam < Precision::PConfusion() + || splitParam - startParam < Precision::PConfusion()) { + THROWM(ValueError, "Split point is at one of the end points of the curve."); + } + if (endParam - splitParam > splitParam - startParam) { + longestPart = 1; + } - // create new curves - auto newCurve = getCurveWithLimitParams(curve, startParam, splitParam); - int newId(GeoEnum::GeoUndef); + // create new curves + auto newCurve = getCurveWithLimitParams(curve, startParam, splitParam); + int newId(GeoEnum::GeoUndef); + newId = addGeometry(std::move(newCurve)); + if (newId >= 0) { + newIds.push_back(newId); + setConstruction(newId, GeometryFacade::getConstruction(curve)); + exposeInternalGeometry(newId); + + // the "second" half + newCurve = getCurveWithLimitParams(curve, splitParam, endParam); newId = addGeometry(std::move(newCurve)); if (newId >= 0) { newIds.push_back(newId); setConstruction(newId, GeometryFacade::getConstruction(curve)); exposeInternalGeometry(newId); - // the "second" half - newCurve = getCurveWithLimitParams(curve, splitParam, endParam); - newId = addGeometry(std::move(newCurve)); - if (newId >= 0) { - newIds.push_back(newId); - setConstruction(newId, GeometryFacade::getConstruction(curve)); - exposeInternalGeometry(newId); - - // TODO: Certain transfers and new constraint can be directly made here. - // But this may reduce readability. - // apply appropriate constraints on the new points at split point and - // transfer constraints from start and end of original spline - createAndTransferConstraints(GeoId, newIds[0], newIds[1]); - return true; - } + // TODO: Certain transfers and new constraint can be directly made here. + // But this may reduce readability. + // apply appropriate constraints on the new points at split point and + // transfer constraints from start and end of original spline + createAndTransferConstraints(GeoId, newIds[0], newIds[1]); + return true; } + } - return false; - }; + return false; + }; bool ok = false; if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { ok = createGeosFromNonPeriodic( - static_cast(geo), + static_cast(geo), [](const Part::GeomCurve* curve, double startParam, double endParam) { - auto newArc = std::unique_ptr(static_cast(curve->copy())); + auto newArc = std::unique_ptr( + static_cast(curve->copy())); newArc->setRange(startParam, endParam); return newArc; }, @@ -3081,9 +3337,10 @@ int SketchObject::split(int GeoId, const Base::Vector3d &point) } else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { ok = createGeosFromPeriodic( - static_cast(geo), + static_cast(geo), [](const Part::GeomCurve* curve, double startParam, double endParam) { - auto newArc = std::make_unique(Handle(Geom_Circle)::DownCast(curve->handle()->Copy())); + auto newArc = std::make_unique( + Handle(Geom_Circle)::DownCast(curve->handle()->Copy())); newArc->setRange(startParam, endParam, false); return newArc; }, @@ -3093,9 +3350,10 @@ int SketchObject::split(int GeoId, const Base::Vector3d &point) } else if (geo->getTypeId() == Part::GeomEllipse::getClassTypeId()) { ok = createGeosFromPeriodic( - static_cast(geo), + static_cast(geo), [](const Part::GeomCurve* curve, double startParam, double endParam) { - auto newArc = std::make_unique(Handle(Geom_Ellipse)::DownCast(curve->handle()->Copy())); + auto newArc = std::make_unique( + Handle(Geom_Ellipse)::DownCast(curve->handle()->Copy())); newArc->setRange(startParam, endParam, false); return newArc; }, @@ -3105,9 +3363,10 @@ int SketchObject::split(int GeoId, const Base::Vector3d &point) } else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { ok = createGeosFromNonPeriodic( - static_cast(geo), + static_cast(geo), [](const Part::GeomCurve* curve, double startParam, double endParam) { - auto newArc = std::unique_ptr(static_cast(curve->copy())); + auto newArc = std::unique_ptr( + static_cast(curve->copy())); newArc->setRange(startParam, endParam, false); return newArc; }, @@ -3135,9 +3394,10 @@ int SketchObject::split(int GeoId, const Base::Vector3d &point) } else if (geo->isDerivedFrom(Part::GeomArcOfConic::getClassTypeId())) { ok = createGeosFromNonPeriodic( - static_cast(geo), + static_cast(geo), [](const Part::GeomCurve* curve, double startParam, double endParam) { - auto newArc = std::unique_ptr(static_cast(curve->copy())); + auto newArc = std::unique_ptr( + static_cast(curve->copy())); newArc->setRange(startParam, endParam); return newArc; }, @@ -3159,26 +3419,29 @@ int SketchObject::split(int GeoId, const Base::Vector3d &point) }); } else if (geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { - const Part::GeomBSplineCurve *bsp = static_cast(geo); + const Part::GeomBSplineCurve* bsp = static_cast(geo); // what to do for periodic b-splines? if (bsp->isPeriodic()) { ok = createGeosFromPeriodic( - static_cast(geo), + static_cast(geo), [](const Part::GeomCurve* curve, double startParam, double endParam) { - auto newBsp = std::unique_ptr(static_cast(curve->copy())); + auto newBsp = std::unique_ptr( + static_cast(curve->copy())); newBsp->Trim(startParam, endParam); return newBsp; }, [](int, int) { - // no constraints to transfer here, and we assume the split is to "break" the b-spline + // no constraints to transfer here, and we assume the split is to "break" the + // b-spline }); } else { ok = createGeosFromNonPeriodic( - static_cast(geo), + static_cast(geo), [](const Part::GeomCurve* curve, double startParam, double endParam) { - auto newBsp = std::unique_ptr(static_cast(curve->copy())); + auto newBsp = std::unique_ptr( + static_cast(curve->copy())); newBsp->Trim(startParam, endParam); return newBsp; }, @@ -3207,15 +3470,16 @@ int SketchObject::split(int GeoId, const Base::Vector3d &point) // keep constraints on internal geometries so they are deleted // when the old curve is deleted - oldConstraints.erase( - std::remove_if( - oldConstraints.begin(), oldConstraints.end(), - [=](const auto& i){return allConstraints[i]->Type == InternalAlignment;}), - oldConstraints.end()); + oldConstraints.erase(std::remove_if(oldConstraints.begin(), + oldConstraints.end(), + [=](const auto& i) { + return allConstraints[i]->Type == InternalAlignment; + }), + oldConstraints.end()); for (unsigned int i = 0; i < oldConstraints.size(); ++i) { - Constraint *con = allConstraints[oldConstraints[i]]; + Constraint* con = allConstraints[oldConstraints[i]]; int conId = con->First; PointPos conPos = con->FirstPos; if (conId == GeoId) { @@ -3225,102 +3489,104 @@ int SketchObject::split(int GeoId, const Base::Vector3d &point) bool transferToAll = false; switch (con->Type) { - case Horizontal: - case Vertical: - case Parallel: { - transferToAll = geo->getTypeId() == Part::GeomLineSegment::getClassTypeId(); - break; - } - case Tangent: - case Perpendicular: { - unsigned int initial = 0; - unsigned int limit = newIds.size(); - - if (geo->isDerivedFrom(Part::GeomArcOfConic::getClassTypeId())) { - const Part::Geometry *conGeo = getGeometry(conId); - - if (conGeo && conGeo->isDerivedFrom(Part::GeomCurve::getClassTypeId())){ - std::vector> intersections; - bool intersects[2]; - auto *geo1 = getGeometry(newIds[0]); - auto *geo2 = getGeometry(newIds[1]); - - intersects[0] = static_cast(geo1)-> - intersect(static_cast(conGeo), intersections); - intersects[1] = static_cast(geo2)-> - intersect(static_cast(conGeo), intersections); - - initial = longestPart; - if (intersects[0] != intersects[1]) { - initial = intersects[1] ? 1 : 0; - } - limit = initial + 1; - } + case Horizontal: + case Vertical: + case Parallel: { + transferToAll = geo->getTypeId() == Part::GeomLineSegment::getClassTypeId(); + break; } + case Tangent: + case Perpendicular: { + unsigned int initial = 0; + unsigned int limit = newIds.size(); - for (unsigned int i = initial; i < limit; ++i) { - Constraint *trans = con->copy(); - trans->substituteIndex(GeoId, newIds[i]); - newConstraints.push_back(trans); - } - break; - } - case Distance: - case DistanceX: - case DistanceY: - case PointOnObject: { - if (con->FirstPos == PointPos::none && con->SecondPos == PointPos::none) { - Constraint *dist = con->copy(); - dist->First = newIds[0]; - dist->FirstPos = PointPos::start; - dist->Second = newIds[1]; - dist->SecondPos = PointPos::end; - newConstraints.push_back(dist); - } - else { - Constraint *trans = con->copy(); - trans->First = conId; - trans->FirstPos = conPos; - trans->SecondPos = PointPos::none; + if (geo->isDerivedFrom(Part::GeomArcOfConic::getClassTypeId())) { + const Part::Geometry* conGeo = getGeometry(conId); - Base::Vector3d conPoint(getPoint(conId, conPos)); - int targetId = newIds[0]; + if (conGeo && conGeo->isDerivedFrom(Part::GeomCurve::getClassTypeId())) { + std::vector> intersections; + bool intersects[2]; + auto* geo1 = getGeometry(newIds[0]); + auto* geo2 = getGeometry(newIds[1]); - // for non-periodic curves, see if second curve is more appropriate - if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - Base::Vector3d projPoint(conPoint.Perpendicular(startPoint, endPoint - startPoint)); - Base::Vector3d splitDir = splitPoint - startPoint; - if ((projPoint - startPoint)*splitDir > splitDir*splitDir) { - targetId = newIds[1]; + intersects[0] = static_cast(geo1)->intersect( + static_cast(conGeo), intersections); + intersects[1] = static_cast(geo2)->intersect( + static_cast(conGeo), intersections); + + initial = longestPart; + if (intersects[0] != intersects[1]) { + initial = intersects[1] ? 1 : 0; + } + limit = initial + 1; } } - else if (geo->isDerivedFrom(Part::GeomArcOfConic::getClassTypeId())) { - double conParam; - static_cast(geo)->closestParameter(conPoint, conParam); - if (conParam > splitParam) - targetId = newIds[1]; - } - trans->Second = targetId; - newConstraints.push_back(trans); + for (unsigned int i = initial; i < limit; ++i) { + Constraint* trans = con->copy(); + trans->substituteIndex(GeoId, newIds[i]); + newConstraints.push_back(trans); + } + break; } - break; - } - case Radius: - case Diameter: - case Equal: { - transferToAll = geo->getTypeId() == Part::GeomCircle::getClassTypeId() - || geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId(); - break; - } - default: - // Release other constraints - break; + case Distance: + case DistanceX: + case DistanceY: + case PointOnObject: { + if (con->FirstPos == PointPos::none && con->SecondPos == PointPos::none) { + Constraint* dist = con->copy(); + dist->First = newIds[0]; + dist->FirstPos = PointPos::start; + dist->Second = newIds[1]; + dist->SecondPos = PointPos::end; + newConstraints.push_back(dist); + } + else { + Constraint* trans = con->copy(); + trans->First = conId; + trans->FirstPos = conPos; + trans->SecondPos = PointPos::none; + + Base::Vector3d conPoint(getPoint(conId, conPos)); + int targetId = newIds[0]; + + // for non-periodic curves, see if second curve is more appropriate + if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + Base::Vector3d projPoint( + conPoint.Perpendicular(startPoint, endPoint - startPoint)); + Base::Vector3d splitDir = splitPoint - startPoint; + if ((projPoint - startPoint) * splitDir > splitDir * splitDir) { + targetId = newIds[1]; + } + } + else if (geo->isDerivedFrom(Part::GeomArcOfConic::getClassTypeId())) { + double conParam; + static_cast(geo)->closestParameter( + conPoint, conParam); + if (conParam > splitParam) + targetId = newIds[1]; + } + trans->Second = targetId; + + newConstraints.push_back(trans); + } + break; + } + case Radius: + case Diameter: + case Equal: { + transferToAll = geo->getTypeId() == Part::GeomCircle::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId(); + break; + } + default: + // Release other constraints + break; } if (transferToAll) { - for (auto& newId: newIds) { - Constraint *trans = con->copy(); + for (auto& newId : newIds) { + Constraint* trans = con->copy(); trans->substituteIndex(GeoId, newId); newConstraints.push_back(trans); } @@ -3334,7 +3600,7 @@ int SketchObject::split(int GeoId, const Base::Vector3d &point) addConstraints(newConstraints); } - for (auto& cons: newConstraints) { + for (auto& cons : newConstraints) { delete cons; } @@ -3346,35 +3612,34 @@ int SketchObject::split(int GeoId, const Base::Vector3d &point) return -1; } -int SketchObject::join(int geoId1, Sketcher::PointPos posId1, - int geoId2, Sketcher::PointPos posId2) +int SketchObject::join(int geoId1, Sketcher::PointPos posId1, int geoId2, Sketcher::PointPos posId2) { // No need to check input data validity as this is an sketchobject managed operation Base::StateLocker lock(managedoperation, true); - if (Sketcher::PointPos::start != posId1 && Sketcher::PointPos::end != posId1 && - Sketcher::PointPos::start != posId2 && Sketcher::PointPos::end != posId2) { - THROWM(ValueError,"Invalid position(s): points must be start or end points of a curve."); + if (Sketcher::PointPos::start != posId1 && Sketcher::PointPos::end != posId1 + && Sketcher::PointPos::start != posId2 && Sketcher::PointPos::end != posId2) { + THROWM(ValueError, "Invalid position(s): points must be start or end points of a curve."); return -1; } if (geoId1 == geoId2) { - THROWM(ValueError,"Connecting the end points of the same curve is not yet supported."); + THROWM(ValueError, "Connecting the end points of the same curve is not yet supported."); return -1; } - if (geoId1 < 0 || geoId1 > getHighestCurveIndex() || - geoId2 < 0 || geoId2 > getHighestCurveIndex()) { + if (geoId1 < 0 || geoId1 > getHighestCurveIndex() || geoId2 < 0 + || geoId2 > getHighestCurveIndex()) { return -1; } // get the old splines - auto* geo1 = dynamic_cast(getGeometry(geoId1)); - auto* geo2 = dynamic_cast(getGeometry(geoId2)); + auto* geo1 = dynamic_cast(getGeometry(geoId1)); + auto* geo2 = dynamic_cast(getGeometry(geoId2)); if (GeometryFacade::getConstruction(geo1) != GeometryFacade::getConstruction(geo2)) { - THROWM(ValueError,"Cannot join construction and non-construction geometries."); + THROWM(ValueError, "Cannot join construction and non-construction geometries."); return -1; } @@ -3386,11 +3651,13 @@ int SketchObject::join(int geoId1, Sketcher::PointPos posId1, // TODO: is there a cleaner way to get our mutable bsp's? // we need the splines to be mutable because we may reverse them // and/or change their degree - std::unique_ptr bsp1(geo1->toNurbs(geo1->getFirstParameter(), geo1->getLastParameter())); - std::unique_ptr bsp2(geo2->toNurbs(geo2->getFirstParameter(), geo2->getLastParameter())); + std::unique_ptr bsp1( + geo1->toNurbs(geo1->getFirstParameter(), geo1->getLastParameter())); + std::unique_ptr bsp2( + geo2->toNurbs(geo2->getFirstParameter(), geo2->getLastParameter())); if (bsp1->isPeriodic() || bsp2->isPeriodic()) { - THROWM(ValueError,"It is only possible to join non-periodic curves."); + THROWM(ValueError, "It is only possible to join non-periodic curves."); return -1; } @@ -3449,14 +3716,13 @@ int SketchObject::join(int geoId1, Sketcher::PointPos posId1, std::make_move_iterator(mults2.begin()), std::make_move_iterator(mults2.end())); - Part::GeomBSplineCurve* newSpline = - new Part::GeomBSplineCurve(newPoles, newWeights, newKnots, newMults, - bsp1->getDegree(), false, true); + Part::GeomBSplineCurve* newSpline = new Part::GeomBSplineCurve( + newPoles, newWeights, newKnots, newMults, bsp1->getDegree(), false, true); int newGeoId = addGeometry(newSpline); if (newGeoId < 0) { - THROWM(ValueError,"Failed to create joined curve."); + THROWM(ValueError, "Failed to create joined curve."); return -1; } else { @@ -3464,8 +3730,10 @@ int SketchObject::join(int geoId1, Sketcher::PointPos posId1, setConstruction(newGeoId, GeometryFacade::getConstruction(geo1)); // TODO: transfer constraints on the non-connected ends - auto otherPosId1 = (Sketcher::PointPos::start == posId1) ? Sketcher::PointPos::end : Sketcher::PointPos::start; - auto otherPosId2 = (Sketcher::PointPos::start == posId2) ? Sketcher::PointPos::end : Sketcher::PointPos::start; + auto otherPosId1 = (Sketcher::PointPos::start == posId1) ? Sketcher::PointPos::end + : Sketcher::PointPos::start; + auto otherPosId2 = (Sketcher::PointPos::start == posId2) ? Sketcher::PointPos::end + : Sketcher::PointPos::start; transferConstraints(geoId1, otherPosId1, newGeoId, PointPos::start, true); transferConstraints(geoId2, otherPosId2, newGeoId, PointPos::end, true); @@ -3477,43 +3745,49 @@ int SketchObject::join(int geoId1, Sketcher::PointPos posId1, return -1; } -bool SketchObject::isExternalAllowed(App::Document *pDoc, App::DocumentObject *pObj, eReasonList* rsn) const +bool SketchObject::isExternalAllowed(App::Document* pDoc, App::DocumentObject* pObj, + eReasonList* rsn) const { if (rsn) *rsn = rlAllowed; // Externals outside of the Document are NOT allowed - if (this->getDocument() != pDoc){ + if (this->getDocument() != pDoc) { if (rsn) *rsn = rlOtherDoc; return false; } - //circular reference prevention + // circular reference prevention try { - if (!(this->testIfLinkDAGCompatible(pObj))){ + if (!(this->testIfLinkDAGCompatible(pObj))) { if (rsn) *rsn = rlCircularReference; return false; } - } catch (Base::Exception &e) { - Base::Console().Warning("Probably, there is a circular reference in the document. Error: %s\n", e.what()); - return true; //prohibiting this reference won't remove the problem anyway... + } + catch (Base::Exception& e) { + Base::Console().Warning( + "Probably, there is a circular reference in the document. Error: %s\n", e.what()); + return true;// prohibiting this reference won't remove the problem anyway... } - // Note: Checking for the body of the support doesn't work when the support are the three base planes - //App::DocumentObject *support = this->Support.getValue(); + // Note: Checking for the body of the support doesn't work when the support are the three base + // planes + // App::DocumentObject *support = this->Support.getValue(); Part::BodyBase* body_this = Part::BodyBase::findBodyOf(this); Part::BodyBase* body_obj = Part::BodyBase::findBodyOf(pObj); App::Part* part_this = App::Part::getPartOfObject(this); App::Part* part_obj = App::Part::getPartOfObject(pObj); - if (part_this == part_obj){ //either in the same part, or in the root of document + if (part_this == part_obj) {// either in the same part, or in the root of document if (!body_this) { return true; - } else if (body_this == body_obj) { + } + else if (body_this == body_obj) { return true; - } else { + } + else { if (rsn) *rsn = rlOtherBody; return false; @@ -3527,7 +3801,8 @@ bool SketchObject::isExternalAllowed(App::Document *pDoc, App::DocumentObject *p } } -bool SketchObject::isCarbonCopyAllowed(App::Document *pDoc, App::DocumentObject *pObj, bool & xinv, bool & yinv, eReasonList* rsn) const +bool SketchObject::isCarbonCopyAllowed(App::Document* pDoc, App::DocumentObject* pObj, bool& xinv, + bool& yinv, eReasonList* rsn) const { if (rsn) *rsn = rlAllowed; @@ -3539,35 +3814,38 @@ bool SketchObject::isCarbonCopyAllowed(App::Document *pDoc, App::DocumentObject return false; } - SketchObject * psObj = static_cast(pObj); + SketchObject* psObj = static_cast(pObj); // Sketches outside of the Document are NOT allowed - if (this->getDocument() != pDoc){ + if (this->getDocument() != pDoc) { if (rsn) *rsn = rlOtherDoc; return false; } - //circular reference prevention + // circular reference prevention try { - if (!(this->testIfLinkDAGCompatible(pObj))){ + if (!(this->testIfLinkDAGCompatible(pObj))) { if (rsn) *rsn = rlCircularReference; return false; } - } catch (Base::Exception &e) { - Base::Console().Warning("Probably, there is a circular reference in the document. Error: %s\n", e.what()); - return true; //prohibiting this reference won't remove the problem anyway... + } + catch (Base::Exception& e) { + Base::Console().Warning( + "Probably, there is a circular reference in the document. Error: %s\n", e.what()); + return true;// prohibiting this reference won't remove the problem anyway... } - // Note: Checking for the body of the support doesn't work when the support are the three base planes - //App::DocumentObject *support = this->Support.getValue(); + // Note: Checking for the body of the support doesn't work when the support are the three base + // planes + // App::DocumentObject *support = this->Support.getValue(); Part::BodyBase* body_this = Part::BodyBase::findBodyOf(this); Part::BodyBase* body_obj = Part::BodyBase::findBodyOf(pObj); App::Part* part_this = App::Part::getPartOfObject(this); App::Part* part_obj = App::Part::getPartOfObject(pObj); - if (part_this == part_obj){ //either in the same part, or in the root of document + if (part_this == part_obj) {// either in the same part, or in the root of document if (body_this) { if (body_this != body_obj) { if (!this->allowOtherBody) { @@ -3575,14 +3853,17 @@ bool SketchObject::isCarbonCopyAllowed(App::Document *pDoc, App::DocumentObject *rsn = rlOtherBody; return false; } - else if (psObj->getExternalGeometryCount()>2){ // if the original sketch has external geometry AND it is not in this body prevent link + // if the original sketch has external geometry AND it is not in this body prevent + // link + else if (psObj->getExternalGeometryCount() > 2) { if (rsn) *rsn = rlOtherBodyWithLinks; return false; } } } - } else { + } + else { // cross-part relation. Disallow, should be done via shapebinders only if (rsn) *rsn = rlOtherPart; @@ -3590,37 +3871,38 @@ bool SketchObject::isCarbonCopyAllowed(App::Document *pDoc, App::DocumentObject } + const Rotation& srot = psObj->Placement.getValue().getRotation(); + const Rotation& lrot = this->Placement.getValue().getRotation(); - const Rotation & srot = psObj->Placement.getValue().getRotation(); - const Rotation & lrot = this->Placement.getValue().getRotation(); - - Base::Vector3d snormal(0,0,1); - Base::Vector3d sx(1,0,0); - Base::Vector3d sy(0,1,0); + Base::Vector3d snormal(0, 0, 1); + Base::Vector3d sx(1, 0, 0); + Base::Vector3d sy(0, 1, 0); srot.multVec(snormal, snormal); srot.multVec(sx, sx); srot.multVec(sy, sy); - Base::Vector3d lnormal(0,0,1); - Base::Vector3d lx(1,0,0); - Base::Vector3d ly(0,1,0); + Base::Vector3d lnormal(0, 0, 1); + Base::Vector3d lx(1, 0, 0); + Base::Vector3d ly(0, 1, 0); lrot.multVec(lnormal, lnormal); lrot.multVec(lx, lx); lrot.multVec(ly, ly); - double dot = snormal*lnormal; + double dot = snormal * lnormal; double dotx = sx * lx; double doty = sy * ly; // the planes of the sketches must be parallel - if(!allowUnaligned && fabs(fabs(dot)-1) > Precision::Confusion()) { + if (!allowUnaligned && fabs(fabs(dot) - 1) > Precision::Confusion()) { if (rsn) *rsn = rlNonParallel; return false; } // the axis must be aligned - if(!allowUnaligned && ((fabs(fabs(dotx)-1) > Precision::Confusion()) || (fabs(fabs(doty)-1) > Precision::Confusion()))) { + if (!allowUnaligned + && ((fabs(fabs(dotx) - 1) > Precision::Confusion()) + || (fabs(fabs(doty) - 1) > Precision::Confusion()))) { if (rsn) *rsn = rlAxesMisaligned; return false; @@ -3628,35 +3910,41 @@ bool SketchObject::isCarbonCopyAllowed(App::Document *pDoc, App::DocumentObject // the origins of the sketches must be aligned or be the same - Base::Vector3d ddir = (psObj->Placement.getValue().getPosition() - this->Placement.getValue().getPosition()).Normalize(); + Base::Vector3d ddir = + (psObj->Placement.getValue().getPosition() - this->Placement.getValue().getPosition()) + .Normalize(); double alignment = ddir * lnormal; - if(!allowUnaligned && (fabs(fabs(alignment)-1) > Precision::Confusion()) && (psObj->Placement.getValue().getPosition() != this->Placement.getValue().getPosition()) ){ + if (!allowUnaligned && (fabs(fabs(alignment) - 1) > Precision::Confusion()) + && (psObj->Placement.getValue().getPosition() + != this->Placement.getValue().getPosition())) { if (rsn) *rsn = rlOriginsMisaligned; return false; } - xinv = allowUnaligned?false:(fabs(dotx-1) > Precision::Confusion()); - yinv = allowUnaligned?false:(fabs(doty-1) > Precision::Confusion()); + xinv = allowUnaligned ? false : (fabs(dotx - 1) > Precision::Confusion()); + yinv = allowUnaligned ? false : (fabs(doty - 1) > Precision::Confusion()); return true; } -int SketchObject::addSymmetric(const std::vector &geoIdList, int refGeoId, Sketcher::PointPos refPosId/*=Sketcher::PointPos::none*/) +int SketchObject::addSymmetric(const std::vector& geoIdList, int refGeoId, + Sketcher::PointPos refPosId /*=Sketcher::PointPos::none*/) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector< Part::Geometry * > &geovals = getInternalGeometry(); - std::vector< Part::Geometry * > newgeoVals(geovals); + const std::vector& geovals = getInternalGeometry(); + std::vector newgeoVals(geovals); - const std::vector< Constraint * > &constrvals = this->Constraints.getValues(); - std::vector< Constraint * > newconstrVals(constrvals); + const std::vector& constrvals = this->Constraints.getValues(); + std::vector newconstrVals(constrvals); - newgeoVals.reserve(geovals.size()+geoIdList.size()); + newgeoVals.reserve(geovals.size() + geoIdList.size()); - int cgeoid = getHighestCurveIndex()+1; + int cgeoid = getHighestCurveIndex() + 1; std::map geoIdMap; std::map isStartEndInverted; @@ -3666,203 +3954,228 @@ int SketchObject::addSymmetric(const std::vector &geoIdList, int refGeoId, bool refIsAxisAligned = false; if (refGeoId == Sketcher::GeoEnum::VAxis || refGeoId == Sketcher::GeoEnum::HAxis) { refIsAxisAligned = true; - } else { - for (std::vector::const_iterator it = constrvals.begin(); it != constrvals.end(); ++it) { - Constraint *constr = *(it); - if (constr->First == refGeoId && (constr->Type == Sketcher::Vertical || constr->Type == Sketcher::Horizontal)) + } + else { + for (std::vector::const_iterator it = constrvals.begin(); + it != constrvals.end(); + ++it) { + Constraint* constr = *(it); + if (constr->First == refGeoId + && (constr->Type == Sketcher::Vertical || constr->Type == Sketcher::Horizontal)) refIsAxisAligned = true; } } // reference is a line - if(refPosId == Sketcher::PointPos::none) { - const Part::Geometry *georef = getGeometry(refGeoId); - if(georef->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { + if (refPosId == Sketcher::PointPos::none) { + const Part::Geometry* georef = getGeometry(refGeoId); + if (georef->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { Base::Console().Error("Reference for symmetric is neither a point nor a line.\n"); return -1; } - const Part::GeomLineSegment *refGeoLine = static_cast(georef); - //line + const Part::GeomLineSegment* refGeoLine = static_cast(georef); + // line Base::Vector3d refstart = refGeoLine->getStartPoint(); - Base::Vector3d vectline = refGeoLine->getEndPoint()-refstart; + Base::Vector3d vectline = refGeoLine->getEndPoint() - refstart; for (std::vector::const_iterator it = geoIdList.begin(); it != geoIdList.end(); ++it) { - const Part::Geometry *geo = getGeometry(*it); - Part::Geometry *geosym; + const Part::Geometry* geo = getGeometry(*it); + Part::Geometry* geosym; auto gf = GeometryFacade::getFacade(geo); - if(gf->isInternalAligned()) { - // only add this geometry if the corresponding geometry it defines is also in the list. + if (gf->isInternalAligned()) { + // only add this geometry if the corresponding geometry it defines is also in the + // list. int definedGeo = GeoEnum::GeoUndef; - for( auto c : Constraints.getValues()) { - if(c->Type == Sketcher::InternalAlignment && c->First == *it) { + for (auto c : Constraints.getValues()) { + if (c->Type == Sketcher::InternalAlignment && c->First == *it) { definedGeo = c->Second; break; } } - if(std::find(geoIdList.begin(), geoIdList.end(), definedGeo) != geoIdList.end() ) + if (std::find(geoIdList.begin(), geoIdList.end(), definedGeo) != geoIdList.end()) geosym = geo->copy(); - else - continue; // we should not mirror internal alignment geometry, unless the element they define is also mirrored - + else { + // we should not mirror internal alignment geometry, unless the element they + // define is also mirrored + continue; + } } else { geosym = geo->copy(); } // Handle Geometry - if(geosym->getTypeId() == Part::GeomLineSegment::getClassTypeId()){ - Part::GeomLineSegment *geosymline = static_cast(geosym); + if (geosym->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + Part::GeomLineSegment* geosymline = static_cast(geosym); Base::Vector3d sp = geosymline->getStartPoint(); Base::Vector3d ep = geosymline->getEndPoint(); - geosymline->setPoints(sp+2.0*(sp.Perpendicular(refGeoLine->getStartPoint(),vectline)-sp), - ep+2.0*(ep.Perpendicular(refGeoLine->getStartPoint(),vectline)-ep)); + geosymline->setPoints( + sp + 2.0 * (sp.Perpendicular(refGeoLine->getStartPoint(), vectline) - sp), + ep + 2.0 * (ep.Perpendicular(refGeoLine->getStartPoint(), vectline) - ep)); isStartEndInverted.insert(std::make_pair(*it, false)); } - else if(geosym->getTypeId() == Part::GeomCircle::getClassTypeId()){ - Part::GeomCircle *geosymcircle = static_cast(geosym); + else if (geosym->getTypeId() == Part::GeomCircle::getClassTypeId()) { + Part::GeomCircle* geosymcircle = static_cast(geosym); Base::Vector3d cp = geosymcircle->getCenter(); - geosymcircle->setCenter(cp+2.0*(cp.Perpendicular(refGeoLine->getStartPoint(),vectline)-cp)); + geosymcircle->setCenter( + cp + 2.0 * (cp.Perpendicular(refGeoLine->getStartPoint(), vectline) - cp)); isStartEndInverted.insert(std::make_pair(*it, false)); } - else if(geosym->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()){ - Part::GeomArcOfCircle *geoaoc = static_cast(geosym); + else if (geosym->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + Part::GeomArcOfCircle* geoaoc = static_cast(geosym); Base::Vector3d sp = geoaoc->getStartPoint(true); Base::Vector3d ep = geoaoc->getEndPoint(true); Base::Vector3d cp = geoaoc->getCenter(); - Base::Vector3d ssp = sp+2.0*(sp.Perpendicular(refGeoLine->getStartPoint(),vectline)-sp); - Base::Vector3d sep = ep+2.0*(ep.Perpendicular(refGeoLine->getStartPoint(),vectline)-ep); - Base::Vector3d scp = cp+2.0*(cp.Perpendicular(refGeoLine->getStartPoint(),vectline)-cp); + Base::Vector3d ssp = + sp + 2.0 * (sp.Perpendicular(refGeoLine->getStartPoint(), vectline) - sp); + Base::Vector3d sep = + ep + 2.0 * (ep.Perpendicular(refGeoLine->getStartPoint(), vectline) - ep); + Base::Vector3d scp = + cp + 2.0 * (cp.Perpendicular(refGeoLine->getStartPoint(), vectline) - cp); - double theta1 = Base::fmod(atan2(sep.y - scp.y, sep.x - scp.x), 2.f*M_PI); - double theta2 = Base::fmod(atan2(ssp.y - scp.y, ssp.x - scp.x), 2.f*M_PI); + double theta1 = Base::fmod(atan2(sep.y - scp.y, sep.x - scp.x), 2.f * M_PI); + double theta2 = Base::fmod(atan2(ssp.y - scp.y, ssp.x - scp.x), 2.f * M_PI); geoaoc->setCenter(scp); - geoaoc->setRange(theta1,theta2,true); + geoaoc->setRange(theta1, theta2, true); isStartEndInverted.insert(std::make_pair(*it, true)); } - else if(geosym->getTypeId() == Part::GeomEllipse::getClassTypeId()){ - Part::GeomEllipse *geosymellipse = static_cast(geosym); + else if (geosym->getTypeId() == Part::GeomEllipse::getClassTypeId()) { + Part::GeomEllipse* geosymellipse = static_cast(geosym); Base::Vector3d cp = geosymellipse->getCenter(); Base::Vector3d majdir = geosymellipse->getMajorAxisDir(); - double majord=geosymellipse->getMajorRadius(); - double minord=geosymellipse->getMinorRadius(); - double df= sqrt(majord*majord-minord*minord); + double majord = geosymellipse->getMajorRadius(); + double minord = geosymellipse->getMinorRadius(); + double df = sqrt(majord * majord - minord * minord); Base::Vector3d f1 = cp + df * majdir; - Base::Vector3d sf1 = f1+2.0*(f1.Perpendicular(refGeoLine->getStartPoint(),vectline)-f1); - Base::Vector3d scp = cp+2.0*(cp.Perpendicular(refGeoLine->getStartPoint(),vectline)-cp); + Base::Vector3d sf1 = + f1 + 2.0 * (f1.Perpendicular(refGeoLine->getStartPoint(), vectline) - f1); + Base::Vector3d scp = + cp + 2.0 * (cp.Perpendicular(refGeoLine->getStartPoint(), vectline) - cp); - geosymellipse->setMajorAxisDir(sf1-scp); + geosymellipse->setMajorAxisDir(sf1 - scp); geosymellipse->setCenter(scp); isStartEndInverted.insert(std::make_pair(*it, false)); } - else if(geosym->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()){ - Part::GeomArcOfEllipse *geosymaoe = static_cast(geosym); + else if (geosym->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { + Part::GeomArcOfEllipse* geosymaoe = static_cast(geosym); Base::Vector3d cp = geosymaoe->getCenter(); Base::Vector3d majdir = geosymaoe->getMajorAxisDir(); - double majord=geosymaoe->getMajorRadius(); - double minord=geosymaoe->getMinorRadius(); - double df= sqrt(majord*majord-minord*minord); + double majord = geosymaoe->getMajorRadius(); + double minord = geosymaoe->getMinorRadius(); + double df = sqrt(majord * majord - minord * minord); Base::Vector3d f1 = cp + df * majdir; - Base::Vector3d sf1 = f1+2.0*(f1.Perpendicular(refGeoLine->getStartPoint(),vectline)-f1); - Base::Vector3d scp = cp+2.0*(cp.Perpendicular(refGeoLine->getStartPoint(),vectline)-cp); + Base::Vector3d sf1 = + f1 + 2.0 * (f1.Perpendicular(refGeoLine->getStartPoint(), vectline) - f1); + Base::Vector3d scp = + cp + 2.0 * (cp.Perpendicular(refGeoLine->getStartPoint(), vectline) - cp); - geosymaoe->setMajorAxisDir(sf1-scp); + geosymaoe->setMajorAxisDir(sf1 - scp); geosymaoe->setCenter(scp); - double theta1,theta2; - geosymaoe->getRange(theta1,theta2,true); - theta1 = 2.0*M_PI - theta1; - theta2 = 2.0*M_PI - theta2; + double theta1, theta2; + geosymaoe->getRange(theta1, theta2, true); + theta1 = 2.0 * M_PI - theta1; + theta2 = 2.0 * M_PI - theta2; std::swap(theta1, theta2); if (theta1 < 0) { - theta1 += 2.0*M_PI; - theta2 += 2.0*M_PI; + theta1 += 2.0 * M_PI; + theta2 += 2.0 * M_PI; } - geosymaoe->setRange(theta1,theta2,true); + geosymaoe->setRange(theta1, theta2, true); isStartEndInverted.insert(std::make_pair(*it, true)); } - else if(geosym->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()){ - Part::GeomArcOfHyperbola *geosymaoe = static_cast(geosym); + else if (geosym->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + Part::GeomArcOfHyperbola* geosymaoe = + static_cast(geosym); Base::Vector3d cp = geosymaoe->getCenter(); Base::Vector3d majdir = geosymaoe->getMajorAxisDir(); - double majord=geosymaoe->getMajorRadius(); - double minord=geosymaoe->getMinorRadius(); - double df= sqrt(majord*majord+minord*minord); + double majord = geosymaoe->getMajorRadius(); + double minord = geosymaoe->getMinorRadius(); + double df = sqrt(majord * majord + minord * minord); Base::Vector3d f1 = cp + df * majdir; - Base::Vector3d sf1 = f1+2.0*(f1.Perpendicular(refGeoLine->getStartPoint(),vectline)-f1); - Base::Vector3d scp = cp+2.0*(cp.Perpendicular(refGeoLine->getStartPoint(),vectline)-cp); + Base::Vector3d sf1 = + f1 + 2.0 * (f1.Perpendicular(refGeoLine->getStartPoint(), vectline) - f1); + Base::Vector3d scp = + cp + 2.0 * (cp.Perpendicular(refGeoLine->getStartPoint(), vectline) - cp); - geosymaoe->setMajorAxisDir(sf1-scp); + geosymaoe->setMajorAxisDir(sf1 - scp); geosymaoe->setCenter(scp); - double theta1,theta2; - geosymaoe->getRange(theta1,theta2,true); + double theta1, theta2; + geosymaoe->getRange(theta1, theta2, true); theta1 = -theta1; theta2 = -theta2; std::swap(theta1, theta2); - geosymaoe->setRange(theta1,theta2,true); + geosymaoe->setRange(theta1, theta2, true); isStartEndInverted.insert(std::make_pair(*it, true)); } - else if(geosym->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()){ - Part::GeomArcOfParabola *geosymaoe = static_cast(geosym); + else if (geosym->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + Part::GeomArcOfParabola* geosymaoe = static_cast(geosym); Base::Vector3d cp = geosymaoe->getCenter(); - //double df= geosymaoe->getFocal(); + // double df= geosymaoe->getFocal(); Base::Vector3d f1 = geosymaoe->getFocus(); - Base::Vector3d sf1 = f1+2.0*(f1.Perpendicular(refGeoLine->getStartPoint(),vectline)-f1); - Base::Vector3d scp = cp+2.0*(cp.Perpendicular(refGeoLine->getStartPoint(),vectline)-cp); + Base::Vector3d sf1 = + f1 + 2.0 * (f1.Perpendicular(refGeoLine->getStartPoint(), vectline) - f1); + Base::Vector3d scp = + cp + 2.0 * (cp.Perpendicular(refGeoLine->getStartPoint(), vectline) - cp); - geosymaoe->setXAxisDir(sf1-scp); + geosymaoe->setXAxisDir(sf1 - scp); geosymaoe->setCenter(scp); - double theta1,theta2; - geosymaoe->getRange(theta1,theta2,true); + double theta1, theta2; + geosymaoe->getRange(theta1, theta2, true); theta1 = -theta1; theta2 = -theta2; std::swap(theta1, theta2); - geosymaoe->setRange(theta1,theta2,true); + geosymaoe->setRange(theta1, theta2, true); isStartEndInverted.insert(std::make_pair(*it, true)); } - else if(geosym->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()){ - Part::GeomBSplineCurve *geosymbsp = static_cast(geosym); + else if (geosym->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { + Part::GeomBSplineCurve* geosymbsp = static_cast(geosym); std::vector poles = geosymbsp->getPoles(); - for(std::vector::iterator jt = poles.begin(); jt != poles.end(); ++jt){ + for (std::vector::iterator jt = poles.begin(); jt != poles.end(); + ++jt) { - (*jt) = (*jt) + 2.0*((*jt).Perpendicular(refGeoLine->getStartPoint(),vectline)-(*jt)); + (*jt) = (*jt) + + 2.0 + * ((*jt).Perpendicular(refGeoLine->getStartPoint(), vectline) - (*jt)); } geosymbsp->setPoles(poles); isStartEndInverted.insert(std::make_pair(*it, false)); } - else if(geosym->getTypeId() == Part::GeomPoint::getClassTypeId()){ - Part::GeomPoint *geosympoint = static_cast(geosym); + else if (geosym->getTypeId() == Part::GeomPoint::getClassTypeId()) { + Part::GeomPoint* geosympoint = static_cast(geosym); Base::Vector3d cp = geosympoint->getPoint(); - geosympoint->setPoint(cp+2.0*(cp.Perpendicular(refGeoLine->getStartPoint(),vectline)-cp)); + geosympoint->setPoint( + cp + 2.0 * (cp.Perpendicular(refGeoLine->getStartPoint(), vectline) - cp)); isStartEndInverted.insert(std::make_pair(*it, false)); } else { @@ -3875,93 +4188,112 @@ int SketchObject::addSymmetric(const std::vector &geoIdList, int refGeoId, cgeoid++; } } - else { //reference is a point + else {// reference is a point refIsAxisAligned = true; Vector3d refpoint; - const Part::Geometry *georef = getGeometry(refGeoId); + const Part::Geometry* georef = getGeometry(refGeoId); if (georef->getTypeId() == Part::GeomPoint::getClassTypeId()) { - refpoint = static_cast(georef)->getPoint(); + refpoint = static_cast(georef)->getPoint(); } - else if ( refGeoId == -1 && refPosId == Sketcher::PointPos::start) { - refpoint = Vector3d(0,0,0); + else if (refGeoId == -1 && refPosId == Sketcher::PointPos::start) { + refpoint = Vector3d(0, 0, 0); } else { - switch(refPosId){ + switch (refPosId) { case Sketcher::PointPos::start: - if(georef->getTypeId() == Part::GeomLineSegment::getClassTypeId()){ - const Part::GeomLineSegment *geosymline = static_cast(georef); + if (georef->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* geosymline = + static_cast(georef); refpoint = geosymline->getStartPoint(); } - else if(georef->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()){ - const Part::GeomArcOfCircle *geoaoc = static_cast(georef); + else if (georef->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* geoaoc = + static_cast(georef); refpoint = geoaoc->getStartPoint(true); } - else if(georef->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()){ - const Part::GeomArcOfEllipse *geosymaoe = static_cast(georef); + else if (georef->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { + const Part::GeomArcOfEllipse* geosymaoe = + static_cast(georef); refpoint = geosymaoe->getStartPoint(true); } - else if(georef->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()){ - const Part::GeomArcOfHyperbola *geosymaoe = static_cast(georef); + else if (georef->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + const Part::GeomArcOfHyperbola* geosymaoe = + static_cast(georef); refpoint = geosymaoe->getStartPoint(true); } - else if(georef->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()){ - const Part::GeomArcOfParabola *geosymaoe = static_cast(georef); + else if (georef->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + const Part::GeomArcOfParabola* geosymaoe = + static_cast(georef); refpoint = geosymaoe->getStartPoint(true); - } else if(georef->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()){ - const Part::GeomBSplineCurve *geosymbsp = static_cast(georef); + } + else if (georef->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { + const Part::GeomBSplineCurve* geosymbsp = + static_cast(georef); refpoint = geosymbsp->getStartPoint(); } break; case Sketcher::PointPos::end: - if(georef->getTypeId() == Part::GeomLineSegment::getClassTypeId()){ - const Part::GeomLineSegment *geosymline = static_cast(georef); + if (georef->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* geosymline = + static_cast(georef); refpoint = geosymline->getEndPoint(); } - else if(georef->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()){ - const Part::GeomArcOfCircle *geoaoc = static_cast(georef); + else if (georef->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* geoaoc = + static_cast(georef); refpoint = geoaoc->getEndPoint(true); } - else if(georef->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()){ - const Part::GeomArcOfEllipse *geosymaoe = static_cast(georef); + else if (georef->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { + const Part::GeomArcOfEllipse* geosymaoe = + static_cast(georef); refpoint = geosymaoe->getEndPoint(true); } - else if(georef->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()){ - const Part::GeomArcOfHyperbola *geosymaoe = static_cast(georef); + else if (georef->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + const Part::GeomArcOfHyperbola* geosymaoe = + static_cast(georef); refpoint = geosymaoe->getEndPoint(true); } - else if(georef->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()){ - const Part::GeomArcOfParabola *geosymaoe = static_cast(georef); + else if (georef->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + const Part::GeomArcOfParabola* geosymaoe = + static_cast(georef); refpoint = geosymaoe->getEndPoint(true); } - else if(georef->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()){ - const Part::GeomBSplineCurve *geosymbsp = static_cast(georef); + else if (georef->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { + const Part::GeomBSplineCurve* geosymbsp = + static_cast(georef); refpoint = geosymbsp->getEndPoint(); } break; case Sketcher::PointPos::mid: - if(georef->getTypeId() == Part::GeomCircle::getClassTypeId()){ - const Part::GeomCircle *geosymcircle = static_cast(georef); + if (georef->getTypeId() == Part::GeomCircle::getClassTypeId()) { + const Part::GeomCircle* geosymcircle = + static_cast(georef); refpoint = geosymcircle->getCenter(); } - else if(georef->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()){ - const Part::GeomArcOfCircle *geoaoc = static_cast(georef); + else if (georef->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* geoaoc = + static_cast(georef); refpoint = geoaoc->getCenter(); } - else if(georef->getTypeId() == Part::GeomEllipse::getClassTypeId()){ - const Part::GeomEllipse *geosymellipse = static_cast(georef); + else if (georef->getTypeId() == Part::GeomEllipse::getClassTypeId()) { + const Part::GeomEllipse* geosymellipse = + static_cast(georef); refpoint = geosymellipse->getCenter(); } - else if(georef->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()){ - const Part::GeomArcOfEllipse *geosymaoe = static_cast(georef); + else if (georef->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { + const Part::GeomArcOfEllipse* geosymaoe = + static_cast(georef); refpoint = geosymaoe->getCenter(); } - else if(georef->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()){ - const Part::GeomArcOfHyperbola *geosymaoe = static_cast(georef); + else if (georef->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + const Part::GeomArcOfHyperbola* geosymaoe = + static_cast(georef); refpoint = geosymaoe->getCenter(); } - else if(georef->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()){ - const Part::GeomArcOfParabola *geosymaoe = static_cast(georef); + else if (georef->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + const Part::GeomArcOfParabola* geosymaoe = + static_cast(georef); refpoint = geosymaoe->getCenter(); } break; @@ -3972,155 +4304,160 @@ int SketchObject::addSymmetric(const std::vector &geoIdList, int refGeoId, } for (std::vector::const_iterator it = geoIdList.begin(); it != geoIdList.end(); ++it) { - const Part::Geometry *geo = getGeometry(*it); + const Part::Geometry* geo = getGeometry(*it); - Part::Geometry *geosym; + Part::Geometry* geosym; auto gf = GeometryFacade::getFacade(geo); - if(gf->isInternalAligned()) { - // only add this geometry if the corresponding geometry it defines is also in the list. + if (gf->isInternalAligned()) { + // only add this geometry if the corresponding geometry it defines is also in the + // list. int definedGeo = GeoEnum::GeoUndef; - for( auto c : Constraints.getValues()) { - if(c->Type == Sketcher::InternalAlignment && c->First == *it) { + for (auto c : Constraints.getValues()) { + if (c->Type == Sketcher::InternalAlignment && c->First == *it) { definedGeo = c->Second; break; } } - if(std::find(geoIdList.begin(), geoIdList.end(), definedGeo) != geoIdList.end() ) + if (std::find(geoIdList.begin(), geoIdList.end(), definedGeo) != geoIdList.end()) geosym = geo->copy(); - else - continue; // we should not mirror internal alignment geometry, unless the element they define is also mirrored - + else { + // we should not mirror internal alignment geometry, unless the element they + // define is also mirrored + continue; + } } else { geosym = geo->copy(); } // Handle Geometry - if(geosym->getTypeId() == Part::GeomLineSegment::getClassTypeId()){ - Part::GeomLineSegment *geosymline = static_cast(geosym); + if (geosym->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + Part::GeomLineSegment* geosymline = static_cast(geosym); Base::Vector3d sp = geosymline->getStartPoint(); Base::Vector3d ep = geosymline->getEndPoint(); - Base::Vector3d ssp = sp + 2.0*(refpoint-sp); - Base::Vector3d sep = ep + 2.0*(refpoint-ep); + Base::Vector3d ssp = sp + 2.0 * (refpoint - sp); + Base::Vector3d sep = ep + 2.0 * (refpoint - ep); geosymline->setPoints(ssp, sep); isStartEndInverted.insert(std::make_pair(*it, false)); } - else if(geosym->getTypeId() == Part::GeomCircle::getClassTypeId()){ - Part::GeomCircle *geosymcircle = static_cast(geosym); + else if (geosym->getTypeId() == Part::GeomCircle::getClassTypeId()) { + Part::GeomCircle* geosymcircle = static_cast(geosym); Base::Vector3d cp = geosymcircle->getCenter(); - geosymcircle->setCenter(cp + 2.0*(refpoint-cp)); + geosymcircle->setCenter(cp + 2.0 * (refpoint - cp)); isStartEndInverted.insert(std::make_pair(*it, false)); } - else if(geosym->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()){ - Part::GeomArcOfCircle *geoaoc = static_cast(geosym); + else if (geosym->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + Part::GeomArcOfCircle* geoaoc = static_cast(geosym); Base::Vector3d sp = geoaoc->getStartPoint(true); Base::Vector3d ep = geoaoc->getEndPoint(true); Base::Vector3d cp = geoaoc->getCenter(); - Base::Vector3d ssp = sp + 2.0*(refpoint-sp); - Base::Vector3d sep = ep + 2.0*(refpoint-ep); - Base::Vector3d scp = cp + 2.0*(refpoint-cp); + Base::Vector3d ssp = sp + 2.0 * (refpoint - sp); + Base::Vector3d sep = ep + 2.0 * (refpoint - ep); + Base::Vector3d scp = cp + 2.0 * (refpoint - cp); - double theta1 = Base::fmod(atan2(ssp.y - scp.y, ssp.x - scp.x), 2.f*M_PI); - double theta2 = Base::fmod(atan2(sep.y - scp.y, sep.x - scp.x), 2.f*M_PI); + double theta1 = Base::fmod(atan2(ssp.y - scp.y, ssp.x - scp.x), 2.f * M_PI); + double theta2 = Base::fmod(atan2(sep.y - scp.y, sep.x - scp.x), 2.f * M_PI); geoaoc->setCenter(scp); - geoaoc->setRange(theta1,theta2,true); + geoaoc->setRange(theta1, theta2, true); isStartEndInverted.insert(std::make_pair(*it, false)); } - else if(geosym->getTypeId() == Part::GeomEllipse::getClassTypeId()){ - Part::GeomEllipse *geosymellipse = static_cast(geosym); + else if (geosym->getTypeId() == Part::GeomEllipse::getClassTypeId()) { + Part::GeomEllipse* geosymellipse = static_cast(geosym); Base::Vector3d cp = geosymellipse->getCenter(); Base::Vector3d majdir = geosymellipse->getMajorAxisDir(); - double majord=geosymellipse->getMajorRadius(); - double minord=geosymellipse->getMinorRadius(); - double df= sqrt(majord*majord-minord*minord); + double majord = geosymellipse->getMajorRadius(); + double minord = geosymellipse->getMinorRadius(); + double df = sqrt(majord * majord - minord * minord); Base::Vector3d f1 = cp + df * majdir; - Base::Vector3d sf1 = f1 + 2.0*(refpoint-f1); - Base::Vector3d scp = cp + 2.0*(refpoint-cp); + Base::Vector3d sf1 = f1 + 2.0 * (refpoint - f1); + Base::Vector3d scp = cp + 2.0 * (refpoint - cp); - geosymellipse->setMajorAxisDir(sf1-scp); + geosymellipse->setMajorAxisDir(sf1 - scp); geosymellipse->setCenter(scp); isStartEndInverted.insert(std::make_pair(*it, false)); } - else if(geosym->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()){ - Part::GeomArcOfEllipse *geosymaoe = static_cast(geosym); + else if (geosym->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { + Part::GeomArcOfEllipse* geosymaoe = static_cast(geosym); Base::Vector3d cp = geosymaoe->getCenter(); Base::Vector3d majdir = geosymaoe->getMajorAxisDir(); - double majord=geosymaoe->getMajorRadius(); - double minord=geosymaoe->getMinorRadius(); - double df= sqrt(majord*majord-minord*minord); + double majord = geosymaoe->getMajorRadius(); + double minord = geosymaoe->getMinorRadius(); + double df = sqrt(majord * majord - minord * minord); Base::Vector3d f1 = cp + df * majdir; - Base::Vector3d sf1 = f1 + 2.0*(refpoint-f1); - Base::Vector3d scp = cp + 2.0*(refpoint-cp); + Base::Vector3d sf1 = f1 + 2.0 * (refpoint - f1); + Base::Vector3d scp = cp + 2.0 * (refpoint - cp); - geosymaoe->setMajorAxisDir(sf1-scp); + geosymaoe->setMajorAxisDir(sf1 - scp); geosymaoe->setCenter(scp); isStartEndInverted.insert(std::make_pair(*it, false)); } - else if(geosym->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()){ - Part::GeomArcOfHyperbola *geosymaoe = static_cast(geosym); + else if (geosym->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + Part::GeomArcOfHyperbola* geosymaoe = + static_cast(geosym); Base::Vector3d cp = geosymaoe->getCenter(); Base::Vector3d majdir = geosymaoe->getMajorAxisDir(); - double majord=geosymaoe->getMajorRadius(); - double minord=geosymaoe->getMinorRadius(); - double df= sqrt(majord*majord+minord*minord); + double majord = geosymaoe->getMajorRadius(); + double minord = geosymaoe->getMinorRadius(); + double df = sqrt(majord * majord + minord * minord); Base::Vector3d f1 = cp + df * majdir; - Base::Vector3d sf1 = f1 + 2.0*(refpoint-f1); - Base::Vector3d scp = cp + 2.0*(refpoint-cp); + Base::Vector3d sf1 = f1 + 2.0 * (refpoint - f1); + Base::Vector3d scp = cp + 2.0 * (refpoint - cp); - geosymaoe->setMajorAxisDir(sf1-scp); + geosymaoe->setMajorAxisDir(sf1 - scp); geosymaoe->setCenter(scp); isStartEndInverted.insert(std::make_pair(*it, false)); } - else if(geosym->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()){ - Part::GeomArcOfParabola *geosymaoe = static_cast(geosym); + else if (geosym->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + Part::GeomArcOfParabola* geosymaoe = static_cast(geosym); Base::Vector3d cp = geosymaoe->getCenter(); /*double df= geosymaoe->getFocal();*/ Base::Vector3d f1 = geosymaoe->getFocus(); - Base::Vector3d sf1 = f1 + 2.0*(refpoint-f1); - Base::Vector3d scp = cp + 2.0*(refpoint-cp); + Base::Vector3d sf1 = f1 + 2.0 * (refpoint - f1); + Base::Vector3d scp = cp + 2.0 * (refpoint - cp); - geosymaoe->setXAxisDir(sf1-scp); + geosymaoe->setXAxisDir(sf1 - scp); geosymaoe->setCenter(scp); isStartEndInverted.insert(std::make_pair(*it, false)); } - else if(geosym->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()){ - Part::GeomBSplineCurve *geosymbsp = static_cast(geosym); + else if (geosym->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { + Part::GeomBSplineCurve* geosymbsp = static_cast(geosym); std::vector poles = geosymbsp->getPoles(); - for(std::vector::iterator it = poles.begin(); it != poles.end(); ++it){ - (*it) = (*it) + 2.0*(refpoint-(*it)); + for (std::vector::iterator it = poles.begin(); it != poles.end(); + ++it) { + (*it) = (*it) + 2.0 * (refpoint - (*it)); } geosymbsp->setPoles(poles); - //isStartEndInverted.insert(std::make_pair(*it, false)); + // isStartEndInverted.insert(std::make_pair(*it, false)); } - else if(geosym->getTypeId() == Part::GeomPoint::getClassTypeId()){ - Part::GeomPoint *geosympoint = static_cast(geosym); + else if (geosym->getTypeId() == Part::GeomPoint::getClassTypeId()) { + Part::GeomPoint* geosympoint = static_cast(geosym); Base::Vector3d cp = geosympoint->getPoint(); - geosympoint->setPoint(cp + 2.0*(refpoint-cp)); + geosympoint->setPoint(cp + 2.0 * (refpoint - cp)); isStartEndInverted.insert(std::make_pair(*it, false)); } else { @@ -4141,102 +4478,106 @@ int SketchObject::addSymmetric(const std::vector &geoIdList, int refGeoId, Base::StateLocker lock(internaltransaction, true); Geometry.setValues(std::move(newgeoVals)); - for (std::vector::const_iterator it = constrvals.begin(); it != constrvals.end(); ++it) { + for (std::vector::const_iterator it = constrvals.begin(); + it != constrvals.end(); + ++it) { + // we look in the map, because we might have skipped internal alignment geometry + auto fit = geoIdMap.find((*it)->First); - auto fit = geoIdMap.find((*it)->First); // we look in the map, because we might have skipped internal alignment geometry + if (fit != geoIdMap.end()) {// if First of constraint is in geoIdList - if(fit != geoIdMap.end()) { // if First of constraint is in geoIdList - - if( (*it)->Second == GeoEnum::GeoUndef /*&& (*it)->Third == GeoEnum::GeoUndef*/) { + if ((*it)->Second == GeoEnum::GeoUndef /*&& (*it)->Third == GeoEnum::GeoUndef*/) { if (refIsAxisAligned) { // in this case we want to keep the Vertical, Horizontal constraints - // DistanceX ,and DistanceY constraints should also be possible to keep in this case, - // but keeping them causes segfault, not sure why. + // DistanceX ,and DistanceY constraints should also be possible to keep in + // this case, but keeping them causes segfault, not sure why. - if( (*it)->Type != Sketcher::DistanceX && (*it)->Type != Sketcher::DistanceY ) { - Constraint *constNew = (*it)->copy(); + if ((*it)->Type != Sketcher::DistanceX + && (*it)->Type != Sketcher::DistanceY) { + Constraint* constNew = (*it)->copy(); constNew->First = fit->second; newconstrVals.push_back(constNew); } - - } else if( (*it)->Type != Sketcher::DistanceX && - (*it)->Type != Sketcher::DistanceY && - (*it)->Type != Sketcher::Vertical && - (*it)->Type != Sketcher::Horizontal ) { // this includes all non-directional single GeoId constraints, as radius, diameter, weight,... - - Constraint *constNew = (*it)->copy(); - constNew->First = fit->second; - newconstrVals.push_back(constNew); } + else if ((*it)->Type != Sketcher::DistanceX + && (*it)->Type != Sketcher::DistanceY + && (*it)->Type != Sketcher::Vertical + && (*it)->Type != Sketcher::Horizontal) { + // this includes all non-directional single GeoId constraints, as radius, + // diameter, weight,... + Constraint* constNew = (*it)->copy(); + constNew->First = fit->second; + newconstrVals.push_back(constNew); + } } - else { // other geoids intervene in this constraint + else {// other geoids intervene in this constraint auto sit = geoIdMap.find((*it)->Second); - if(sit != geoIdMap.end()) { // Second is also in the list + if (sit != geoIdMap.end()) {// Second is also in the list - if( (*it)->Third == GeoEnum::GeoUndef ) { - if((*it)->Type == Sketcher::Coincident || - (*it)->Type == Sketcher::Perpendicular || - (*it)->Type == Sketcher::Parallel || - (*it)->Type == Sketcher::Tangent || - (*it)->Type == Sketcher::Distance || - (*it)->Type == Sketcher::Equal || - (*it)->Type == Sketcher::Angle || - (*it)->Type == Sketcher::PointOnObject || - (*it)->Type == Sketcher::InternalAlignment ){ - Constraint *constNew = (*it)->copy(); + if ((*it)->Third == GeoEnum::GeoUndef) { + if ((*it)->Type == Sketcher::Coincident + || (*it)->Type == Sketcher::Perpendicular + || (*it)->Type == Sketcher::Parallel + || (*it)->Type == Sketcher::Tangent + || (*it)->Type == Sketcher::Distance + || (*it)->Type == Sketcher::Equal || (*it)->Type == Sketcher::Angle + || (*it)->Type == Sketcher::PointOnObject + || (*it)->Type == Sketcher::InternalAlignment) { + Constraint* constNew = (*it)->copy(); constNew->First = fit->second; constNew->Second = sit->second; - if(isStartEndInverted[(*it)->First]){ - if((*it)->FirstPos == Sketcher::PointPos::start) + if (isStartEndInverted[(*it)->First]) { + if ((*it)->FirstPos == Sketcher::PointPos::start) constNew->FirstPos = Sketcher::PointPos::end; - else if((*it)->FirstPos == Sketcher::PointPos::end) + else if ((*it)->FirstPos == Sketcher::PointPos::end) constNew->FirstPos = Sketcher::PointPos::start; } - if(isStartEndInverted[(*it)->Second]){ - if((*it)->SecondPos == Sketcher::PointPos::start) + if (isStartEndInverted[(*it)->Second]) { + if ((*it)->SecondPos == Sketcher::PointPos::start) constNew->SecondPos = Sketcher::PointPos::end; - else if((*it)->SecondPos == Sketcher::PointPos::end) + else if ((*it)->SecondPos == Sketcher::PointPos::end) constNew->SecondPos = Sketcher::PointPos::start; } if (constNew->Type == Tangent || constNew->Type == Perpendicular) - AutoLockTangencyAndPerpty(constNew,true); + AutoLockTangencyAndPerpty(constNew, true); - if( ((*it)->Type == Sketcher::Angle) && (refPosId == Sketcher::PointPos::none)) { + if (((*it)->Type == Sketcher::Angle) + && (refPosId == Sketcher::PointPos::none)) { constNew->setValue(-(*it)->getValue()); } newconstrVals.push_back(constNew); } } - else { // three GeoIds intervene in constraint + else {// three GeoIds intervene in constraint auto tit = geoIdMap.find((*it)->Third); - if(tit != geoIdMap.end()) { // Third is also in the list - Constraint *constNew = (*it)->copy(); + if (tit != geoIdMap.end()) {// Third is also in the list + Constraint* constNew = (*it)->copy(); constNew->First = fit->second; constNew->Second = sit->second; constNew->Third = tit->second; - if(isStartEndInverted[(*it)->First]){ - if((*it)->FirstPos == Sketcher::PointPos::start) + if (isStartEndInverted[(*it)->First]) { + if ((*it)->FirstPos == Sketcher::PointPos::start) constNew->FirstPos = Sketcher::PointPos::end; - else if((*it)->FirstPos == Sketcher::PointPos::end) + else if ((*it)->FirstPos == Sketcher::PointPos::end) constNew->FirstPos = Sketcher::PointPos::start; } - if(isStartEndInverted[(*it)->Second]){ - if((*it)->SecondPos == Sketcher::PointPos::start) + if (isStartEndInverted[(*it)->Second]) { + if ((*it)->SecondPos == Sketcher::PointPos::start) constNew->SecondPos = Sketcher::PointPos::end; - else if((*it)->SecondPos == Sketcher::PointPos::end) + else if ((*it)->SecondPos == Sketcher::PointPos::end) constNew->SecondPos = Sketcher::PointPos::start; } - if(isStartEndInverted[(*it)->Third]){ - if((*it)->ThirdPos == Sketcher::PointPos::start) + if (isStartEndInverted[(*it)->Third]) { + if ((*it)->ThirdPos == Sketcher::PointPos::start) constNew->ThirdPos = Sketcher::PointPos::end; - else if((*it)->ThirdPos == Sketcher::PointPos::end) + else if ((*it)->ThirdPos == Sketcher::PointPos::end) constNew->ThirdPos = Sketcher::PointPos::start; } newconstrVals.push_back(constNew); @@ -4247,44 +4588,46 @@ int SketchObject::addSymmetric(const std::vector &geoIdList, int refGeoId, } } - if( newconstrVals.size() > constrvals.size() ) - Constraints.setValues(std::move(newconstrVals)); - + if (newconstrVals.size() > constrvals.size()) + Constraints.setValues(std::move(newconstrVals)); } // we delayed update, so trigger it now. - // Update geometry indices and rebuild vertexindex now via onChanged, so that ViewProvider::UpdateData is triggered. + // Update geometry indices and rebuild vertexindex now via onChanged, so that + // ViewProvider::UpdateData is triggered. Geometry.touch(); - return Geometry.getSize()-1; + return Geometry.getSize() - 1; } -int SketchObject::addCopy(const std::vector &geoIdList, const Base::Vector3d& displacement, bool moveonly /*=false*/, - bool clone /*=false*/, int csize/*=2*/, int rsize/*=1*/, bool constraindisplacement /*= false*/, +int SketchObject::addCopy(const std::vector& geoIdList, const Base::Vector3d& displacement, + bool moveonly /*=false*/, bool clone /*=false*/, int csize /*=2*/, + int rsize /*=1*/, bool constraindisplacement /*= false*/, double perpscale /*= 1.0*/) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector< Part::Geometry * > &geovals = getInternalGeometry(); - std::vector< Part::Geometry * > newgeoVals(geovals); + const std::vector& geovals = getInternalGeometry(); + std::vector newgeoVals(geovals); - const std::vector< Constraint * > &constrvals = this->Constraints.getValues(); - std::vector< Constraint * > newconstrVals(constrvals); + const std::vector& constrvals = this->Constraints.getValues(); + std::vector newconstrVals(constrvals); - if(!moveonly) { - newgeoVals.reserve(geovals.size()+geoIdList.size()); + if (!moveonly) { + newgeoVals.reserve(geovals.size() + geoIdList.size()); } std::vector newgeoIdList(geoIdList); - if(newgeoIdList.empty()) {// default option to operate on all the geometry - for(int i = 0; i < int(geovals.size()); i++) + if (newgeoIdList.empty()) {// default option to operate on all the geometry + for (int i = 0; i < int(geovals.size()); i++) newgeoIdList.push_back(i); } - int cgeoid = getHighestCurveIndex()+1; + int cgeoid = getHighestCurveIndex() + 1; - int iterfirstgeoid = -1 ; + int iterfirstgeoid = -1; Base::Vector3d iterfirstpoint; @@ -4292,175 +4635,203 @@ int SketchObject::addCopy(const std::vector &geoIdList, const Base::Vector3 int colrefgeoid = 0, rowrefgeoid = 0; - int currentrowfirstgeoid= -1, prevrowstartfirstgeoid = -1, prevfirstgeoid = -1; + int currentrowfirstgeoid = -1, prevrowstartfirstgeoid = -1, prevfirstgeoid = -1; Sketcher::PointPos refposId = Sketcher::PointPos::none; std::map geoIdMap; - Base::Vector3d perpendicularDisplacement = Base::Vector3d(perpscale*displacement.y,perpscale*-displacement.x,0); + Base::Vector3d perpendicularDisplacement = + Base::Vector3d(perpscale * displacement.y, perpscale * -displacement.x, 0); - int x,y; + int x, y; - for (y=0;yisInternalAligned() && !moveonly) { - // only add this geometry if the corresponding geometry it defines is also in the list. + if (gf->isInternalAligned() && !moveonly) { + // only add this geometry if the corresponding geometry it defines is also in + // the list. int definedGeo = GeoEnum::GeoUndef; - for( auto c : Constraints.getValues()) { - if(c->Type == Sketcher::InternalAlignment && c->First == *(newgeoIdList.begin())) { + for (auto c : Constraints.getValues()) { + if (c->Type == Sketcher::InternalAlignment + && c->First == *(newgeoIdList.begin())) { definedGeo = c->Second; break; } } - if(std::find(newgeoIdList.begin(), newgeoIdList.end(), definedGeo) == newgeoIdList.end() ) { - // the first element setting the reference is an internal alignment geometry, wherein the geometry - // it defines is not part of the copy operation. - THROWM(Base::ValueError,"A move/copy/array operation on an internal alignment geometry is only possible together with the geometry it defines.") + if (std::find(newgeoIdList.begin(), newgeoIdList.end(), definedGeo) + == newgeoIdList.end()) { + // the first element setting the reference is an internal alignment + // geometry, wherein the geometry it defines is not part of the copy + // operation. + THROWM(Base::ValueError, + "A move/copy/array operation on an internal alignment geometry is " + "only possible together with the geometry it defines.") } } - refgeoid=*(newgeoIdList.begin()); + refgeoid = *(newgeoIdList.begin()); currentrowfirstgeoid = refgeoid; iterfirstgeoid = refgeoid; - if(geo->getTypeId() == Part::GeomCircle::getClassTypeId() || - geo->getTypeId() == Part::GeomEllipse::getClassTypeId() ){ + if (geo->getTypeId() == Part::GeomCircle::getClassTypeId() + || geo->getTypeId() == Part::GeomEllipse::getClassTypeId()) { refposId = Sketcher::PointPos::mid; } else refposId = Sketcher::PointPos::start; - continue; // the first element is already in place + continue;// the first element is already in place } else { prevfirstgeoid = iterfirstgeoid; iterfirstgeoid = cgeoid; - if( x == 0 ) { // if first element of second row + if (x == 0) {// if first element of second row prevrowstartfirstgeoid = currentrowfirstgeoid; currentrowfirstgeoid = cgeoid; } } int index = 0; - for (std::vector::const_iterator it = newgeoIdList.begin(); it != newgeoIdList.end(); ++it, index++) { - const Part::Geometry *geo = getGeometry(*it); + for (std::vector::const_iterator it = newgeoIdList.begin(); + it != newgeoIdList.end(); + ++it, index++) { + const Part::Geometry* geo = getGeometry(*it); - Part::Geometry *geocopy; + Part::Geometry* geocopy; auto gf = GeometryFacade::getFacade(geo); - if(gf->isInternalAligned() && !moveonly) { - // only add this geometry if the corresponding geometry it defines is also in the list. + if (gf->isInternalAligned() && !moveonly) { + // only add this geometry if the corresponding geometry it defines is also in + // the list. int definedGeo = GeoEnum::GeoUndef; - for( auto c : Constraints.getValues()) { - if(c->Type == Sketcher::InternalAlignment && c->First == *it) { + for (auto c : Constraints.getValues()) { + if (c->Type == Sketcher::InternalAlignment && c->First == *it) { definedGeo = c->Second; break; } } - if(std::find(newgeoIdList.begin(), newgeoIdList.end(), definedGeo) == newgeoIdList.end() ) - continue; // we should not copy internal alignment geometry, unless the element they define is also mirrored - + if (std::find(newgeoIdList.begin(), newgeoIdList.end(), definedGeo) + == newgeoIdList.end()) { + // we should not copy internal alignment geometry, unless the element they + // define is also mirrored + continue; + } } - // We have already cloned all geometry and constraints, we only need a copy if not moving - if(!moveonly) + // We have already cloned all geometry and constraints, we only need a copy if not + // moving + if (!moveonly) geocopy = geo->copy(); else geocopy = newgeoVals[*it]; // Handle Geometry - if(geocopy->getTypeId() == Part::GeomLineSegment::getClassTypeId()){ - Part::GeomLineSegment *geosymline = static_cast(geocopy); + if (geocopy->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + Part::GeomLineSegment* geosymline = + static_cast(geocopy); Base::Vector3d ep = geosymline->getEndPoint(); - Base::Vector3d ssp = geosymline->getStartPoint()+double(x)*displacement+double(y)*perpendicularDisplacement; + Base::Vector3d ssp = geosymline->getStartPoint() + double(x) * displacement + + double(y) * perpendicularDisplacement; - geosymline->setPoints( ssp, - ep+double(x)*displacement+double(y)*perpendicularDisplacement); + geosymline->setPoints( + ssp, ep + double(x) * displacement + double(y) * perpendicularDisplacement); - if(it == newgeoIdList.begin()) + if (it == newgeoIdList.begin()) iterfirstpoint = ssp; } - else if(geocopy->getTypeId() == Part::GeomCircle::getClassTypeId()){ - Part::GeomCircle *geosymcircle = static_cast(geocopy); + else if (geocopy->getTypeId() == Part::GeomCircle::getClassTypeId()) { + Part::GeomCircle* geosymcircle = static_cast(geocopy); Base::Vector3d cp = geosymcircle->getCenter(); - Base::Vector3d scp = cp+double(x)*displacement+double(y)*perpendicularDisplacement; + Base::Vector3d scp = + cp + double(x) * displacement + double(y) * perpendicularDisplacement; geosymcircle->setCenter(scp); - if(it == newgeoIdList.begin()) + if (it == newgeoIdList.begin()) iterfirstpoint = scp; } - else if(geocopy->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()){ - Part::GeomArcOfCircle *geoaoc = static_cast(geocopy); + else if (geocopy->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + Part::GeomArcOfCircle* geoaoc = static_cast(geocopy); Base::Vector3d cp = geoaoc->getCenter(); - Base::Vector3d scp = cp+double(x)*displacement+double(y)*perpendicularDisplacement; + Base::Vector3d scp = + cp + double(x) * displacement + double(y) * perpendicularDisplacement; geoaoc->setCenter(scp); - if(it == newgeoIdList.begin()) + if (it == newgeoIdList.begin()) iterfirstpoint = geoaoc->getStartPoint(true); } - else if(geocopy->getTypeId() == Part::GeomEllipse::getClassTypeId()){ - Part::GeomEllipse *geosymellipse = static_cast(geocopy); + else if (geocopy->getTypeId() == Part::GeomEllipse::getClassTypeId()) { + Part::GeomEllipse* geosymellipse = static_cast(geocopy); Base::Vector3d cp = geosymellipse->getCenter(); - Base::Vector3d scp = cp+double(x)*displacement+double(y)*perpendicularDisplacement; + Base::Vector3d scp = + cp + double(x) * displacement + double(y) * perpendicularDisplacement; geosymellipse->setCenter(scp); - if(it == newgeoIdList.begin()) + if (it == newgeoIdList.begin()) iterfirstpoint = scp; } - else if(geocopy->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()){ - Part::GeomArcOfEllipse *geoaoe = static_cast(geocopy); + else if (geocopy->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { + Part::GeomArcOfEllipse* geoaoe = static_cast(geocopy); Base::Vector3d cp = geoaoe->getCenter(); - Base::Vector3d scp = cp+double(x)*displacement+double(y)*perpendicularDisplacement; + Base::Vector3d scp = + cp + double(x) * displacement + double(y) * perpendicularDisplacement; geoaoe->setCenter(scp); - if(it == newgeoIdList.begin()) + if (it == newgeoIdList.begin()) iterfirstpoint = geoaoe->getStartPoint(true); } - else if(geocopy->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()){ - Part::GeomArcOfHyperbola *geoaoe = static_cast(geocopy); + else if (geocopy->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + Part::GeomArcOfHyperbola* geoaoe = + static_cast(geocopy); Base::Vector3d cp = geoaoe->getCenter(); - Base::Vector3d scp = cp+double(x)*displacement+double(y)*perpendicularDisplacement; + Base::Vector3d scp = + cp + double(x) * displacement + double(y) * perpendicularDisplacement; geoaoe->setCenter(scp); - if(it == newgeoIdList.begin()) + if (it == newgeoIdList.begin()) iterfirstpoint = geoaoe->getStartPoint(true); } - else if(geocopy->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()){ - Part::GeomArcOfParabola *geoaoe = static_cast(geocopy); + else if (geocopy->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + Part::GeomArcOfParabola* geoaoe = + static_cast(geocopy); Base::Vector3d cp = geoaoe->getCenter(); - Base::Vector3d scp = cp+double(x)*displacement+double(y)*perpendicularDisplacement; + Base::Vector3d scp = + cp + double(x) * displacement + double(y) * perpendicularDisplacement; geoaoe->setCenter(scp); - if(it == newgeoIdList.begin()) + if (it == newgeoIdList.begin()) iterfirstpoint = geoaoe->getStartPoint(true); } - else if(geocopy->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()){ - Part::GeomBSplineCurve *geobsp = static_cast(geocopy); + else if (geocopy->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { + Part::GeomBSplineCurve* geobsp = static_cast(geocopy); std::vector poles = geobsp->getPoles(); - for(std::vector::iterator jt = poles.begin(); jt != poles.end(); ++jt){ + for (std::vector::iterator jt = poles.begin(); + jt != poles.end(); + ++jt) { - (*jt) = (*jt) + double(x)*displacement + double(y)*perpendicularDisplacement; + (*jt) = (*jt) + double(x) * displacement + + double(y) * perpendicularDisplacement; } geobsp->setPoles(poles); @@ -4468,13 +4839,14 @@ int SketchObject::addCopy(const std::vector &geoIdList, const Base::Vector3 if (it == newgeoIdList.begin()) iterfirstpoint = geobsp->getStartPoint(); } - else if(geocopy->getTypeId() == Part::GeomPoint::getClassTypeId()){ - Part::GeomPoint *geopoint = static_cast(geocopy); + else if (geocopy->getTypeId() == Part::GeomPoint::getClassTypeId()) { + Part::GeomPoint* geopoint = static_cast(geocopy); Base::Vector3d cp = geopoint->getPoint(); - Base::Vector3d scp = cp+double(x)*displacement+double(y)*perpendicularDisplacement; + Base::Vector3d scp = + cp + double(x) * displacement + double(y) * perpendicularDisplacement; geopoint->setPoint(scp); - if(it == newgeoIdList.begin()) + if (it == newgeoIdList.begin()) iterfirstpoint = scp; } else { @@ -4482,74 +4854,89 @@ int SketchObject::addCopy(const std::vector &geoIdList, const Base::Vector3 continue; } - if(!moveonly) { // we are copying + if (!moveonly) {// we are copying newgeoVals.push_back(geocopy); geoIdMap.insert(std::make_pair(*it, cgeoid)); cgeoid++; } } - if(!moveonly) { + if (!moveonly) { // handle geometry constraints - for (std::vector::const_iterator it = constrvals.begin(); it != constrvals.end(); ++it) { + for (std::vector::const_iterator it = constrvals.begin(); + it != constrvals.end(); + ++it) { auto fit = geoIdMap.find((*it)->First); - if(fit != geoIdMap.end()) { // if First of constraint is in geoIdList + if (fit != geoIdMap.end()) {// if First of constraint is in geoIdList - if( (*it)->Second == GeoEnum::GeoUndef /*&& (*it)->Third == GeoEnum::GeoUndef*/) { - if( ((*it)->Type != Sketcher::DistanceX && (*it)->Type != Sketcher::DistanceY ) || - (*it)->FirstPos == Sketcher::PointPos::none ) { // if it is not a point locking DistanceX/Y - if (((*it)->Type == Sketcher::DistanceX || - (*it)->Type == Sketcher::DistanceY || - (*it)->Type == Sketcher::Distance || - (*it)->Type == Sketcher::Diameter || - (*it)->Type == Sketcher::Weight || - (*it)->Type == Sketcher::Radius ) && clone ) { - // Distances on a single Element are mapped to equality constraints in clone mode - Constraint *constNew = (*it)->copy(); - constNew->Type = Sketcher::Equal; + if ((*it)->Second + == GeoEnum::GeoUndef /*&& (*it)->Third == GeoEnum::GeoUndef*/) { + if (((*it)->Type != Sketcher::DistanceX + && (*it)->Type != Sketcher::DistanceY) + || (*it)->FirstPos == Sketcher::PointPos::none) { + // if it is not a point locking DistanceX/Y + if (((*it)->Type == Sketcher::DistanceX + || (*it)->Type == Sketcher::DistanceY + || (*it)->Type == Sketcher::Distance + || (*it)->Type == Sketcher::Diameter + || (*it)->Type == Sketcher::Weight + || (*it)->Type == Sketcher::Radius) + && clone) { + // Distances on a single Element are mapped to equality + // constraints in clone mode + Constraint* constNew = (*it)->copy(); + constNew->Type = Sketcher::Equal; + constNew->isDriving = true; + // first is already (*it->First) + constNew->Second = fit->second; + newconstrVals.push_back(constNew); + } + else if ((*it)->Type == Sketcher::Angle && clone) { + if (getGeometry((*it)->First)->getTypeId() + == Part::GeomLineSegment::getClassTypeId()) { + // Angles on a single Element are mapped to parallel + // constraints in clone mode + Constraint* constNew = (*it)->copy(); + constNew->Type = Sketcher::Parallel; constNew->isDriving = true; - constNew->Second = fit->second; // first is already (*it->First) - newconstrVals.push_back(constNew); - } - else if ((*it)->Type == Sketcher::Angle && clone) { - if (getGeometry((*it)->First)->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - // Angles on a single Element are mapped to parallel constraints in clone mode - Constraint *constNew = (*it)->copy(); - constNew->Type = Sketcher::Parallel; - constNew->isDriving = true; - constNew->Second = fit->second; // first is already (*it->First) - newconstrVals.push_back(constNew); - } - } - else { - Constraint *constNew = (*it)->copy(); - constNew->First = fit->second; + // first is already (*it->First) + constNew->Second = fit->second; newconstrVals.push_back(constNew); } + } + else { + Constraint* constNew = (*it)->copy(); + constNew->First = fit->second; + newconstrVals.push_back(constNew); + } } } - else { // other geoids intervene in this constraint + else {// other geoids intervene in this constraint auto sit = geoIdMap.find((*it)->Second); - if(sit != geoIdMap.end()) { // Second is also in the list - if( (*it)->Third == GeoEnum::GeoUndef ) { - if (((*it)->Type == Sketcher::DistanceX || - (*it)->Type == Sketcher::DistanceY || - (*it)->Type == Sketcher::Distance) && ((*it)->First == (*it)->Second) && clone ) { - // Distances on a two Elements, which must be points of the same line are mapped to equality constraints in clone mode - Constraint *constNew = (*it)->copy(); + if (sit != geoIdMap.end()) {// Second is also in the list + if ((*it)->Third == GeoEnum::GeoUndef) { + if (((*it)->Type == Sketcher::DistanceX + || (*it)->Type == Sketcher::DistanceY + || (*it)->Type == Sketcher::Distance) + && ((*it)->First == (*it)->Second) && clone) { + // Distances on a two Elements, which must be points of the + // same line are mapped to equality constraints in clone + // mode + Constraint* constNew = (*it)->copy(); constNew->Type = Sketcher::Equal; constNew->isDriving = true; constNew->FirstPos = Sketcher::PointPos::none; - constNew->Second = fit->second; // first is already (*it->First) + // first is already (*it->First) + constNew->Second = fit->second; constNew->SecondPos = Sketcher::PointPos::none; newconstrVals.push_back(constNew); } - else { // this includes InternalAlignment constraints - Constraint *constNew = (*it)->copy(); + else {// this includes InternalAlignment constraints + Constraint* constNew = (*it)->copy(); constNew->First = fit->second; constNew->Second = sit->second; newconstrVals.push_back(constNew); @@ -4558,8 +4945,8 @@ int SketchObject::addCopy(const std::vector &geoIdList, const Base::Vector3 else { auto tit = geoIdMap.find((*it)->Third); - if(tit != geoIdMap.end()) { // Third is also in the list - Constraint *constNew = (*it)->copy(); + if (tit != geoIdMap.end()) {// Third is also in the list + Constraint* constNew = (*it)->copy(); constNew->First = fit->second; constNew->Second = sit->second; constNew->Third = tit->second; @@ -4573,23 +4960,28 @@ int SketchObject::addCopy(const std::vector &geoIdList, const Base::Vector3 } // handle inter-geometry constraints - if(constraindisplacement){ + if (constraindisplacement) { // add a construction line - Part::GeomLineSegment *constrline= new Part::GeomLineSegment(); + Part::GeomLineSegment* constrline = new Part::GeomLineSegment(); - Base::Vector3d sp = getPoint(refgeoid,refposId)+ ( ( x == 0 )? - (double(x)*displacement+double(y-1)*perpendicularDisplacement): - (double(x-1)*displacement+double(y)*perpendicularDisplacement)); // position of the reference point - Base::Vector3d ep = iterfirstpoint; // position of the current instance corresponding point - constrline->setPoints(sp,ep); - GeometryFacade::setConstruction(constrline,true); + // position of the reference point + Base::Vector3d sp = getPoint(refgeoid, refposId) + + ((x == 0) ? (double(x) * displacement + + double(y - 1) * perpendicularDisplacement) + : (double(x - 1) * displacement + + double(y) * perpendicularDisplacement)); + + // position of the current instance corresponding point + Base::Vector3d ep = iterfirstpoint; + constrline->setPoints(sp, ep); + GeometryFacade::setConstruction(constrline, true); newgeoVals.push_back(constrline); - Constraint *constNew; + Constraint* constNew; - if(x == 0) { // first element of a row + if (x == 0) {// first element of a row // add coincidents for construction line constNew = new Constraint(); @@ -4608,12 +5000,14 @@ int SketchObject::addCopy(const std::vector &geoIdList, const Base::Vector3 constNew->SecondPos = Sketcher::PointPos::end; newconstrVals.push_back(constNew); - if( y == 1 ) { // it is the first added element of this row in the perpendicular to displacementvector direction + // it is the first added element of this row in the perpendicular to + // displacementvector direction + if (y == 1) { rowrefgeoid = cgeoid; cgeoid++; // add length (or equal if perpscale==1) and perpendicular - if(perpscale==1.0) { + if (perpscale == 1.0) { constNew = new Constraint(); constNew->Type = Sketcher::Equal; constNew->First = rowrefgeoid; @@ -4621,7 +5015,8 @@ int SketchObject::addCopy(const std::vector &geoIdList, const Base::Vector3 constNew->Second = colrefgeoid; constNew->SecondPos = Sketcher::PointPos::none; newconstrVals.push_back(constNew); - } else { + } + else { constNew = new Constraint(); constNew->Type = Sketcher::Distance; constNew->First = rowrefgeoid; @@ -4638,7 +5033,7 @@ int SketchObject::addCopy(const std::vector &geoIdList, const Base::Vector3 constNew->SecondPos = Sketcher::PointPos::none; newconstrVals.push_back(constNew); } - else { // it is just one more element in the col direction + else {// it is just one more element in the col direction cgeoid++; // all other first rowers get an equality and perpendicular constraint @@ -4646,20 +5041,20 @@ int SketchObject::addCopy(const std::vector &geoIdList, const Base::Vector3 constNew->Type = Sketcher::Equal; constNew->First = rowrefgeoid; constNew->FirstPos = Sketcher::PointPos::none; - constNew->Second = cgeoid-1; + constNew->Second = cgeoid - 1; constNew->SecondPos = Sketcher::PointPos::none; newconstrVals.push_back(constNew); constNew = new Constraint(); constNew->Type = Sketcher::Perpendicular; - constNew->First = cgeoid-1; + constNew->First = cgeoid - 1; constNew->FirstPos = Sketcher::PointPos::none; constNew->Second = colrefgeoid; constNew->SecondPos = Sketcher::PointPos::none; newconstrVals.push_back(constNew); } } - else { // any element not being the first element of a row + else {// any element not being the first element of a row // add coincidents for construction line constNew = new Constraint(); @@ -4678,26 +5073,26 @@ int SketchObject::addCopy(const std::vector &geoIdList, const Base::Vector3 constNew->SecondPos = Sketcher::PointPos::end; newconstrVals.push_back(constNew); - if(y == 0 && x == 1) { // first element of the first row - colrefgeoid = cgeoid; - cgeoid++; + if (y == 0 && x == 1) {// first element of the first row + colrefgeoid = cgeoid; + cgeoid++; - // add length and Angle - constNew = new Constraint(); - constNew->Type = Sketcher::Distance; - constNew->First = colrefgeoid; - constNew->FirstPos = Sketcher::PointPos::none; - constNew->setValue(displacement.Length()); - newconstrVals.push_back(constNew); + // add length and Angle + constNew = new Constraint(); + constNew->Type = Sketcher::Distance; + constNew->First = colrefgeoid; + constNew->FirstPos = Sketcher::PointPos::none; + constNew->setValue(displacement.Length()); + newconstrVals.push_back(constNew); - constNew = new Constraint(); - constNew->Type = Sketcher::Angle; - constNew->First = colrefgeoid; - constNew->FirstPos = Sketcher::PointPos::none; - constNew->setValue(atan2(displacement.y,displacement.x)); - newconstrVals.push_back(constNew); + constNew = new Constraint(); + constNew->Type = Sketcher::Angle; + constNew->First = colrefgeoid; + constNew->FirstPos = Sketcher::PointPos::none; + constNew->setValue(atan2(displacement.y, displacement.x)); + newconstrVals.push_back(constNew); } - else { // any other element + else {// any other element cgeoid++; // all other elements get an equality and parallel constraint @@ -4705,13 +5100,13 @@ int SketchObject::addCopy(const std::vector &geoIdList, const Base::Vector3 constNew->Type = Sketcher::Equal; constNew->First = colrefgeoid; constNew->FirstPos = Sketcher::PointPos::none; - constNew->Second = cgeoid-1; + constNew->Second = cgeoid - 1; constNew->SecondPos = Sketcher::PointPos::none; newconstrVals.push_back(constNew); constNew = new Constraint(); constNew->Type = Sketcher::Parallel; - constNew->First = cgeoid-1; + constNew->First = cgeoid - 1; constNew->FirstPos = Sketcher::PointPos::none; constNew->Second = colrefgeoid; constNew->SecondPos = Sketcher::PointPos::none; @@ -4719,8 +5114,9 @@ int SketchObject::addCopy(const std::vector &geoIdList, const Base::Vector3 } } } - - geoIdMap.clear(); // after each creation reset map so that the key-value is univoque (only for operations other than move) + // after each creation reset map so that the key-value is univoque (only for + // operations other than move) + geoIdMap.clear(); } } } @@ -4730,24 +5126,25 @@ int SketchObject::addCopy(const std::vector &geoIdList, const Base::Vector3 Base::StateLocker lock(internaltransaction, true); Geometry.setValues(std::move(newgeoVals)); - if( newconstrVals.size() > constrvals.size() ) + if (newconstrVals.size() > constrvals.size()) Constraints.setValues(std::move(newconstrVals)); } // we inhibited update, so we trigger it now - // Update geometry indices and rebuild vertexindex now via onChanged, so that ViewProvider::UpdateData is triggered. + // Update geometry indices and rebuild vertexindex now via onChanged, so that + // ViewProvider::UpdateData is triggered. Geometry.touch(); - return Geometry.getSize()-1; - + return Geometry.getSize() - 1; } -int SketchObject::removeAxesAlignment(const std::vector &geoIdList) +int SketchObject::removeAxesAlignment(const std::vector& geoIdList) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector< Constraint * > &constrvals = this->Constraints.getValues(); + const std::vector& constrvals = this->Constraints.getValues(); unsigned int nhoriz = 0; unsigned int nvert = 0; @@ -4757,31 +5154,34 @@ int SketchObject::removeAxesAlignment(const std::vector &geoIdList) std::vector> changeConstraintIndices; for (size_t i = 0; i < constrvals.size(); i++) { - for( auto geoid : geoIdList) { - if (constrvals[i]->First == geoid || constrvals[i]->Second == geoid || constrvals[i]->Third == geoid) { - switch(constrvals[i]->Type) { + for (auto geoid : geoIdList) { + if (constrvals[i]->First == geoid || constrvals[i]->Second == geoid + || constrvals[i]->Third == geoid) { + switch (constrvals[i]->Type) { case Sketcher::Horizontal: - if( constrvals[i]->FirstPos == Sketcher::PointPos::none && - constrvals[i]->SecondPos == Sketcher::PointPos::none ) { + if (constrvals[i]->FirstPos == Sketcher::PointPos::none + && constrvals[i]->SecondPos == Sketcher::PointPos::none) { changeConstraintIndices.emplace_back(i, constrvals[i]->Type); nhoriz++; - } + } break; case Sketcher::Vertical: - if( constrvals[i]->FirstPos == Sketcher::PointPos::none && - constrvals[i]->SecondPos == Sketcher::PointPos::none ) { + if (constrvals[i]->FirstPos == Sketcher::PointPos::none + && constrvals[i]->SecondPos == Sketcher::PointPos::none) { changeConstraintIndices.emplace_back(i, constrvals[i]->Type); nvert++; - } + } break; - case Sketcher::Symmetric: // only remove symmetric to axes - if( (constrvals[i]->Third == GeoEnum::HAxis || constrvals[i]->Third == GeoEnum::VAxis) && - constrvals[i]->ThirdPos == Sketcher::PointPos::none ) + case Sketcher::Symmetric:// only remove symmetric to axes + if ((constrvals[i]->Third == GeoEnum::HAxis + || constrvals[i]->Third == GeoEnum::VAxis) + && constrvals[i]->ThirdPos == Sketcher::PointPos::none) changeConstraintIndices.emplace_back(i, constrvals[i]->Type); break; case Sketcher::PointOnObject: - if( (constrvals[i]->Second == GeoEnum::HAxis || constrvals[i]->Second == GeoEnum::VAxis) && - constrvals[i]->SecondPos == Sketcher::PointPos::none ) + if ((constrvals[i]->Second == GeoEnum::HAxis + || constrvals[i]->Second == GeoEnum::VAxis) + && constrvals[i]->SecondPos == Sketcher::PointPos::none) changeConstraintIndices.emplace_back(i, constrvals[i]->Type); break; case Sketcher::DistanceX: @@ -4795,10 +5195,10 @@ int SketchObject::removeAxesAlignment(const std::vector &geoIdList) } } - if(changeConstraintIndices.empty()) - return 0; // nothing to be done + if (changeConstraintIndices.empty()) + return 0;// nothing to be done - std::vector< Constraint * > newconstrVals; + std::vector newconstrVals; newconstrVals.reserve(constrvals.size()); int referenceHorizontal = GeoEnum::GeoUndef; @@ -4806,10 +5206,10 @@ int SketchObject::removeAxesAlignment(const std::vector &geoIdList) int cindex = 0; for (size_t i = 0; i < constrvals.size(); i++) { - if ( i == changeConstraintIndices[cindex].first ) { - if(changeConstraintIndices[cindex].second == Sketcher::Horizontal && nhoriz > 0) { + if (i == changeConstraintIndices[cindex].first) { + if (changeConstraintIndices[cindex].second == Sketcher::Horizontal && nhoriz > 0) { changed = true; - if(referenceHorizontal == GeoEnum::GeoUndef) { + if (referenceHorizontal == GeoEnum::GeoUndef) { referenceHorizontal = constrvals[i]->First; } else { @@ -4823,10 +5223,11 @@ int SketchObject::removeAxesAlignment(const std::vector &geoIdList) newconstrVals.push_back(newConstr); } } - else if(changeConstraintIndices[cindex].second == Sketcher::Vertical && nvert > 0) { + else if (changeConstraintIndices[cindex].second == Sketcher::Vertical && nvert > 0) { changed = true; - if(referenceVertical == GeoEnum::GeoUndef) { - referenceVertical = constrvals[i]->First;; + if (referenceVertical == GeoEnum::GeoUndef) { + referenceVertical = constrvals[i]->First; + ; } else { auto newConstr = new Constraint(); @@ -4838,13 +5239,13 @@ int SketchObject::removeAxesAlignment(const std::vector &geoIdList) newconstrVals.push_back(newConstr); } } - else if(changeConstraintIndices[cindex].second == Sketcher::Symmetric || - changeConstraintIndices[cindex].second == Sketcher::PointOnObject) { - changed = true; // We remove symmetric on axes + else if (changeConstraintIndices[cindex].second == Sketcher::Symmetric + || changeConstraintIndices[cindex].second == Sketcher::PointOnObject) { + changed = true;// We remove symmetric on axes } - else if(changeConstraintIndices[cindex].second == Sketcher::DistanceX || - changeConstraintIndices[cindex].second == Sketcher::DistanceY) { - changed = true; // We remove symmetric on axes + else if (changeConstraintIndices[cindex].second == Sketcher::DistanceX + || changeConstraintIndices[cindex].second == Sketcher::DistanceY) { + changed = true;// We remove symmetric on axes newconstrVals.push_back(constrvals[i]->clone()); newconstrVals.back()->Type = Sketcher::Distance; } @@ -4856,7 +5257,7 @@ int SketchObject::removeAxesAlignment(const std::vector &geoIdList) } } - if( nhoriz > 0 && nvert > 0 ) { + if (nhoriz > 0 && nvert > 0) { auto newConstr = new Constraint(); newConstr->Type = Sketcher::Perpendicular; @@ -4866,11 +5267,10 @@ int SketchObject::removeAxesAlignment(const std::vector &geoIdList) newconstrVals.push_back(newConstr); } - if(changed) + if (changed) Constraints.setValues(std::move(newconstrVals)); return 0; - } int SketchObject::exposeInternalGeometry(int GeoId) @@ -4878,33 +5278,33 @@ int SketchObject::exposeInternalGeometry(int GeoId) if (GeoId < 0 || GeoId > getHighestCurveIndex()) return -1; - const Part::Geometry *geo = getGeometry(GeoId); + const Part::Geometry* geo = getGeometry(GeoId); // Only for supported types - if(geo->getTypeId() == Part::GeomEllipse::getClassTypeId() || geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { + if (geo->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { // First we search what has to be restored - bool major=false; - bool minor=false; - bool focus1=false; - bool focus2=false; + bool major = false; + bool minor = false; + bool focus1 = false; + bool focus2 = false; - const std::vector< Sketcher::Constraint * > &vals = Constraints.getValues(); + const std::vector& vals = Constraints.getValues(); - for (std::vector< Sketcher::Constraint * >::const_iterator it= vals.begin(); - it != vals.end(); ++it) { - if((*it)->Type == Sketcher::InternalAlignment && (*it)->Second == GeoId) - { - switch((*it)->AlignmentType){ + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); + ++it) { + if ((*it)->Type == Sketcher::InternalAlignment && (*it)->Second == GeoId) { + switch ((*it)->AlignmentType) { case Sketcher::EllipseMajorDiameter: - major=true; + major = true; break; case Sketcher::EllipseMinorDiameter: - minor=true; + minor = true; break; case Sketcher::EllipseFocus1: - focus1=true; + focus1 = true; break; case Sketcher::EllipseFocus2: - focus2=true; + focus2 = true; break; default: return -1; @@ -4912,32 +5312,32 @@ int SketchObject::exposeInternalGeometry(int GeoId) } } - int currentgeoid= getHighestCurveIndex(); - int incrgeo= 0; + int currentgeoid = getHighestCurveIndex(); + int incrgeo = 0; Base::Vector3d center; double majord; double minord; Base::Vector3d majdir; - std::vector igeo; - std::vector icon; + std::vector igeo; + std::vector icon; - if(geo->getTypeId() == Part::GeomEllipse::getClassTypeId()){ - const Part::GeomEllipse *ellipse = static_cast(geo); + if (geo->getTypeId() == Part::GeomEllipse::getClassTypeId()) { + const Part::GeomEllipse* ellipse = static_cast(geo); - center=ellipse->getCenter(); - majord=ellipse->getMajorRadius(); - minord=ellipse->getMinorRadius(); - majdir=ellipse->getMajorAxisDir(); + center = ellipse->getCenter(); + majord = ellipse->getMajorRadius(); + minord = ellipse->getMinorRadius(); + majdir = ellipse->getMajorAxisDir(); } else { - const Part::GeomArcOfEllipse *aoe = static_cast(geo); + const Part::GeomArcOfEllipse* aoe = static_cast(geo); - center=aoe->getCenter(); - majord=aoe->getMajorRadius(); - minord=aoe->getMinorRadius(); - majdir=aoe->getMajorAxisDir(); + center = aoe->getCenter(); + majord = aoe->getMajorRadius(); + minord = aoe->getMinorRadius(); + majdir = aoe->getMajorAxisDir(); } Base::Vector3d mindir = Vector3d(-majdir.y, majdir.x); @@ -4947,85 +5347,81 @@ int SketchObject::exposeInternalGeometry(int GeoId) Base::Vector3d minorpositiveend = center + minord * mindir; Base::Vector3d minornegativeend = center - minord * mindir; - double df= sqrt(majord*majord-minord*minord); + double df = sqrt(majord * majord - minord * minord); Base::Vector3d focus1P = center + df * majdir; Base::Vector3d focus2P = center - df * majdir; - if(!major) - { - Part::GeomLineSegment *lmajor = new Part::GeomLineSegment(); - lmajor->setPoints(majorpositiveend,majornegativeend); + if (!major) { + Part::GeomLineSegment* lmajor = new Part::GeomLineSegment(); + lmajor->setPoints(majorpositiveend, majornegativeend); igeo.push_back(lmajor); - Sketcher::Constraint *newConstr = new Sketcher::Constraint(); + Sketcher::Constraint* newConstr = new Sketcher::Constraint(); newConstr->Type = Sketcher::InternalAlignment; newConstr->AlignmentType = EllipseMajorDiameter; - newConstr->First = currentgeoid+incrgeo+1; + newConstr->First = currentgeoid + incrgeo + 1; newConstr->Second = GeoId; icon.push_back(newConstr); incrgeo++; } - if(!minor) - { - Part::GeomLineSegment *lminor = new Part::GeomLineSegment(); - lminor->setPoints(minorpositiveend,minornegativeend); + if (!minor) { + Part::GeomLineSegment* lminor = new Part::GeomLineSegment(); + lminor->setPoints(minorpositiveend, minornegativeend); igeo.push_back(lminor); - Sketcher::Constraint *newConstr = new Sketcher::Constraint(); + Sketcher::Constraint* newConstr = new Sketcher::Constraint(); newConstr->Type = Sketcher::InternalAlignment; newConstr->AlignmentType = EllipseMinorDiameter; - newConstr->First = currentgeoid+incrgeo+1; + newConstr->First = currentgeoid + incrgeo + 1; newConstr->Second = GeoId; icon.push_back(newConstr); incrgeo++; } - if(!focus1) - { - Part::GeomPoint *pf1 = new Part::GeomPoint(); + if (!focus1) { + Part::GeomPoint* pf1 = new Part::GeomPoint(); pf1->setPoint(focus1P); igeo.push_back(pf1); - Sketcher::Constraint *newConstr = new Sketcher::Constraint(); + Sketcher::Constraint* newConstr = new Sketcher::Constraint(); newConstr->Type = Sketcher::InternalAlignment; newConstr->AlignmentType = EllipseFocus1; - newConstr->First = currentgeoid+incrgeo+1; + newConstr->First = currentgeoid + incrgeo + 1; newConstr->FirstPos = Sketcher::PointPos::start; newConstr->Second = GeoId; icon.push_back(newConstr); incrgeo++; } - if(!focus2) - { - Part::GeomPoint *pf2 = new Part::GeomPoint(); + if (!focus2) { + Part::GeomPoint* pf2 = new Part::GeomPoint(); pf2->setPoint(focus2P); igeo.push_back(pf2); - Sketcher::Constraint *newConstr = new Sketcher::Constraint(); + Sketcher::Constraint* newConstr = new Sketcher::Constraint(); newConstr->Type = Sketcher::InternalAlignment; newConstr->AlignmentType = EllipseFocus2; - newConstr->First = currentgeoid+incrgeo+1; + newConstr->First = currentgeoid + incrgeo + 1; newConstr->FirstPos = Sketcher::PointPos::start; newConstr->Second = GeoId; icon.push_back(newConstr); } - this->addGeometry(igeo,true); + this->addGeometry(igeo, true); this->addConstraints(icon); - for (std::vector::iterator it=igeo.begin(); it != igeo.end(); ++it) { + for (std::vector::iterator it = igeo.begin(); it != igeo.end(); ++it) { if (*it) delete *it; } - for (std::vector::iterator it=icon.begin(); it != icon.end(); ++it) { + for (std::vector::iterator it = icon.begin(); it != icon.end(); ++it) { if (*it) delete *it; } @@ -5033,29 +5429,28 @@ int SketchObject::exposeInternalGeometry(int GeoId) icon.clear(); igeo.clear(); - return incrgeo; //number of added elements + return incrgeo;// number of added elements } - else if(geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + else if (geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { // First we search what has to be restored - bool major=false; - bool minor=false; - bool focus=false; + bool major = false; + bool minor = false; + bool focus = false; - const std::vector< Sketcher::Constraint * > &vals = Constraints.getValues(); + const std::vector& vals = Constraints.getValues(); - for (std::vector< Sketcher::Constraint * >::const_iterator it= vals.begin(); - it != vals.end(); ++it) { - if((*it)->Type == Sketcher::InternalAlignment && (*it)->Second == GeoId) - { - switch((*it)->AlignmentType){ + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); + ++it) { + if ((*it)->Type == Sketcher::InternalAlignment && (*it)->Second == GeoId) { + switch ((*it)->AlignmentType) { case Sketcher::HyperbolaMajor: - major=true; + major = true; break; case Sketcher::HyperbolaMinor: - minor=true; + minor = true; break; case Sketcher::HyperbolaFocus: - focus=true; + focus = true; break; default: return -1; @@ -5063,18 +5458,18 @@ int SketchObject::exposeInternalGeometry(int GeoId) } } - int currentgeoid= getHighestCurveIndex(); - int incrgeo= 0; + int currentgeoid = getHighestCurveIndex(); + int incrgeo = 0; - const Part::GeomArcOfHyperbola *aoh = static_cast(geo); + const Part::GeomArcOfHyperbola* aoh = static_cast(geo); Base::Vector3d center = aoh->getCenter(); double majord = aoh->getMajorRadius(); double minord = aoh->getMinorRadius(); Base::Vector3d majdir = aoh->getMajorAxisDir(); - std::vector igeo; - std::vector icon; + std::vector igeo; + std::vector icon; Base::Vector3d mindir = Vector3d(-majdir.y, majdir.x); @@ -5083,54 +5478,51 @@ int SketchObject::exposeInternalGeometry(int GeoId) Base::Vector3d minorpositiveend = majorpositiveend + minord * mindir; Base::Vector3d minornegativeend = majorpositiveend - minord * mindir; - double df= sqrt(majord*majord+minord*minord); + double df = sqrt(majord * majord + minord * minord); Base::Vector3d focus1P = center + df * majdir; - if(!major) - { - Part::GeomLineSegment *lmajor = new Part::GeomLineSegment(); - lmajor->setPoints(majorpositiveend,majornegativeend); + if (!major) { + Part::GeomLineSegment* lmajor = new Part::GeomLineSegment(); + lmajor->setPoints(majorpositiveend, majornegativeend); igeo.push_back(lmajor); - Sketcher::Constraint *newConstr = new Sketcher::Constraint(); + Sketcher::Constraint* newConstr = new Sketcher::Constraint(); newConstr->Type = Sketcher::InternalAlignment; newConstr->AlignmentType = Sketcher::HyperbolaMajor; - newConstr->First = currentgeoid+incrgeo+1; + newConstr->First = currentgeoid + incrgeo + 1; newConstr->Second = GeoId; icon.push_back(newConstr); incrgeo++; } - if(!minor) - { - Part::GeomLineSegment *lminor = new Part::GeomLineSegment(); - lminor->setPoints(minorpositiveend,minornegativeend); + if (!minor) { + Part::GeomLineSegment* lminor = new Part::GeomLineSegment(); + lminor->setPoints(minorpositiveend, minornegativeend); igeo.push_back(lminor); - Sketcher::Constraint *newConstr = new Sketcher::Constraint(); + Sketcher::Constraint* newConstr = new Sketcher::Constraint(); newConstr->Type = Sketcher::InternalAlignment; newConstr->AlignmentType = Sketcher::HyperbolaMinor; - newConstr->First = currentgeoid+incrgeo+1; + newConstr->First = currentgeoid + incrgeo + 1; newConstr->Second = GeoId; icon.push_back(newConstr); incrgeo++; } - if(!focus) - { - Part::GeomPoint *pf1 = new Part::GeomPoint(); + if (!focus) { + Part::GeomPoint* pf1 = new Part::GeomPoint(); pf1->setPoint(focus1P); igeo.push_back(pf1); - Sketcher::Constraint *newConstr = new Sketcher::Constraint(); + Sketcher::Constraint* newConstr = new Sketcher::Constraint(); newConstr->Type = Sketcher::InternalAlignment; newConstr->AlignmentType = Sketcher::HyperbolaFocus; - newConstr->First = currentgeoid+incrgeo+1; + newConstr->First = currentgeoid + incrgeo + 1; newConstr->FirstPos = Sketcher::PointPos::start; newConstr->Second = GeoId; @@ -5138,36 +5530,35 @@ int SketchObject::exposeInternalGeometry(int GeoId) incrgeo++; } - this->addGeometry(igeo,true); + this->addGeometry(igeo, true); this->addConstraints(icon); - for (std::vector::iterator it=igeo.begin(); it != igeo.end(); ++it) + for (std::vector::iterator it = igeo.begin(); it != igeo.end(); ++it) if (*it) delete *it; - for (std::vector::iterator it=icon.begin(); it != icon.end(); ++it) + for (std::vector::iterator it = icon.begin(); it != icon.end(); ++it) if (*it) delete *it; icon.clear(); igeo.clear(); - return incrgeo; //number of added elements + return incrgeo;// number of added elements } - else if(geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + else if (geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { // First we search what has to be restored - bool focus=false; - bool focus_to_vertex=false; + bool focus = false; + bool focus_to_vertex = false; - const std::vector< Sketcher::Constraint * > &vals = Constraints.getValues(); + const std::vector& vals = Constraints.getValues(); - for (std::vector< Sketcher::Constraint * >::const_iterator it= vals.begin(); - it != vals.end(); ++it) { - if((*it)->Type == Sketcher::InternalAlignment && (*it)->Second == GeoId) - { - switch((*it)->AlignmentType){ + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); + ++it) { + if ((*it)->Type == Sketcher::InternalAlignment && (*it)->Second == GeoId) { + switch ((*it)->AlignmentType) { case Sketcher::ParabolaFocus: - focus=true; + focus = true; break; case Sketcher::ParabolaFocalAxis: focus_to_vertex = true; @@ -5178,27 +5569,27 @@ int SketchObject::exposeInternalGeometry(int GeoId) } } - int currentgeoid= getHighestCurveIndex(); - int incrgeo= 0; + int currentgeoid = getHighestCurveIndex(); + int incrgeo = 0; - const Part::GeomArcOfParabola *aop = static_cast(geo); + const Part::GeomArcOfParabola* aop = static_cast(geo); Base::Vector3d center = aop->getCenter(); Base::Vector3d focusp = aop->getFocus(); - std::vector igeo; - std::vector icon; + std::vector igeo; + std::vector icon; - if (!focus) { - Part::GeomPoint *pf1 = new Part::GeomPoint(); + if (!focus) { + Part::GeomPoint* pf1 = new Part::GeomPoint(); pf1->setPoint(focusp); igeo.push_back(pf1); - Sketcher::Constraint *newConstr = new Sketcher::Constraint(); + Sketcher::Constraint* newConstr = new Sketcher::Constraint(); newConstr->Type = Sketcher::InternalAlignment; newConstr->AlignmentType = Sketcher::ParabolaFocus; - newConstr->First = currentgeoid+incrgeo+1; + newConstr->First = currentgeoid + incrgeo + 1; newConstr->FirstPos = Sketcher::PointPos::start; newConstr->Second = GeoId; @@ -5206,16 +5597,16 @@ int SketchObject::exposeInternalGeometry(int GeoId) incrgeo++; } - if (!focus_to_vertex) { - Part::GeomLineSegment *paxis = new Part::GeomLineSegment(); - paxis->setPoints(center,focusp); + if (!focus_to_vertex) { + Part::GeomLineSegment* paxis = new Part::GeomLineSegment(); + paxis->setPoints(center, focusp); igeo.push_back(paxis); - Sketcher::Constraint *newConstr = new Sketcher::Constraint(); + Sketcher::Constraint* newConstr = new Sketcher::Constraint(); newConstr->Type = Sketcher::InternalAlignment; newConstr->AlignmentType = Sketcher::ParabolaFocalAxis; - newConstr->First = currentgeoid+incrgeo+1; + newConstr->First = currentgeoid + incrgeo + 1; newConstr->FirstPos = Sketcher::PointPos::none; newConstr->Second = GeoId; @@ -5224,15 +5615,15 @@ int SketchObject::exposeInternalGeometry(int GeoId) incrgeo++; } - this->addGeometry(igeo,true); + this->addGeometry(igeo, true); this->addConstraints(icon); - for (std::vector::iterator it=igeo.begin(); it != igeo.end(); ++it) { + for (std::vector::iterator it = igeo.begin(); it != igeo.end(); ++it) { if (*it) delete *it; } - for (std::vector::iterator it=icon.begin(); it != icon.end(); ++it) { + for (std::vector::iterator it = icon.begin(); it != icon.end(); ++it) { if (*it) delete *it; } @@ -5240,11 +5631,11 @@ int SketchObject::exposeInternalGeometry(int GeoId) icon.clear(); igeo.clear(); - return incrgeo; //number of added elements + return incrgeo;// number of added elements } - else if(geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { + else if (geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { - const Part::GeomBSplineCurve *bsp = static_cast(geo); + const Part::GeomBSplineCurve* bsp = static_cast(geo); // First we search what has to be restored std::vector controlpoints(bsp->countPoles()); std::vector controlpointgeoids(bsp->countPoles()); @@ -5257,24 +5648,27 @@ int SketchObject::exposeInternalGeometry(int GeoId) std::vector::iterator itb; std::vector::iterator it; - for(it=controlpointgeoids.begin(), itb=controlpoints.begin(); it!=controlpointgeoids.end() && itb!=controlpoints.end(); ++it, ++itb) { - (*it)=-1; - (*itb)=false; + for (it = controlpointgeoids.begin(), itb = controlpoints.begin(); + it != controlpointgeoids.end() && itb != controlpoints.end(); + ++it, ++itb) { + (*it) = -1; + (*itb) = false; } - for(it=knotgeoids.begin(), itb=knotpoints.begin(); it!=knotgeoids.end() && itb!=knotpoints.end(); ++it, ++itb) { - (*it)=-1; - (*itb)=false; + for (it = knotgeoids.begin(), itb = knotpoints.begin(); + it != knotgeoids.end() && itb != knotpoints.end(); + ++it, ++itb) { + (*it) = -1; + (*itb) = false; } - const std::vector< Sketcher::Constraint * > &vals = Constraints.getValues(); + const std::vector& vals = Constraints.getValues(); // search for existing poles - for (std::vector< Sketcher::Constraint * >::const_iterator it= vals.begin(); - it != vals.end(); ++it) { - if((*it)->Type == Sketcher::InternalAlignment && (*it)->Second == GeoId) - { - switch((*it)->AlignmentType){ + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); + ++it) { + if ((*it)->Type == Sketcher::InternalAlignment && (*it)->Second == GeoId) { + switch ((*it)->AlignmentType) { case Sketcher::BSplineControlPoint: controlpoints[(*it)->InternalAlignmentIndex] = true; controlpointgeoids[(*it)->InternalAlignmentIndex] = (*it)->First; @@ -5289,12 +5683,13 @@ int SketchObject::exposeInternalGeometry(int GeoId) } } - if(controlpoints[0]) { + if (controlpoints[0]) { // search for first pole weight constraint - for (std::vector< Sketcher::Constraint * >::const_iterator it= vals.begin(); - it != vals.end(); ++it) { - if((*it)->Type == Sketcher::Weight && (*it)->First == controlpointgeoids[0]) { - isfirstweightconstrained = true ; + for (std::vector::const_iterator it = vals.begin(); + it != vals.end(); + ++it) { + if ((*it)->Type == Sketcher::Weight && (*it)->First == controlpointgeoids[0]) { + isfirstweightconstrained = true; } } } @@ -5302,44 +5697,46 @@ int SketchObject::exposeInternalGeometry(int GeoId) int currentgeoid = getHighestCurveIndex(); int incrgeo = 0; - std::vector igeo; - std::vector icon; + std::vector igeo; + std::vector icon; std::vector poles = bsp->getPoles(); std::vector weights = bsp->getWeights(); std::vector knots = bsp->getKnots(); - double distance_p0_p1 = (poles[1]-poles[0]).Length(); // for visual purposes only + double distance_p0_p1 = (poles[1] - poles[0]).Length();// for visual purposes only - int index=0; + int index = 0; - for(it=controlpointgeoids.begin(), itb=controlpoints.begin(); it!=controlpointgeoids.end() && itb!=controlpoints.end(); ++it, ++itb, index++) { + for (it = controlpointgeoids.begin(), itb = controlpoints.begin(); + it != controlpointgeoids.end() && itb != controlpoints.end(); + ++it, ++itb, index++) { - if(!(*itb)) // if controlpoint not existing + if (!(*itb))// if controlpoint not existing { - Part::GeomCircle *pc = new Part::GeomCircle(); + Part::GeomCircle* pc = new Part::GeomCircle(); pc->setCenter(poles[index]); - pc->setRadius(distance_p0_p1/6); + pc->setRadius(distance_p0_p1 / 6); igeo.push_back(pc); - Sketcher::Constraint *newConstr = new Sketcher::Constraint(); + Sketcher::Constraint* newConstr = new Sketcher::Constraint(); newConstr->Type = Sketcher::InternalAlignment; newConstr->AlignmentType = Sketcher::BSplineControlPoint; - newConstr->First = currentgeoid+incrgeo+1; + newConstr->First = currentgeoid + incrgeo + 1; newConstr->FirstPos = Sketcher::PointPos::mid; newConstr->Second = GeoId; newConstr->InternalAlignmentIndex = index; icon.push_back(newConstr); - if(it != controlpointgeoids.begin()) { - if(isfirstweightconstrained && weights[0] == weights[index]) { + if (it != controlpointgeoids.begin()) { + if (isfirstweightconstrained && weights[0] == weights[index]) { // if pole-weight newly created AND first weight is radius-constrained, // AND these weights are equal, constrain them to be equal - Sketcher::Constraint *newConstr2 = new Sketcher::Constraint(); + Sketcher::Constraint* newConstr2 = new Sketcher::Constraint(); newConstr2->Type = Sketcher::Equal; - newConstr2->First = currentgeoid+incrgeo+1; + newConstr2->First = currentgeoid + incrgeo + 1; newConstr2->FirstPos = Sketcher::PointPos::none; newConstr2->Second = controlpointgeoids[0]; newConstr2->SecondPos = Sketcher::PointPos::none; @@ -5348,10 +5745,10 @@ int SketchObject::exposeInternalGeometry(int GeoId) } } else { - controlpointgeoids[0] = currentgeoid+incrgeo+1; + controlpointgeoids[0] = currentgeoid + incrgeo + 1; if (weights[0] == 1.0) { // if the first weight is 1.0 it's probably going to be non-rational - Sketcher::Constraint *newConstr3 = new Sketcher::Constraint(); + Sketcher::Constraint* newConstr3 = new Sketcher::Constraint(); newConstr3->Type = Sketcher::Weight; newConstr3->First = controlpointgeoids[0]; newConstr3->setValue(weights[0]); @@ -5365,22 +5762,24 @@ int SketchObject::exposeInternalGeometry(int GeoId) } } - index=0; + index = 0; - for(it=knotgeoids.begin(), itb=knotpoints.begin(); it!=knotgeoids.end() && itb!=knotpoints.end(); ++it, ++itb, index++) { + for (it = knotgeoids.begin(), itb = knotpoints.begin(); + it != knotgeoids.end() && itb != knotpoints.end(); + ++it, ++itb, index++) { - if(!(*itb)) // if knot point not existing + if (!(*itb))// if knot point not existing { - Part::GeomPoint *kp = new Part::GeomPoint(); + Part::GeomPoint* kp = new Part::GeomPoint(); kp->setPoint(bsp->pointAtParameter(knots[index])); igeo.push_back(kp); - Sketcher::Constraint *newConstr = new Sketcher::Constraint(); + Sketcher::Constraint* newConstr = new Sketcher::Constraint(); newConstr->Type = Sketcher::InternalAlignment; newConstr->AlignmentType = Sketcher::BSplineKnotPoint; - newConstr->First = currentgeoid+incrgeo+1; + newConstr->First = currentgeoid + incrgeo + 1; newConstr->FirstPos = Sketcher::PointPos::start; newConstr->Second = GeoId; newConstr->InternalAlignmentIndex = index; @@ -5393,63 +5792,62 @@ int SketchObject::exposeInternalGeometry(int GeoId) Q_UNUSED(isfirstweightconstrained); - this->addGeometry(igeo,true); + this->addGeometry(igeo, true); this->addConstraints(icon); - for (std::vector::iterator it=igeo.begin(); it != igeo.end(); ++it) + for (std::vector::iterator it = igeo.begin(); it != igeo.end(); ++it) if (*it) delete *it; - for (std::vector::iterator it=icon.begin(); it != icon.end(); ++it) + for (std::vector::iterator it = icon.begin(); it != icon.end(); ++it) if (*it) delete *it; icon.clear(); igeo.clear(); - return incrgeo; //number of added elements + return incrgeo;// number of added elements } else - return -1; // not supported type + return -1;// not supported type } int SketchObject::deleteUnusedInternalGeometry(int GeoId, bool delgeoid) { - if (GeoId < 0 || GeoId > getHighestCurveIndex()) + if (GeoId < 0 || GeoId > getHighestCurveIndex()) return -1; - const Part::Geometry *geo = getGeometry(GeoId); + const Part::Geometry* geo = getGeometry(GeoId); // Only for supported types - if (geo->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + if (geo->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { - int majorelementindex=-1; - int minorelementindex=-1; - int focus1elementindex=-1; - int focus2elementindex=-1; + int majorelementindex = -1; + int minorelementindex = -1; + int focus1elementindex = -1; + int focus2elementindex = -1; - const std::vector< Sketcher::Constraint * > &vals = Constraints.getValues(); + const std::vector& vals = Constraints.getValues(); - for (std::vector< Sketcher::Constraint * >::const_iterator it = vals.begin(); - it != vals.end(); ++it) { - if((*it)->Type == Sketcher::InternalAlignment && (*it)->Second == GeoId) - { - switch((*it)->AlignmentType){ + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); + ++it) { + if ((*it)->Type == Sketcher::InternalAlignment && (*it)->Second == GeoId) { + switch ((*it)->AlignmentType) { case Sketcher::EllipseMajorDiameter: case Sketcher::HyperbolaMajor: - majorelementindex=(*it)->First; + majorelementindex = (*it)->First; break; case Sketcher::EllipseMinorDiameter: case Sketcher::HyperbolaMinor: - minorelementindex=(*it)->First; + minorelementindex = (*it)->First; break; case Sketcher::EllipseFocus1: case Sketcher::HyperbolaFocus: - focus1elementindex=(*it)->First; + focus1elementindex = (*it)->First; break; case Sketcher::EllipseFocus2: - focus2elementindex=(*it)->First; + focus2elementindex = (*it)->First; break; default: return -1; @@ -5458,125 +5856,137 @@ int SketchObject::deleteUnusedInternalGeometry(int GeoId, bool delgeoid) } // Hide unused geometry here - int majorconstraints=0; // number of constraints associated to the geoid of the major axis - int minorconstraints=0; - int focus1constraints=0; - int focus2constraints=0; + int majorconstraints = 0;// number of constraints associated to the geoid of the major axis + int minorconstraints = 0; + int focus1constraints = 0; + int focus2constraints = 0; - for (std::vector< Sketcher::Constraint * >::const_iterator it= vals.begin(); - it != vals.end(); ++it) { + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); + ++it) { - if((*it)->Second == majorelementindex || (*it)->First == majorelementindex || (*it)->Third == majorelementindex) + if ((*it)->Second == majorelementindex || (*it)->First == majorelementindex + || (*it)->Third == majorelementindex) majorconstraints++; - else if((*it)->Second == minorelementindex || (*it)->First == minorelementindex || (*it)->Third == minorelementindex) + else if ((*it)->Second == minorelementindex || (*it)->First == minorelementindex + || (*it)->Third == minorelementindex) minorconstraints++; - else if((*it)->Second == focus1elementindex || (*it)->First == focus1elementindex || (*it)->Third == focus1elementindex) + else if ((*it)->Second == focus1elementindex || (*it)->First == focus1elementindex + || (*it)->Third == focus1elementindex) focus1constraints++; - else if((*it)->Second == focus2elementindex || (*it)->First == focus2elementindex || (*it)->Third == focus2elementindex) + else if ((*it)->Second == focus2elementindex || (*it)->First == focus2elementindex + || (*it)->Third == focus2elementindex) focus2constraints++; } std::vector delgeometries; // those with less than 2 constraints must be removed - if (focus2constraints<2) + if (focus2constraints < 2) delgeometries.push_back(focus2elementindex); - if (focus1constraints<2) + if (focus1constraints < 2) delgeometries.push_back(focus1elementindex); - if (minorconstraints<2) + if (minorconstraints < 2) delgeometries.push_back(minorelementindex); - if (majorconstraints<2) + if (majorconstraints < 2) delgeometries.push_back(majorelementindex); - if(delgeoid) + if (delgeoid) delgeometries.push_back(GeoId); - std::sort(delgeometries.begin(), delgeometries.end()); // indices over an erased element get automatically updated!! + // indices over an erased element get automatically updated!! + std::sort(delgeometries.begin(), delgeometries.end()); if (!delgeometries.empty()) { - for (std::vector::reverse_iterator it=delgeometries.rbegin(); it!=delgeometries.rend(); ++it) { - delGeometry(*it,false); + for (std::vector::reverse_iterator it = delgeometries.rbegin(); + it != delgeometries.rend(); + ++it) { + delGeometry(*it, false); } } - int ndeleted = delgeometries.size(); + int ndeleted = delgeometries.size(); delgeometries.clear(); - return ndeleted; //number of deleted elements + return ndeleted;// number of deleted elements } - else if( geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + else if (geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { // if the focus-to-vertex line is constrained, then never delete the focus // if the line is unconstrained, then the line may be deleted, // in this case the focus may be deleted if unconstrained. - int majorelementindex=-1; - int focus1elementindex=-1; + int majorelementindex = -1; + int focus1elementindex = -1; - const std::vector< Sketcher::Constraint * > &vals = Constraints.getValues(); + const std::vector& vals = Constraints.getValues(); - for (std::vector< Sketcher::Constraint * >::const_iterator it= vals.begin(); it != vals.end(); ++it) { + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); + ++it) { if ((*it)->Type == Sketcher::InternalAlignment && (*it)->Second == GeoId) { switch ((*it)->AlignmentType) { - case Sketcher::ParabolaFocus: - focus1elementindex = (*it)->First; - break; - case Sketcher::ParabolaFocalAxis: - majorelementindex = (*it)->First; - break; - default: - return -1; + case Sketcher::ParabolaFocus: + focus1elementindex = (*it)->First; + break; + case Sketcher::ParabolaFocalAxis: + majorelementindex = (*it)->First; + break; + default: + return -1; } } } // Hide unused geometry here - int majorconstraints=0; // number of constraints associated to the geoid of the major axis other than the coincident ones - int focus1constraints=0; + // number of constraints associated to the geoid of the major axis other than the coincident + // ones + int majorconstraints = 0; + int focus1constraints = 0; - for (std::vector< Sketcher::Constraint * >::const_iterator it= vals.begin(); it != vals.end(); ++it) { - if( (*it)->Second == majorelementindex || - (*it)->First == majorelementindex || - (*it)->Third == majorelementindex) + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); + ++it) { + if ((*it)->Second == majorelementindex || (*it)->First == majorelementindex + || (*it)->Third == majorelementindex) majorconstraints++; - else if ((*it)->Second == focus1elementindex || - (*it)->First == focus1elementindex || - (*it)->Third == focus1elementindex) + else if ((*it)->Second == focus1elementindex || (*it)->First == focus1elementindex + || (*it)->Third == focus1elementindex) focus1constraints++; } std::vector delgeometries; // major has minimum one constraint, the specific internal alignment constraint - if (majorelementindex !=-1 && majorconstraints<2) + if (majorelementindex != -1 && majorconstraints < 2) delgeometries.push_back(majorelementindex); // focus has minimum one constraint now, the specific internal alignment constraint - if (focus1elementindex !=-1 && focus1constraints<2) + if (focus1elementindex != -1 && focus1constraints < 2) delgeometries.push_back(focus1elementindex); - if(delgeoid) + if (delgeoid) delgeometries.push_back(GeoId); - std::sort(delgeometries.begin(), delgeometries.end()); // indices over an erased element get automatically updated!! + // indices over an erased element get automatically updated!! + std::sort(delgeometries.begin(), delgeometries.end()); if (!delgeometries.empty()) { - for (std::vector::reverse_iterator it=delgeometries.rbegin(); it!=delgeometries.rend(); ++it) { - delGeometry(*it,false); + for (std::vector::reverse_iterator it = delgeometries.rbegin(); + it != delgeometries.rend(); + ++it) { + delGeometry(*it, false); } } - int ndeleted = delgeometries.size(); + int ndeleted = delgeometries.size(); delgeometries.clear(); - return ndeleted; //number of deleted elements + return ndeleted;// number of deleted elements } else if (geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { - const Part::GeomBSplineCurve *bsp = static_cast(geo); + const Part::GeomBSplineCurve* bsp = static_cast(geo); // First we search existing IA std::vector controlpointgeoids(bsp->countPoles()); @@ -5588,124 +5998,141 @@ int SketchObject::deleteUnusedInternalGeometry(int GeoId, bool delgeoid) std::vector::iterator it; std::vector::iterator ita; - for (it=controlpointgeoids.begin(), ita=cpassociatedconstraints.begin(); it!=controlpointgeoids.end() && ita!=cpassociatedconstraints.end(); ++it, ++ita) { + for (it = controlpointgeoids.begin(), ita = cpassociatedconstraints.begin(); + it != controlpointgeoids.end() && ita != cpassociatedconstraints.end(); + ++it, ++ita) { (*it) = -1; (*ita) = 0; } - for (it=knotgeoids.begin(), ita=kassociatedconstraints.begin(); it!=knotgeoids.end() && ita!=kassociatedconstraints.end(); ++it, ++ita) { + for (it = knotgeoids.begin(), ita = kassociatedconstraints.begin(); + it != knotgeoids.end() && ita != kassociatedconstraints.end(); + ++it, ++ita) { (*it) = -1; (*ita) = 0; } - const std::vector< Sketcher::Constraint * > &vals = Constraints.getValues(); + const std::vector& vals = Constraints.getValues(); // search for existing poles - for (std::vector< Sketcher::Constraint * >::const_iterator jt = vals.begin(); jt != vals.end(); ++jt) { + for (std::vector::const_iterator jt = vals.begin(); jt != vals.end(); + ++jt) { if ((*jt)->Type == Sketcher::InternalAlignment && (*jt)->Second == GeoId) { switch ((*jt)->AlignmentType) { - case Sketcher::BSplineControlPoint: - controlpointgeoids[(*jt)->InternalAlignmentIndex] = (*jt)->First; - break; - case Sketcher::BSplineKnotPoint: - knotgeoids[(*jt)->InternalAlignmentIndex] = (*jt)->First; - break; - default: - return -1; + case Sketcher::BSplineControlPoint: + controlpointgeoids[(*jt)->InternalAlignmentIndex] = (*jt)->First; + break; + case Sketcher::BSplineKnotPoint: + knotgeoids[(*jt)->InternalAlignmentIndex] = (*jt)->First; + break; + default: + return -1; } } } std::vector delgeometries; - for (it=controlpointgeoids.begin(), ita=cpassociatedconstraints.begin(); it!=controlpointgeoids.end() && ita!=cpassociatedconstraints.end(); ++it, ++ita) { + for (it = controlpointgeoids.begin(), ita = cpassociatedconstraints.begin(); + it != controlpointgeoids.end() && ita != cpassociatedconstraints.end(); + ++it, ++ita) { if ((*it) != -1) { // look for a circle at geoid index - for (std::vector< Sketcher::Constraint * >::const_iterator itc= vals.begin(); itc != vals.end(); ++itc) { + for (std::vector::const_iterator itc = vals.begin(); + itc != vals.end(); + ++itc) { - if ( (*itc)->Type==Sketcher::Equal ) { - bool f=false,s=false; - for ( std::vector::iterator its=controlpointgeoids.begin(); its!=controlpointgeoids.end(); ++its) { - if( (*itc)->First == *its ) { - f=true; + if ((*itc)->Type == Sketcher::Equal) { + bool f = false, s = false; + for (std::vector::iterator its = controlpointgeoids.begin(); + its != controlpointgeoids.end(); + ++its) { + if ((*itc)->First == *its) { + f = true; } - else if ( (*itc)->Second == *its ) { - s=true; + else if ((*itc)->Second == *its) { + s = true; } - if (f && s) { // the equality constraint is not interpole + if (f && s) {// the equality constraint is not interpole break; } } - if (f != s) { // the equality constraint constraints a pole but it is not interpole + // the equality constraint constraints a pole but it is not interpole + if (f != s) { (*ita)++; } - } - // We do not ignore weight constraints as we did with radius constraints, because the radius magnitude no longer makes sense - // without the B-Spline. + // We do not ignore weight constraints as we did with radius constraints, + // because the radius magnitude no longer makes sense without the B-Spline. } - if ( (*ita) < 2 ) { // IA + if ((*ita) < 2) {// IA delgeometries.push_back((*it)); } } } - for (it=knotgeoids.begin(), ita=kassociatedconstraints.begin(); it!=knotgeoids.end() && ita!=kassociatedconstraints.end(); ++it, ++ita) { + for (it = knotgeoids.begin(), ita = kassociatedconstraints.begin(); + it != knotgeoids.end() && ita != kassociatedconstraints.end(); + ++it, ++ita) { if ((*it) != -1) { // look for a point at geoid index - for (std::vector< Sketcher::Constraint * >::const_iterator itc= vals.begin(); itc != vals.end(); ++itc) { - if ((*itc)->Second == (*it) || (*itc)->First == (*it) || (*itc)->Third == (*it)) { + for (std::vector::const_iterator itc = vals.begin(); + itc != vals.end(); + ++itc) { + if ((*itc)->Second == (*it) || (*itc)->First == (*it) + || (*itc)->Third == (*it)) { (*ita)++; } } - if ( (*ita) < 2 ) { // IA + if ((*ita) < 2) {// IA delgeometries.push_back((*it)); } } } - if(delgeoid) + if (delgeoid) delgeometries.push_back(GeoId); int ndeleted = delGeometriesExclusiveList(delgeometries); - return ndeleted; //number of deleted elements + return ndeleted;// number of deleted elements } else { - return -1; // not supported type + return -1;// not supported type } } bool SketchObject::convertToNURBS(int GeoId) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - if (GeoId > getHighestCurveIndex() || - (GeoId < 0 && -GeoId > static_cast(ExternalGeo.size())) || - GeoId == -1 || GeoId == -2) + if (GeoId > getHighestCurveIndex() + || (GeoId < 0 && -GeoId > static_cast(ExternalGeo.size())) || GeoId == -1 + || GeoId == -2) return false; - const Part::Geometry *geo = getGeometry(GeoId); + const Part::Geometry* geo = getGeometry(GeoId); - if(geo->getTypeId() == Part::GeomPoint::getClassTypeId()) + if (geo->getTypeId() == Part::GeomPoint::getClassTypeId()) return false; - const Part::GeomCurve *geo1 = static_cast(geo); + const Part::GeomCurve* geo1 = static_cast(geo); Part::GeomBSplineCurve* bspline; try { bspline = geo1->toNurbs(geo1->getFirstParameter(), geo1->getLastParameter()); - if(geo1->isDerivedFrom(Part::GeomArcOfConic::getClassTypeId())){ - const Part::GeomArcOfConic * geoaoc = static_cast(geo1); + if (geo1->isDerivedFrom(Part::GeomArcOfConic::getClassTypeId())) { + const Part::GeomArcOfConic* geoaoc = static_cast(geo1); - if(geoaoc->isReversed()) + if (geoaoc->isReversed()) bspline->reverse(); } } @@ -5715,39 +6142,42 @@ bool SketchObject::convertToNURBS(int GeoId) return false; } - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); - std::vector< Part::Geometry * > newVals(vals); + std::vector newVals(vals); // Block checks and updates in OnChanged to avoid unnecessary checks and updates { Base::StateLocker lock(internaltransaction, true); - if (GeoId < 0) { // external geometry + if (GeoId < 0) {// external geometry newVals.push_back(bspline); } - else { // normal geometry + else {// normal geometry newVals[GeoId] = bspline; - const std::vector< Sketcher::Constraint * > &cvals = Constraints.getValues(); + const std::vector& cvals = Constraints.getValues(); - std::vector< Constraint * > newcVals(cvals); + std::vector newcVals(cvals); - int index = cvals.size()-1; - // delete constraints on this elements other than coincident constraints (bspline does not support them currently), except - // for coincidents on mid point of the to-be-converted curve. + int index = cvals.size() - 1; + // delete constraints on this elements other than coincident constraints (bspline does + // not support them currently), except for coincidents on mid point of the + // to-be-converted curve. for (; index >= 0; index--) { - auto otherthancoincident = cvals[index]->Type != Sketcher::Coincident && - (cvals[index]->First == GeoId || cvals[index]->Second == GeoId || cvals[index]->Third == GeoId); + auto otherthancoincident = cvals[index]->Type != Sketcher::Coincident + && (cvals[index]->First == GeoId || cvals[index]->Second == GeoId + || cvals[index]->Third == GeoId); - auto coincidentonmidpoint = cvals[index]->Type == Sketcher::Coincident && - ( (cvals[index]->First == GeoId && cvals[index]->FirstPos == Sketcher::PointPos::mid) || - (cvals[index]->Second == GeoId && cvals[index]->SecondPos == Sketcher::PointPos::mid) ); + auto coincidentonmidpoint = cvals[index]->Type == Sketcher::Coincident + && ((cvals[index]->First == GeoId + && cvals[index]->FirstPos == Sketcher::PointPos::mid) + || (cvals[index]->Second == GeoId + && cvals[index]->SecondPos == Sketcher::PointPos::mid)); if (otherthancoincident || coincidentonmidpoint) - newcVals.erase(newcVals.begin()+index); - + newcVals.erase(newcVals.begin() + index); } this->Constraints.setValues(std::move(newcVals)); @@ -5757,26 +6187,27 @@ bool SketchObject::convertToNURBS(int GeoId) } // trigger update now - // Update geometry indices and rebuild vertexindex now via onChanged, so that ViewProvider::UpdateData is triggered. + // Update geometry indices and rebuild vertexindex now via onChanged, so that + // ViewProvider::UpdateData is triggered. Geometry.touch(); return true; - } bool SketchObject::increaseBSplineDegree(int GeoId, int degreeincrement /*= 1*/) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); if (GeoId < 0 || GeoId > getHighestCurveIndex()) return false; - const Part::Geometry *geo = getGeometry(GeoId); + const Part::Geometry* geo = getGeometry(GeoId); if (geo->getTypeId() != Part::GeomBSplineCurve::getClassTypeId()) return false; - const Part::GeomBSplineCurve *bsp = static_cast(geo); + const Part::GeomBSplineCurve* bsp = static_cast(geo); const Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast(bsp->handle()); @@ -5785,16 +6216,16 @@ bool SketchObject::increaseBSplineDegree(int GeoId, int degreeincrement /*= 1*/) try { int cdegree = bspline->getDegree(); - bspline->increaseDegree(cdegree+degreeincrement); + bspline->increaseDegree(cdegree + degreeincrement); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); return false; } - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); - std::vector< Part::Geometry * > newVals(vals); + std::vector newVals(vals); newVals[GeoId] = bspline.release(); @@ -5806,17 +6237,18 @@ bool SketchObject::increaseBSplineDegree(int GeoId, int degreeincrement /*= 1*/) bool SketchObject::decreaseBSplineDegree(int GeoId, int degreedecrement /*= 1*/) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); if (GeoId < 0 || GeoId > getHighestCurveIndex()) return false; - const Part::Geometry *geo = getGeometry(GeoId); + const Part::Geometry* geo = getGeometry(GeoId); if (geo->getTypeId() != Part::GeomBSplineCurve::getClassTypeId()) return false; - const Part::GeomBSplineCurve *bsp = static_cast(geo); + const Part::GeomBSplineCurve* bsp = static_cast(geo); const Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast(bsp->handle()); @@ -5860,47 +6292,67 @@ bool SketchObject::decreaseBSplineDegree(int GeoId, int degreedecrement /*= 1*/) bool SketchObject::modifyBSplineKnotMultiplicity(int GeoId, int knotIndex, int multiplicityincr) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); if (GeoId < 0 || GeoId > getHighestCurveIndex()) - THROWMT(Base::ValueError,QT_TRANSLATE_NOOP("Exceptions", "BSpline Geometry Index (GeoID) is out of bounds.")) + THROWMT(Base::ValueError, + QT_TRANSLATE_NOOP("Exceptions", "BSpline Geometry Index (GeoID) is out of bounds.")) - if (multiplicityincr == 0) // no change in multiplicity - THROWMT(Base::ValueError,QT_TRANSLATE_NOOP("Exceptions", "You are requesting no change in knot multiplicity.")) + if (multiplicityincr == 0)// no change in multiplicity + THROWMT( + Base::ValueError, + QT_TRANSLATE_NOOP("Exceptions", "You are requesting no change in knot multiplicity.")) - const Part::Geometry *geo = getGeometry(GeoId); + const Part::Geometry* geo = getGeometry(GeoId); - if(geo->getTypeId() != Part::GeomBSplineCurve::getClassTypeId()) - THROWMT(Base::TypeError,QT_TRANSLATE_NOOP("Exceptions", "The Geometry Index (GeoId) provided is not a B-spline curve.")) + if (geo->getTypeId() != Part::GeomBSplineCurve::getClassTypeId()) + THROWMT(Base::TypeError, + QT_TRANSLATE_NOOP("Exceptions", + "The Geometry Index (GeoId) provided is not a B-spline curve.")) - const Part::GeomBSplineCurve *bsp = static_cast(geo); + const Part::GeomBSplineCurve* bsp = static_cast(geo); int degree = bsp->getDegree(); - if( knotIndex > bsp->countKnots() || knotIndex < 1 ) // knotindex in OCC 1 -> countKnots - THROWMT(Base::ValueError,QT_TRANSLATE_NOOP("Exceptions", "The knot index is out of bounds. Note that in accordance with OCC notation, the first knot has index 1 and not zero.")) + if (knotIndex > bsp->countKnots() || knotIndex < 1)// knotindex in OCC 1 -> countKnots + THROWMT(Base::ValueError, + QT_TRANSLATE_NOOP("Exceptions", + "The knot index is out of bounds. Note that in accordance with " + "OCC notation, the first knot has index 1 and not zero.")) std::unique_ptr bspline; int curmult = bsp->getMultiplicity(knotIndex); - if ( (curmult + multiplicityincr) > degree ) // zero is removing the knot, degree is just positional continuity - THROWMT(Base::ValueError,QT_TRANSLATE_NOOP("Exceptions","The multiplicity cannot be increased beyond the degree of the B-spline.")) + // zero is removing the knot, degree is just positional continuity + if ((curmult + multiplicityincr) > degree) + THROWMT(Base::ValueError, + QT_TRANSLATE_NOOP( + "Exceptions", + "The multiplicity cannot be increased beyond the degree of the B-spline.")) - if ( (curmult + multiplicityincr) < 0) // zero is removing the knot, degree is just positional continuity - THROWMT(Base::ValueError,QT_TRANSLATE_NOOP("Exceptions", "The multiplicity cannot be decreased beyond zero.")) + // zero is removing the knot, degree is just positional continuity + if ((curmult + multiplicityincr) < 0) + THROWMT( + Base::ValueError, + QT_TRANSLATE_NOOP("Exceptions", "The multiplicity cannot be decreased beyond zero.")) try { - bspline.reset(static_cast(bsp->clone())); + bspline.reset(static_cast(bsp->clone())); - if(multiplicityincr > 0) { // increase multiplicity + if (multiplicityincr > 0) {// increase multiplicity bspline->increaseMultiplicity(knotIndex, curmult + multiplicityincr); } - else { // decrease multiplicity - bool result = bspline->removeKnot(knotIndex, curmult + multiplicityincr,1E6); + else {// decrease multiplicity + bool result = bspline->removeKnot(knotIndex, curmult + multiplicityincr, 1E6); - if(!result) - THROWMT(Base::CADKernelError, QT_TRANSLATE_NOOP("Exceptions", "OCC is unable to decrease the multiplicity within the maximum tolerance.")) + if (!result) + THROWMT( + Base::CADKernelError, + QT_TRANSLATE_NOOP( + "Exceptions", + "OCC is unable to decrease the multiplicity within the maximum tolerance.")) } } catch (const Base::Exception& e) { @@ -5908,7 +6360,8 @@ bool SketchObject::modifyBSplineKnotMultiplicity(int GeoId, int knotIndex, int m return false; } - // we succeeded with the multiplicity modification, so alignment geometry may be invalid/inconsistent for the new bspline + // we succeeded with the multiplicity modification, so alignment geometry may be + // invalid/inconsistent for the new bspline std::vector delGeoId; @@ -5916,13 +6369,13 @@ bool SketchObject::modifyBSplineKnotMultiplicity(int GeoId, int knotIndex, int m std::vector newpoles = bspline->getPoles(); std::vector prevpole(bsp->countPoles()); - for(int i = 0; i < int(poles.size()); i++) + for (int i = 0; i < int(poles.size()); i++) prevpole[i] = -1; int taken = 0; - for(int j = 0; j < int(poles.size()); j++){ - for(int i = taken; i < int(newpoles.size()); i++){ - if( newpoles[i] == poles[j] ) { + for (int j = 0; j < int(poles.size()); j++) { + for (int i = taken; i < int(newpoles.size()); i++) { + if (newpoles[i] == poles[j]) { prevpole[j] = i; taken++; break; @@ -5935,13 +6388,13 @@ bool SketchObject::modifyBSplineKnotMultiplicity(int GeoId, int knotIndex, int m std::vector newknots = bspline->getKnots(); std::vector prevknot(bsp->countKnots()); - for(int i = 0; i < int(knots.size()); i++) + for (int i = 0; i < int(knots.size()); i++) prevknot[i] = -1; taken = 0; - for(int j = 0; j < int(knots.size()); j++){ - for(int i = taken; i < int(newknots.size()); i++){ - if( newknots[i] == knots[j] ) { + for (int j = 0; j < int(knots.size()); j++) { + for (int i = taken; i < int(newknots.size()); i++) { + if (newknots[i] == knots[j]) { prevknot[j] = i; taken++; break; @@ -5949,37 +6402,41 @@ bool SketchObject::modifyBSplineKnotMultiplicity(int GeoId, int knotIndex, int m } } - const std::vector< Sketcher::Constraint * > &cvals = Constraints.getValues(); + const std::vector& cvals = Constraints.getValues(); - std::vector< Constraint * > newcVals(0); + std::vector newcVals(0); // modify pole constraints - for (std::vector< Sketcher::Constraint * >::const_iterator it= cvals.begin(); it != cvals.end(); ++it) { - if((*it)->Type == Sketcher::InternalAlignment && (*it)->Second == GeoId) - { - if((*it)->AlignmentType == Sketcher::BSplineControlPoint) { - if (prevpole[(*it)->InternalAlignmentIndex]!=-1) { + for (std::vector::const_iterator it = cvals.begin(); it != cvals.end(); + ++it) { + if ((*it)->Type == Sketcher::InternalAlignment && (*it)->Second == GeoId) { + if ((*it)->AlignmentType == Sketcher::BSplineControlPoint) { + if (prevpole[(*it)->InternalAlignmentIndex] != -1) { assert(prevpole[(*it)->InternalAlignmentIndex] < bspline->countPoles()); - Constraint * newConstr = (*it)->clone(); + Constraint* newConstr = (*it)->clone(); newConstr->InternalAlignmentIndex = prevpole[(*it)->InternalAlignmentIndex]; newcVals.push_back(newConstr); } - else { // it is an internal alignment geometry that is no longer valid => delete it and the pole circle + else { + // it is an internal alignment geometry that is no longer valid => delete it and + // the pole circle delGeoId.push_back((*it)->First); } } - else if((*it)->AlignmentType == Sketcher::BSplineKnotPoint) { - if (prevknot[(*it)->InternalAlignmentIndex]!=-1) { + else if ((*it)->AlignmentType == Sketcher::BSplineKnotPoint) { + if (prevknot[(*it)->InternalAlignmentIndex] != -1) { assert(prevknot[(*it)->InternalAlignmentIndex] < bspline->countKnots()); - Constraint * newConstr = (*it)->clone(); + Constraint* newConstr = (*it)->clone(); newConstr->InternalAlignmentIndex = prevknot[(*it)->InternalAlignmentIndex]; newcVals.push_back(newConstr); } - else { // it is an internal alignment geometry that is no longer valid => delete it and the knot point + else { + // it is an internal alignment geometry that is no longer valid => delete it and + // the knot point delGeoId.push_back((*it)->First); } } - else { // it is a bspline geometry, but not a controlpoint or knot + else {// it is a bspline geometry, but not a controlpoint or knot newcVals.push_back(*it); } } @@ -5988,9 +6445,9 @@ bool SketchObject::modifyBSplineKnotMultiplicity(int GeoId, int knotIndex, int m } } - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); - std::vector< Part::Geometry * > newVals(vals); + std::vector newVals(vals); newVals[GeoId] = bspline.release(); @@ -6003,7 +6460,8 @@ bool SketchObject::modifyBSplineKnotMultiplicity(int GeoId, int knotIndex, int m } // Trigger update now - // Update geometry indices and rebuild vertexindex now via onChanged, so that ViewProvider::UpdateData is triggered. + // Update geometry indices and rebuild vertexindex now via onChanged, so that + // ViewProvider::UpdateData is triggered. if (!delGeoId.empty()) { delGeometriesExclusiveList(delGeoId); } @@ -6015,17 +6473,23 @@ bool SketchObject::modifyBSplineKnotMultiplicity(int GeoId, int knotIndex, int m // https://forum.freecad.org/viewtopic.php?f=10&t=9364&start=330#p162528 // // A segmentation fault is generated: - //Program received signal SIGSEGV, Segmentation fault. - //#0 /lib/x86_64-linux-gnu/libc.so.6(+0x36cb0) [0x7f4b933bbcb0] - //#1 0x7f4b0300ea14 in BSplCLib::BuildCache(double, double, bool, int, TColStd_Array1OfReal const&, TColgp_Array1OfPnt const&, TColStd_Array1OfReal const&, TColgp_Array1OfPnt&, TColStd_Array1OfReal&) from /usr/lib/x86_64-linux-gnu/libTKMath.so.10+0x484 - //#2 0x7f4b033f9582 in Geom_BSplineCurve::ValidateCache(double) from /usr/lib/x86_64-linux-gnu/libTKG3d.so.10+0x202 - //#3 0x7f4b033f2a7e in Geom_BSplineCurve::D0(double, gp_Pnt&) const from /usr/lib/x86_64-linux-gnu/libTKG3d.so.10+0xde - //#4 0x7f4b033de1b5 in Geom_Curve::Value(double) const from /usr/lib/x86_64-linux-gnu/libTKG3d.so.10+0x25 - //#5 0x7f4b03423d73 in GeomLProp_CurveTool::Value(Handle(Geom_Curve) const&, double, gp_Pnt&) from /usr/lib/x86_64-linux-gnu/libTKG3d.so.10+0x13 - //#6 0x7f4b03427175 in GeomLProp_CLProps::SetParameter(double) from /usr/lib/x86_64-linux-gnu/libTKG3d.so.10+0x75 - //#7 0x7f4b0342727d in GeomLProp_CLProps::GeomLProp_CLProps(Handle(Geom_Curve) const&, double, int, double) from /usr/lib/x86_64-linux-gnu/libTKG3d.so.10+0xcd - //#8 0x7f4b11924b53 in Part::GeomCurve::pointAtParameter(double) const from /home/abdullah/github/freecad-build/Mod/Part/Part.so+0xa7 - + // Program received signal SIGSEGV, Segmentation fault. + // #0 /lib/x86_64-linux-gnu/libc.so.6(+0x36cb0) [0x7f4b933bbcb0] + // #1 0x7f4b0300ea14 in BSplCLib::BuildCache(double, double, bool, int, TColStd_Array1OfReal + // const&, TColgp_Array1OfPnt const&, TColStd_Array1OfReal const&, TColgp_Array1OfPnt&, + // TColStd_Array1OfReal&) from /usr/lib/x86_64-linux-gnu/libTKMath.so.10+0x484 #2 0x7f4b033f9582 + // in Geom_BSplineCurve::ValidateCache(double) from + // /usr/lib/x86_64-linux-gnu/libTKG3d.so.10+0x202 #3 0x7f4b033f2a7e in + // Geom_BSplineCurve::D0(double, gp_Pnt&) const from + // /usr/lib/x86_64-linux-gnu/libTKG3d.so.10+0xde #4 0x7f4b033de1b5 in Geom_Curve::Value(double) + // const from /usr/lib/x86_64-linux-gnu/libTKG3d.so.10+0x25 #5 0x7f4b03423d73 in + // GeomLProp_CurveTool::Value(Handle(Geom_Curve) const&, double, gp_Pnt&) from + // /usr/lib/x86_64-linux-gnu/libTKG3d.so.10+0x13 #6 0x7f4b03427175 in + // GeomLProp_CLProps::SetParameter(double) from /usr/lib/x86_64-linux-gnu/libTKG3d.so.10+0x75 #7 + // 0x7f4b0342727d in GeomLProp_CLProps::GeomLProp_CLProps(Handle(Geom_Curve) const&, double, + // int, double) from /usr/lib/x86_64-linux-gnu/libTKG3d.so.10+0xcd #8 0x7f4b11924b53 in + // Part::GeomCurve::pointAtParameter(double) const from + // /home/abdullah/github/freecad-build/Mod/Part/Part.so+0xa7 return true; @@ -6033,43 +6497,55 @@ bool SketchObject::modifyBSplineKnotMultiplicity(int GeoId, int knotIndex, int m bool SketchObject::insertBSplineKnot(int GeoId, double param, int multiplicity) { - Base::StateLocker lock(managedoperation, true); // TODO: Check if this is still valid: no need to check input data validity as this is an sketchobject managed operation. + // TODO: Check if this is still valid: no need to check input data validity as this is an + // sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); // handling unacceptable cases if (GeoId < 0 || GeoId > getHighestCurveIndex()) - THROWMT(Base::ValueError,QT_TRANSLATE_NOOP("Exceptions", "BSpline Geometry Index (GeoID) is out of bounds.")); + THROWMT( + Base::ValueError, + QT_TRANSLATE_NOOP("Exceptions", "BSpline Geometry Index (GeoID) is out of bounds.")); if (multiplicity == 0) - THROWMT(Base::ValueError,QT_TRANSLATE_NOOP("Exceptions", "Knot cannot have zero multiplicity.")); + THROWMT(Base::ValueError, + QT_TRANSLATE_NOOP("Exceptions", "Knot cannot have zero multiplicity.")); - const Part::Geometry *geo = getGeometry(GeoId); + const Part::Geometry* geo = getGeometry(GeoId); - if(geo->getTypeId() != Part::GeomBSplineCurve::getClassTypeId()) - THROWMT(Base::TypeError,QT_TRANSLATE_NOOP("Exceptions", "The Geometry Index (GeoId) provided is not a B-spline curve.")); + if (geo->getTypeId() != Part::GeomBSplineCurve::getClassTypeId()) + THROWMT(Base::TypeError, + QT_TRANSLATE_NOOP("Exceptions", + "The Geometry Index (GeoId) provided is not a B-spline curve.")); - const Part::GeomBSplineCurve *bsp = static_cast(geo); + const Part::GeomBSplineCurve* bsp = static_cast(geo); int degree = bsp->getDegree(); double firstParam = bsp->getFirstParameter(); double lastParam = bsp->getLastParameter(); if (multiplicity > degree) - THROWMT(Base::ValueError,QT_TRANSLATE_NOOP("Exceptions", "Knot multiplicity cannot be higher than the degree of the BSpline.")); + THROWMT(Base::ValueError, + QT_TRANSLATE_NOOP( + "Exceptions", + "Knot multiplicity cannot be higher than the degree of the BSpline.")); if (param > lastParam || param < firstParam) - THROWMT(Base::ValueError,QT_TRANSLATE_NOOP("Exceptions", "Knot cannot be inserted outside the BSpline parameter range.")); + THROWMT(Base::ValueError, + QT_TRANSLATE_NOOP("Exceptions", + "Knot cannot be inserted outside the BSpline parameter range.")); std::unique_ptr bspline; // run the command try { - bspline.reset(static_cast(bsp->clone())); + bspline.reset(static_cast(bsp->clone())); - bspline->insertKnot(param, multiplicity); + bspline->insertKnot(param, multiplicity); } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); - return false; + Base::Console().Error("%s\n", e.what()); + return false; } // once command is run update the internal geometries @@ -6079,13 +6555,13 @@ bool SketchObject::insertBSplineKnot(int GeoId, double param, int multiplicity) std::vector newpoles = bspline->getPoles(); std::vector prevpole(bsp->countPoles()); - for(int i = 0; i < int(poles.size()); i++) + for (int i = 0; i < int(poles.size()); i++) prevpole[i] = -1; int taken = 0; - for(int j = 0; j < int(poles.size()); j++){ - for(int i = taken; i < int(newpoles.size()); i++){ - if( newpoles[i] == poles[j] ) { + for (int j = 0; j < int(poles.size()); j++) { + for (int i = taken; i < int(newpoles.size()); i++) { + if (newpoles[i] == poles[j]) { prevpole[j] = i; taken++; break; @@ -6098,13 +6574,13 @@ bool SketchObject::insertBSplineKnot(int GeoId, double param, int multiplicity) std::vector newknots = bspline->getKnots(); std::vector prevknot(bsp->countKnots()); - for(int i = 0; i < int(knots.size()); i++) + for (int i = 0; i < int(knots.size()); i++) prevknot[i] = -1; taken = 0; - for(int j = 0; j < int(knots.size()); j++){ - for(int i = taken; i < int(newknots.size()); i++){ - if( newknots[i] == knots[j] ) { + for (int j = 0; j < int(knots.size()); j++) { + for (int i = taken; i < int(newknots.size()); i++) { + if (newknots[i] == knots[j]) { prevknot[j] = i; taken++; break; @@ -6112,37 +6588,42 @@ bool SketchObject::insertBSplineKnot(int GeoId, double param, int multiplicity) } } - const std::vector< Sketcher::Constraint * > &cvals = Constraints.getValues(); + const std::vector& cvals = Constraints.getValues(); - std::vector< Constraint * > newcVals(0); + std::vector newcVals(0); // modify pole constraints - for (std::vector< Sketcher::Constraint * >::const_iterator it= cvals.begin(); it != cvals.end(); ++it) { - if((*it)->Type == Sketcher::InternalAlignment && (*it)->Second == GeoId) - { - if((*it)->AlignmentType == Sketcher::BSplineControlPoint) { - if (prevpole[(*it)->InternalAlignmentIndex]!=-1) { + for (std::vector::const_iterator it = cvals.begin(); it != cvals.end(); + ++it) { + if ((*it)->Type == Sketcher::InternalAlignment && (*it)->Second == GeoId) { + if ((*it)->AlignmentType == Sketcher::BSplineControlPoint) { + if (prevpole[(*it)->InternalAlignmentIndex] != -1) { assert(prevpole[(*it)->InternalAlignmentIndex] < bspline->countPoles()); - Constraint * newConstr = (*it)->clone(); + Constraint* newConstr = (*it)->clone(); newConstr->InternalAlignmentIndex = prevpole[(*it)->InternalAlignmentIndex]; newcVals.push_back(newConstr); } - else { // it is an internal alignment geometry that is no longer valid => delete it and the pole circle + else { + // it is an internal alignment geometry that is no longer valid => delete it and + // the pole circle delGeoId.push_back((*it)->First); } } - else if((*it)->AlignmentType == Sketcher::BSplineKnotPoint) { - if (prevknot[(*it)->InternalAlignmentIndex]!=-1) { + else if ((*it)->AlignmentType == Sketcher::BSplineKnotPoint) { + if (prevknot[(*it)->InternalAlignmentIndex] != -1) { assert(prevknot[(*it)->InternalAlignmentIndex] < bspline->countKnots()); - Constraint * newConstr = (*it)->clone(); + Constraint* newConstr = (*it)->clone(); newConstr->InternalAlignmentIndex = prevknot[(*it)->InternalAlignmentIndex]; newcVals.push_back(newConstr); } - else { // it is an internal alignment geometry that is no longer valid => delete it and the knot point + else { + // it is an internal alignment geometry that is no longer valid => delete it and + // the knot point delGeoId.push_back((*it)->First); } } - else { // it is a bspline geometry, but not a controlpoint or knot + else { + // it is a bspline geometry, but not a controlpoint or knot newcVals.push_back(*it); } } @@ -6151,9 +6632,9 @@ bool SketchObject::insertBSplineKnot(int GeoId, double param, int multiplicity) } } - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); - std::vector< Part::Geometry * > newVals(vals); + std::vector newVals(vals); newVals[GeoId] = bspline.release(); @@ -6166,10 +6647,12 @@ bool SketchObject::insertBSplineKnot(int GeoId, double param, int multiplicity) } // Trigger update now - // Update geometry indices and rebuild vertexindex now via onChanged, so that ViewProvider::UpdateData is triggered. + // Update geometry indices and rebuild vertexindex now via onChanged, so that + // ViewProvider::UpdateData is triggered. if (!delGeoId.empty()) { // NOTE: There have been a couple of instances when knot insertion has - // led to a segmentation fault: see https://forum.freecad.org/viewtopic.php?f=19&t=64962&sid=10272db50a635c633260517b14ecad37. + // led to a segmentation fault: see + // https://forum.freecad.org/viewtopic.php?f=19&t=64962&sid=10272db50a635c633260517b14ecad37. // If a segfault happens again and a `Geometry.touch()` here fixes it, // it is possible that `delGeometriesExclusiveList` is causing an update // in constraint GUI features during an intermediate step. @@ -6185,9 +6668,10 @@ bool SketchObject::insertBSplineKnot(int GeoId, double param, int multiplicity) return true; } -int SketchObject::carbonCopy(App::DocumentObject * pObj, bool construction) +int SketchObject::carbonCopy(App::DocumentObject* pObj, bool construction) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); // so far only externals to the support of the sketch and datum features bool xinv = false, yinv = false; @@ -6195,15 +6679,15 @@ int SketchObject::carbonCopy(App::DocumentObject * pObj, bool construction) if (!isCarbonCopyAllowed(pObj->getDocument(), pObj, xinv, yinv)) return -1; - SketchObject * psObj = static_cast(pObj); + SketchObject* psObj = static_cast(pObj); - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); - const std::vector< Sketcher::Constraint * > &cvals = Constraints.getValues(); + const std::vector& cvals = Constraints.getValues(); - std::vector< Part::Geometry * > newVals(vals); + std::vector newVals(vals); - std::vector< Constraint * > newcVals(cvals); + std::vector newcVals(cvals); int nextgeoid = vals.size(); @@ -6211,35 +6695,38 @@ int SketchObject::carbonCopy(App::DocumentObject * pObj, bool construction) int nextcid = cvals.size(); - const std::vector< Part::Geometry * > &svals = psObj->getInternalGeometry(); + const std::vector& svals = psObj->getInternalGeometry(); - const std::vector< Sketcher::Constraint * > &scvals = psObj->Constraints.getValues(); + const std::vector& scvals = psObj->Constraints.getValues(); - newVals.reserve(vals.size()+svals.size()); - newcVals.reserve(cvals.size()+scvals.size()); + newVals.reserve(vals.size() + svals.size()); + newcVals.reserve(cvals.size() + scvals.size()); - if(psObj->ExternalGeometry.getSize()>0) { - std::vector Objects = ExternalGeometry.getValues(); - std::vector SubElements = ExternalGeometry.getSubValues(); + if (psObj->ExternalGeometry.getSize() > 0) { + std::vector Objects = ExternalGeometry.getValues(); + std::vector SubElements = ExternalGeometry.getSubValues(); const std::vector originalObjects = Objects; - const std::vector originalSubElements = SubElements; + const std::vector originalSubElements = SubElements; - std::vector sObjects = psObj->ExternalGeometry.getValues(); - std::vector sSubElements = psObj->ExternalGeometry.getSubValues(); + std::vector sObjects = psObj->ExternalGeometry.getValues(); + std::vector sSubElements = psObj->ExternalGeometry.getSubValues(); if (Objects.size() != SubElements.size() || sObjects.size() != sSubElements.size()) { assert(0 /*counts of objects and subelements in external geometry links do not match*/); - Base::Console().Error("Internal error: counts of objects and subelements in external geometry links do not match\n"); + Base::Console().Error("Internal error: counts of objects and subelements in external " + "geometry links do not match\n"); return -1; } - int si=0; - for (auto & sobj : sObjects) { - int i=0; - for (auto & obj : Objects){ - if (obj == sobj && SubElements[i] == sSubElements[si]){ - Base::Console().Error("Link to %s already exists in this sketch. Delete the link and try again\n",sSubElements[si].c_str()); + int si = 0; + for (auto& sobj : sObjects) { + int i = 0; + for (auto& obj : Objects) { + if (obj == sobj && SubElements[i] == sSubElements[si]) { + Base::Console().Error( + "Link to %s already exists in this sketch. Delete the link and try again\n", + sSubElements[si].c_str()); return -1; } @@ -6252,7 +6739,7 @@ int SketchObject::carbonCopy(App::DocumentObject * pObj, bool construction) si++; } - ExternalGeometry.setValues(Objects,SubElements); + ExternalGeometry.setValues(Objects, SubElements); try { rebuildExternalGeometry(); @@ -6260,36 +6747,37 @@ int SketchObject::carbonCopy(App::DocumentObject * pObj, bool construction) catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); // revert to original values - ExternalGeometry.setValues(originalObjects,originalSubElements); + ExternalGeometry.setValues(originalObjects, originalSubElements); return -1; } - solverNeedsUpdate=true; + solverNeedsUpdate = true; } - for (std::vector::const_iterator it=svals.begin(); it != svals.end(); ++it){ - Part::Geometry *geoNew = (*it)->copy(); - if(construction && geoNew->getTypeId() != Part::GeomPoint::getClassTypeId()) { + for (std::vector::const_iterator it = svals.begin(); it != svals.end(); ++it) { + Part::Geometry* geoNew = (*it)->copy(); + if (construction && geoNew->getTypeId() != Part::GeomPoint::getClassTypeId()) { GeometryFacade::setConstruction(geoNew, true); } newVals.push_back(geoNew); } - for (std::vector< Sketcher::Constraint * >::const_iterator it= scvals.begin(); it != scvals.end(); ++it) { - Sketcher::Constraint *newConstr = (*it)->copy(); - if( (*it)->First>=0 ) + for (std::vector::const_iterator it = scvals.begin(); it != scvals.end(); + ++it) { + Sketcher::Constraint* newConstr = (*it)->copy(); + if ((*it)->First >= 0) newConstr->First += nextgeoid; - if( (*it)->Second>=0 ) + if ((*it)->Second >= 0) newConstr->Second += nextgeoid; - if( (*it)->Third>=0 ) + if ((*it)->Third >= 0) newConstr->Third += nextgeoid; - if( (*it)->First<-2 && (*it)->First != GeoEnum::GeoUndef ) - newConstr->First -= (nextextgeoid-2); - if( (*it)->Second<-2 && (*it)->Second != GeoEnum::GeoUndef) - newConstr->Second -= (nextextgeoid-2); - if( (*it)->Third<-2 && (*it)->Third != GeoEnum::GeoUndef) - newConstr->Third -= (nextextgeoid-2); + if ((*it)->First < -2 && (*it)->First != GeoEnum::GeoUndef) + newConstr->First -= (nextextgeoid - 2); + if ((*it)->Second < -2 && (*it)->Second != GeoEnum::GeoUndef) + newConstr->Second -= (nextextgeoid - 2); + if ((*it)->Third < -2 && (*it)->Third != GeoEnum::GeoUndef) + newConstr->Third -= (nextextgeoid - 2); newcVals.push_back(newConstr); } @@ -6301,11 +6789,13 @@ int SketchObject::carbonCopy(App::DocumentObject * pObj, bool construction) this->Constraints.setValues(std::move(newcVals)); } // we trigger now the update (before dealing with expressions) - // Update geometry indices and rebuild vertexindex now via onChanged, so that ViewProvider::UpdateData is triggered. + // Update geometry indices and rebuild vertexindex now via onChanged, so that + // ViewProvider::UpdateData is triggered. Geometry.touch(); int sourceid = 0; - for (std::vector< Sketcher::Constraint * >::const_iterator it= scvals.begin(); it != scvals.end(); ++it, nextcid++, sourceid++) { + for (std::vector::const_iterator it = scvals.begin(); it != scvals.end(); + ++it, nextcid++, sourceid++) { if ((*it)->isDimensional()) { // then we link its value to the parent @@ -6313,20 +6803,27 @@ int SketchObject::carbonCopy(App::DocumentObject * pObj, bool construction) App::ObjectIdentifier spath; std::shared_ptr expr; std::string scname = (*it)->Name; - if ( App::ExpressionParser::isTokenAnIndentifier(scname) ) { - spath = App::ObjectIdentifier(psObj->Constraints) << App::ObjectIdentifier::SimpleComponent(scname); - expr = std::shared_ptr(App::Expression::parse(this, spath.getDocumentObjectName().getString() + spath.toString())); + if (App::ExpressionParser::isTokenAnIndentifier(scname)) { + spath = App::ObjectIdentifier(psObj->Constraints) + << App::ObjectIdentifier::SimpleComponent(scname); + expr = std::shared_ptr(App::Expression::parse( + this, spath.getDocumentObjectName().getString() + spath.toString())); } else { spath = psObj->Constraints.createPath(sourceid); - expr = std::shared_ptr(App::Expression::parse(this, spath.getDocumentObjectName().getString() +std::string(1,'.') + spath.toString())); + expr = std::shared_ptr( + App::Expression::parse(this, + spath.getDocumentObjectName().getString() + + std::string(1, '.') + spath.toString())); } - // (there is a plausible alternative for a slightly different use case to copy the expression of the parent if one is existing) + // (there is a plausible alternative for a slightly different use case to copy the + // expression of the parent if one is existing) /* - * App::PropertyExpressionEngine::ExpressionInfo expr_info = psObj->getExpression(path); + * App::PropertyExpressionEngine::ExpressionInfo expr_info = + * psObj->getExpression(path); * * if (expr_info.expression)*/ - //App::Expression * expr = parse(this, const std::string& buffer); + // App::Expression * expr = parse(this, const std::string& buffer); setExpression(Constraints.createPath(nextcid), expr); } } @@ -6335,30 +6832,32 @@ int SketchObject::carbonCopy(App::DocumentObject * pObj, bool construction) return svals.size(); } -int SketchObject::addExternal(App::DocumentObject *Obj, const char* SubName) +int SketchObject::addExternal(App::DocumentObject* Obj, const char* SubName) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); // so far only externals to the support of the sketch and datum features if (!isExternalAllowed(Obj->getDocument(), Obj)) - return -1; + return -1; // get the actual lists of the externals - std::vector Objects = ExternalGeometry.getValues(); - std::vector SubElements = ExternalGeometry.getSubValues(); + std::vector Objects = ExternalGeometry.getValues(); + std::vector SubElements = ExternalGeometry.getSubValues(); const std::vector originalObjects = Objects; - const std::vector originalSubElements = SubElements; + const std::vector originalSubElements = SubElements; if (Objects.size() != SubElements.size()) { assert(0 /*counts of objects and subelements in external geometry links do not match*/); - Base::Console().Error("Internal error: counts of objects and subelements in external geometry links do not match\n"); + Base::Console().Error("Internal error: counts of objects and subelements in external " + "geometry links do not match\n"); return -1; } - for (size_t i = 0 ; i < Objects.size() ; ++i){ - if (Objects[i] == Obj && std::string(SubName) == SubElements[i]){ - Base::Console().Error("Link to %s already exists in this sketch.\n",SubName); + for (size_t i = 0; i < Objects.size(); ++i) { + if (Objects[i] == Obj && std::string(SubName) == SubElements[i]) { + Base::Console().Error("Link to %s already exists in this sketch.\n", SubName); return -1; } } @@ -6368,61 +6867,59 @@ int SketchObject::addExternal(App::DocumentObject *Obj, const char* SubName) SubElements.emplace_back(SubName); // set the Link list. - ExternalGeometry.setValues(Objects,SubElements); + ExternalGeometry.setValues(Objects, SubElements); try { rebuildExternalGeometry(); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); // revert to original values - ExternalGeometry.setValues(originalObjects,originalSubElements); + ExternalGeometry.setValues(originalObjects, originalSubElements); return -1; } - acceptGeometry(); // This may need to be refactored into onChanged for ExternalGeometry + acceptGeometry();// This may need to be refactored into onChanged for ExternalGeometry - solverNeedsUpdate=true; - return ExternalGeometry.getValues().size()-1; + solverNeedsUpdate = true; + return ExternalGeometry.getValues().size() - 1; } int SketchObject::delExternal(int ExtGeoId) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); // get the actual lists of the externals - std::vector Objects = ExternalGeometry.getValues(); - std::vector SubElements = ExternalGeometry.getSubValues(); + std::vector Objects = ExternalGeometry.getValues(); + std::vector SubElements = ExternalGeometry.getSubValues(); if (ExtGeoId < 0 || ExtGeoId >= int(SubElements.size())) return -1; const std::vector originalObjects = Objects; - const std::vector originalSubElements = SubElements; + const std::vector originalSubElements = SubElements; - Objects.erase(Objects.begin()+ExtGeoId); - SubElements.erase(SubElements.begin()+ExtGeoId); + Objects.erase(Objects.begin() + ExtGeoId); + SubElements.erase(SubElements.begin() + ExtGeoId); - const std::vector< Constraint * > &constraints = Constraints.getValues(); - std::vector< Constraint * > newConstraints; - std::vector< Constraint * > copiedConstraints; + const std::vector& constraints = Constraints.getValues(); + std::vector newConstraints; + std::vector copiedConstraints; int GeoId = GeoEnum::RefExt - ExtGeoId; for (auto cstr : constraints) { if (cstr->First != GeoId && cstr->Second != GeoId && cstr->Third != GeoId) { auto copiedConstr = cstr; - if (copiedConstr->First < GeoId && - copiedConstr->First != GeoEnum::GeoUndef) { + if (copiedConstr->First < GeoId && copiedConstr->First != GeoEnum::GeoUndef) { if (cstr == copiedConstr) copiedConstr = cstr->clone(); copiedConstr->First += 1; } - if (copiedConstr->Second < GeoId && - copiedConstr->Second != GeoEnum::GeoUndef) { + if (copiedConstr->Second < GeoId && copiedConstr->Second != GeoEnum::GeoUndef) { if (cstr == copiedConstr) copiedConstr = cstr->clone(); copiedConstr->Second += 1; } - if (copiedConstr->Third < GeoId && - copiedConstr->Third != GeoEnum::GeoUndef) { + if (copiedConstr->Third < GeoId && copiedConstr->Third != GeoEnum::GeoUndef) { if (cstr == copiedConstr) copiedConstr = cstr->clone(); copiedConstr->Third += 1; @@ -6434,86 +6931,86 @@ int SketchObject::delExternal(int ExtGeoId) } } - ExternalGeometry.setValues(Objects,SubElements); + ExternalGeometry.setValues(Objects, SubElements); try { rebuildExternalGeometry(); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); // revert to original values - ExternalGeometry.setValues(originalObjects,originalSubElements); + ExternalGeometry.setValues(originalObjects, originalSubElements); for (Constraint* it : copiedConstraints) delete it; return -1; } - solverNeedsUpdate=true; + solverNeedsUpdate = true; Constraints.setValues(std::move(newConstraints)); - acceptGeometry(); // This may need to be refactored into OnChanged for ExternalGeometry. + acceptGeometry();// This may need to be refactored into OnChanged for ExternalGeometry. return 0; } int SketchObject::delAllExternal() { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); // get the actual lists of the externals - std::vector Objects = ExternalGeometry.getValues(); - std::vector SubElements = ExternalGeometry.getSubValues(); + std::vector Objects = ExternalGeometry.getValues(); + std::vector SubElements = ExternalGeometry.getSubValues(); const std::vector originalObjects = Objects; - const std::vector originalSubElements = SubElements; + const std::vector originalSubElements = SubElements; Objects.clear(); SubElements.clear(); - const std::vector< Constraint * > &constraints = Constraints.getValues(); - std::vector< Constraint * > newConstraints(0); + const std::vector& constraints = Constraints.getValues(); + std::vector newConstraints(0); - for (std::vector::const_iterator it = constraints.begin(); it != constraints.end(); ++it) { - if ((*it)->First > GeoEnum::RefExt && - ((*it)->Second > GeoEnum::RefExt || (*it)->Second == GeoEnum::GeoUndef ) && - ((*it)->Third > GeoEnum::RefExt || (*it)->Third == GeoEnum::GeoUndef) ) { - Constraint *copiedConstr = (*it)->clone(); + for (std::vector::const_iterator it = constraints.begin(); it != constraints.end(); + ++it) { + if ((*it)->First > GeoEnum::RefExt + && ((*it)->Second > GeoEnum::RefExt || (*it)->Second == GeoEnum::GeoUndef) + && ((*it)->Third > GeoEnum::RefExt || (*it)->Third == GeoEnum::GeoUndef)) { + Constraint* copiedConstr = (*it)->clone(); newConstraints.push_back(copiedConstr); } } - ExternalGeometry.setValues(Objects,SubElements); + ExternalGeometry.setValues(Objects, SubElements); try { rebuildExternalGeometry(); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); // revert to original values - ExternalGeometry.setValues(originalObjects,originalSubElements); + ExternalGeometry.setValues(originalObjects, originalSubElements); for (Constraint* it : newConstraints) delete it; return -1; } - solverNeedsUpdate=true; + solverNeedsUpdate = true; Constraints.setValues(std::move(newConstraints)); - acceptGeometry(); // This may need to be refactored into OnChanged for ExternalGeometry + acceptGeometry();// This may need to be refactored into OnChanged for ExternalGeometry return 0; } int SketchObject::delConstraintsToExternal() { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - const std::vector< Constraint * > &constraints = Constraints.getValuesForce(); - std::vector< Constraint * > newConstraints(0); + const std::vector& constraints = Constraints.getValuesForce(); + std::vector newConstraints(0); int GeoId = GeoEnum::RefExt, NullId = GeoEnum::GeoUndef; - for (std::vector::const_iterator it = constraints.begin(); - it != constraints.end(); ++it) { - if ( (*it)->First > GeoId - && - ((*it)->Second > GeoId || (*it)->Second == NullId) - && - ((*it)->Third > GeoId || (*it)->Third == NullId)) { + for (std::vector::const_iterator it = constraints.begin(); it != constraints.end(); + ++it) { + if ((*it)->First > GeoId && ((*it)->Second > GeoId || (*it)->Second == NullId) + && ((*it)->Third > GeoId || (*it)->Third == NullId)) { newConstraints.push_back(*it); } } @@ -6521,7 +7018,8 @@ int SketchObject::delConstraintsToExternal() Constraints.setValues(std::move(newConstraints)); Constraints.acceptGeometry(getCompleteGeometry()); - if(noRecomputes) // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + // if we do not have a recompute, the sketch must be solved to update the DoF of the solver + if (noRecomputes) solve(); return 0; @@ -6534,20 +7032,19 @@ int SketchObject::getCompleteGeometryIndex(int GeoId) const return GeoId; } else if (-GeoId <= int(ExternalGeo.size())) - return -GeoId-1; + return -GeoId - 1; return GeoEnum::GeoUndef; } int SketchObject::getGeoIdFromCompleteGeometryIndex(int completeGeometryIndex) const { - int completeGeometryCount = int(Geometry.getSize()+ExternalGeo.size()); + int completeGeometryCount = int(Geometry.getSize() + ExternalGeo.size()); - if(completeGeometryIndex < 0 || - completeGeometryIndex >= completeGeometryCount) + if (completeGeometryIndex < 0 || completeGeometryIndex >= completeGeometryCount) return GeoEnum::GeoUndef; - if(completeGeometryIndex < Geometry.getSize()) + if (completeGeometryIndex < Geometry.getSize()) return completeGeometryIndex; else return (completeGeometryIndex - completeGeometryCount); @@ -6559,17 +7056,16 @@ std::unique_ptr SketchObject::getGeometryFacade(int GeoId) } // Auxiliary Method: returns vector projection in UV space of plane -static gp_Vec2d ProjVecOnPlane_UV( const gp_Vec& V, const gp_Pln& Pl) +static gp_Vec2d ProjVecOnPlane_UV(const gp_Vec& V, const gp_Pln& Pl) { - return gp_Vec2d( V.Dot(Pl.Position().XDirection()), - V.Dot(Pl.Position().YDirection())); + return gp_Vec2d(V.Dot(Pl.Position().XDirection()), V.Dot(Pl.Position().YDirection())); } // Auxiliary Method: returns vector projection in UVN space of plane -static gp_Vec ProjVecOnPlane_UVN( const gp_Vec& V, const gp_Pln& Pl) +static gp_Vec ProjVecOnPlane_UVN(const gp_Vec& V, const gp_Pln& Pl) { - gp_Vec2d vector = ProjVecOnPlane_UV(V, Pl); - return gp_Vec(vector.X(), vector.Y(), 0.0); + gp_Vec2d vector = ProjVecOnPlane_UV(V, Pl); + return gp_Vec(vector.X(), vector.Y(), 0.0); } // Auxiliary Method: returns vector projection in XYZ space @@ -6582,28 +7078,31 @@ static gp_Vec ProjVecOnPlane_XYZ( const gp_Vec& V, const gp_Pln& Pl) #endif // Auxiliary Method: returns point projection in UV space of plane -static gp_Vec2d ProjPointOnPlane_UV( const gp_Pnt& P, const gp_Pln& Pl) +static gp_Vec2d ProjPointOnPlane_UV(const gp_Pnt& P, const gp_Pln& Pl) { - gp_Vec OP = gp_Vec(Pl.Location(), P); - return ProjVecOnPlane_UV(OP, Pl); + gp_Vec OP = gp_Vec(Pl.Location(), P); + return ProjVecOnPlane_UV(OP, Pl); } // Auxiliary Method: returns point projection in UVN space of plane static gp_Vec ProjPointOnPlane_UVN(const gp_Pnt& P, const gp_Pln& Pl) { - gp_Vec2d vec2 = ProjPointOnPlane_UV(P, Pl); - return gp_Vec(vec2.X(), vec2.Y(), 0.0); + gp_Vec2d vec2 = ProjPointOnPlane_UV(P, Pl); + return gp_Vec(vec2.X(), vec2.Y(), 0.0); } // Auxiliary Method: returns point projection in XYZ space static gp_Pnt ProjPointOnPlane_XYZ(const gp_Pnt& P, const gp_Pln& Pl) { - gp_Vec positionUVN = ProjPointOnPlane_UVN(P, Pl); - return gp_Pnt((positionUVN.X() * Pl.Position().XDirection() + positionUVN.Y() * Pl.Position().YDirection() + gp_Vec(Pl.Location().XYZ())).XYZ()); + gp_Vec positionUVN = ProjPointOnPlane_UVN(P, Pl); + return gp_Pnt((positionUVN.X() * Pl.Position().XDirection() + + positionUVN.Y() * Pl.Position().YDirection() + gp_Vec(Pl.Location().XYZ())) + .XYZ()); } // Auxiliary method -Part::Geometry* projectLine(const BRepAdaptor_Curve& curve, const Handle(Geom_Plane)& gPlane, const Base::Placement& invPlm) +Part::Geometry* projectLine(const BRepAdaptor_Curve& curve, const Handle(Geom_Plane) & gPlane, + const Base::Placement& invPlm) { double first = curve.FirstParameter(); @@ -6622,17 +7121,17 @@ Part::Geometry* projectLine(const BRepAdaptor_Curve& curve, const Handle(Geom_Pl gp_Pnt P1 = curve.Value(first); gp_Pnt P2 = curve.Value(last); - GeomAPI_ProjectPointOnSurf proj1(P1,gPlane); + GeomAPI_ProjectPointOnSurf proj1(P1, gPlane); P1 = proj1.NearestPoint(); - GeomAPI_ProjectPointOnSurf proj2(P2,gPlane); + GeomAPI_ProjectPointOnSurf proj2(P2, gPlane); P2 = proj2.NearestPoint(); - Base::Vector3d p1(P1.X(),P1.Y(),P1.Z()); - Base::Vector3d p2(P2.X(),P2.Y(),P2.Z()); - invPlm.multVec(p1,p1); - invPlm.multVec(p2,p2); + Base::Vector3d p1(P1.X(), P1.Y(), P1.Z()); + Base::Vector3d p2(P2.X(), P2.Y(), P2.Z()); + invPlm.multVec(p1, p1); + invPlm.multVec(p2, p2); - if (Base::Distance(p1,p2) < Precision::Confusion()) { + if (Base::Distance(p1, p2) < Precision::Confusion()) { Base::Vector3d p = (p1 + p2) / 2; Part::GeomPoint* point = new Part::GeomPoint(p); GeometryFacade::setConstruction(point, true); @@ -6640,7 +7139,7 @@ Part::Geometry* projectLine(const BRepAdaptor_Curve& curve, const Handle(Geom_Pl } else { Part::GeomLineSegment* line = new Part::GeomLineSegment(); - line->setPoints(p1,p2); + line->setPoints(p1, p2); GeometryFacade::setConstruction(line, true); return line; } @@ -6649,7 +7148,7 @@ Part::Geometry* projectLine(const BRepAdaptor_Curve& curve, const Handle(Geom_Pl bool SketchObject::evaluateSupport() { // returns false if the shape is broken, null or non-planar - App::DocumentObject *link = Support.getValue(); + App::DocumentObject* link = Support.getValue(); if (!link || !link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) return false; return true; @@ -6657,16 +7156,17 @@ bool SketchObject::evaluateSupport() void SketchObject::validateExternalLinks() { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - std::vector Objects = ExternalGeometry.getValues(); - std::vector SubElements = ExternalGeometry.getSubValues(); + std::vector Objects = ExternalGeometry.getValues(); + std::vector SubElements = ExternalGeometry.getSubValues(); bool rebuild = false; - for (int i=0; i < int(Objects.size()); i++) { - const App::DocumentObject *Obj=Objects[i]; - const std::string SubElement=SubElements[i]; + for (int i = 0; i < int(Objects.size()); i++) { + const App::DocumentObject* Obj = Objects[i]; + const std::string SubElement = SubElements[i]; TopoDS_Shape refSubShape; try { @@ -6675,31 +7175,29 @@ void SketchObject::validateExternalLinks() refSubShape = datum->getShape(); } else { - const Part::Feature *refObj=static_cast(Obj); - const Part::TopoShape& refShape=refObj->Shape.getShape(); + const Part::Feature* refObj = static_cast(Obj); + const Part::TopoShape& refShape = refObj->Shape.getShape(); refSubShape = refShape.getSubShape(SubElement.c_str()); } } catch (Standard_Failure&) { - rebuild = true ; - Objects.erase(Objects.begin()+i); - SubElements.erase(SubElements.begin()+i); + rebuild = true; + Objects.erase(Objects.begin() + i); + SubElements.erase(SubElements.begin() + i); - const std::vector< Constraint * > &constraints = Constraints.getValues(); - std::vector< Constraint * > newConstraints(0); + const std::vector& constraints = Constraints.getValues(); + std::vector newConstraints(0); int GeoId = GeoEnum::RefExt - i; - for (std::vector::const_iterator it = constraints.begin(); - it != constraints.end(); ++it) { + for (std::vector::const_iterator it = constraints.begin(); + it != constraints.end(); + ++it) { if ((*it)->First != GeoId && (*it)->Second != GeoId && (*it)->Third != GeoId) { - Constraint *copiedConstr = (*it)->clone(); - if (copiedConstr->First < GeoId && - copiedConstr->First != GeoEnum::GeoUndef) + Constraint* copiedConstr = (*it)->clone(); + if (copiedConstr->First < GeoId && copiedConstr->First != GeoEnum::GeoUndef) copiedConstr->First += 1; - if (copiedConstr->Second < GeoId && - copiedConstr->Second != GeoEnum::GeoUndef) + if (copiedConstr->Second < GeoId && copiedConstr->Second != GeoEnum::GeoUndef) copiedConstr->Second += 1; - if (copiedConstr->Third < GeoId && - copiedConstr->Third != GeoEnum::GeoUndef) + if (copiedConstr->Third < GeoId && copiedConstr->Third != GeoEnum::GeoUndef) copiedConstr->Third += 1; newConstraints.push_back(copiedConstr); @@ -6707,100 +7205,113 @@ void SketchObject::validateExternalLinks() } Constraints.setValues(std::move(newConstraints)); - i--; // we deleted an item, so the next one took its place + i--;// we deleted an item, so the next one took its place } } if (rebuild) { - ExternalGeometry.setValues(Objects,SubElements); + ExternalGeometry.setValues(Objects, SubElements); rebuildExternalGeometry(); - acceptGeometry(); // This may need to be refactor to OnChanged for ExternalGeo - solve(true); // we have to update this sketch and everything depending on it. + acceptGeometry();// This may need to be refactor to OnChanged for ExternalGeo + solve(true); // we have to update this sketch and everything depending on it. } } void SketchObject::rebuildExternalGeometry() { // get the actual lists of the externals - std::vector Objects = ExternalGeometry.getValues(); - std::vector SubElements = ExternalGeometry.getSubValues(); + std::vector Objects = ExternalGeometry.getValues(); + std::vector SubElements = ExternalGeometry.getSubValues(); Base::Placement Plm = Placement.getValue(); Base::Vector3d Pos = Plm.getPosition(); Base::Rotation Rot = Plm.getRotation(); Base::Rotation invRot = Rot.inverse(); - Base::Vector3d dN(0,0,1); - Rot.multVec(dN,dN); - Base::Vector3d dX(1,0,0); - Rot.multVec(dX,dX); + Base::Vector3d dN(0, 0, 1); + Rot.multVec(dN, dN); + Base::Vector3d dX(1, 0, 0); + Rot.multVec(dX, dX); Base::Placement invPlm = Plm.inverse(); Base::Matrix4D invMat = invPlm.toMatrix(); gp_Trsf mov; - mov.SetValues(invMat[0][0],invMat[0][1],invMat[0][2],invMat[0][3], - invMat[1][0],invMat[1][1],invMat[1][2],invMat[1][3], - invMat[2][0],invMat[2][1],invMat[2][2],invMat[2][3]); + mov.SetValues(invMat[0][0], + invMat[0][1], + invMat[0][2], + invMat[0][3], + invMat[1][0], + invMat[1][1], + invMat[1][2], + invMat[1][3], + invMat[2][0], + invMat[2][1], + invMat[2][2], + invMat[2][3]); - gp_Ax3 sketchAx3(gp_Pnt(Pos.x,Pos.y,Pos.z), - gp_Dir(dN.x,dN.y,dN.z), - gp_Dir(dX.x,dX.y,dX.z)); + gp_Ax3 sketchAx3( + gp_Pnt(Pos.x, Pos.y, Pos.z), gp_Dir(dN.x, dN.y, dN.z), gp_Dir(dX.x, dX.y, dX.z)); gp_Pln sketchPlane(sketchAx3); Handle(Geom_Plane) gPlane = new Geom_Plane(sketchPlane); BRepBuilderAPI_MakeFace mkFace(sketchPlane); TopoDS_Shape aProjFace = mkFace.Shape(); - for (std::vector::iterator it=ExternalGeo.begin(); it != ExternalGeo.end(); ++it) - if (*it) delete *it; + for (std::vector::iterator it = ExternalGeo.begin(); it != ExternalGeo.end(); + ++it) + if (*it) + delete *it; ExternalGeo.clear(); - Part::GeomLineSegment *HLine = new Part::GeomLineSegment(); - Part::GeomLineSegment *VLine = new Part::GeomLineSegment(); - HLine->setPoints(Base::Vector3d(0,0,0),Base::Vector3d(1,0,0)); - VLine->setPoints(Base::Vector3d(0,0,0),Base::Vector3d(0,1,0)); + Part::GeomLineSegment* HLine = new Part::GeomLineSegment(); + Part::GeomLineSegment* VLine = new Part::GeomLineSegment(); + HLine->setPoints(Base::Vector3d(0, 0, 0), Base::Vector3d(1, 0, 0)); + VLine->setPoints(Base::Vector3d(0, 0, 0), Base::Vector3d(0, 1, 0)); GeometryFacade::setConstruction(HLine, true); GeometryFacade::setConstruction(VLine, true); ExternalGeo.push_back(HLine); ExternalGeo.push_back(VLine); - for (int i=0; i < int(Objects.size()); i++) { - const App::DocumentObject *Obj=Objects[i]; - const std::string SubElement=SubElements[i]; + for (int i = 0; i < int(Objects.size()); i++) { + const App::DocumentObject* Obj = Objects[i]; + const std::string SubElement = SubElements[i]; TopoDS_Shape refSubShape; if (Obj->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId())) { const Part::Datum* datum = static_cast(Obj); refSubShape = datum->getShape(); - } else if (Obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) { + } + else if (Obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) { try { - const Part::Feature *refObj=static_cast(Obj); - const Part::TopoShape& refShape=refObj->Shape.getShape(); + const Part::Feature* refObj = static_cast(Obj); + const Part::TopoShape& refShape = refObj->Shape.getShape(); refSubShape = refShape.getSubShape(SubElement.c_str()); } catch (Standard_Failure& e) { throw Base::CADKernelError(e.GetMessageString()); } - } else if (Obj->getTypeId().isDerivedFrom(App::Plane::getClassTypeId())) { + } + else if (Obj->getTypeId().isDerivedFrom(App::Plane::getClassTypeId())) { const App::Plane* pl = static_cast(Obj); Base::Placement plm = pl->Placement.getValue(); Base::Vector3d base = plm.getPosition(); Base::Rotation rot = plm.getRotation(); - Base::Vector3d normal(0,0,1); + Base::Vector3d normal(0, 0, 1); rot.multVec(normal, normal); - gp_Pln plane(gp_Pnt(base.x,base.y,base.z), gp_Dir(normal.x, normal.y, normal.z)); + gp_Pln plane(gp_Pnt(base.x, base.y, base.z), gp_Dir(normal.x, normal.y, normal.z)); BRepBuilderAPI_MakeFace fBuilder(plane); if (!fBuilder.IsDone()) - throw Base::RuntimeError("Sketcher: addExternal(): Failed to build face from App::Plane"); + throw Base::RuntimeError( + "Sketcher: addExternal(): Failed to build face from App::Plane"); TopoDS_Face f = TopoDS::Face(fBuilder.Shape()); refSubShape = f; - } else { - throw Base::TypeError("Datum feature type is not yet supported as external geometry for a sketch"); + } + else { + throw Base::TypeError( + "Datum feature type is not yet supported as external geometry for a sketch"); } - switch (refSubShape.ShapeType()) - { - case TopAbs_FACE: - { + switch (refSubShape.ShapeType()) { + case TopAbs_FACE: { const TopoDS_Face& face = TopoDS::Face(refSubShape); BRepAdaptor_Surface surface(face); if (surface.GetType() == GeomAbs_Plane) { @@ -6809,7 +7320,8 @@ void SketchObject::rebuildExternalGeometry() gp_Dir dnormal = plane.Axis().Direction(); gp_Dir snormal = sketchPlane.Axis().Direction(); if (fabs(dnormal.Angle(snormal) - M_PI_2) < Precision::Confusion()) { - // Get vector that is normal to both sketch plane normal and plane normal. This is the line's direction + // Get vector that is normal to both sketch plane normal and plane normal. + // This is the line's direction gp_Dir lnormal = dnormal.Crossed(snormal); BRepBuilderAPI_MakeEdge builder(gp_Lin(plane.Location(), lnormal)); builder.Build(); @@ -6820,17 +7332,18 @@ void SketchObject::rebuildExternalGeometry() ExternalGeo.push_back(projectLine(curve, gPlane, invPlm)); } } - - } else { - throw Base::ValueError("Selected external reference plane must be normal to sketch plane"); } - } else { - throw Base::ValueError("Non-planar faces are not yet supported for external geometry of sketches"); + else { + throw Base::ValueError( + "Selected external reference plane must be normal to sketch plane"); + } } - } - break; - case TopAbs_EDGE: - { + else { + throw Base::ValueError( + "Non-planar faces are not yet supported for external geometry of sketches"); + } + } break; + case TopAbs_EDGE: { const TopoDS_Edge& edge = TopoDS::Edge(refSubShape); BRepAdaptor_Curve curve(edge); if (curve.GetType() == GeomAbs_Line) { @@ -6845,7 +7358,7 @@ void SketchObject::rebuildExternalGeometry() gp_Pnt beg = curve.Value(curve.FirstParameter()); gp_Pnt end = curve.Value(curve.LastParameter()); - GeomAPI_ProjectPointOnSurf proj(cnt,gPlane); + GeomAPI_ProjectPointOnSurf proj(cnt, gPlane); cnt = proj.NearestPoint(); circle.SetLocation(cnt); cnt.Transform(mov); @@ -6854,7 +7367,7 @@ void SketchObject::rebuildExternalGeometry() if (beg.SquareDistance(end) < Precision::Confusion()) { Part::GeomCircle* gCircle = new Part::GeomCircle(); gCircle->setRadius(circle.Radius()); - gCircle->setCenter(Base::Vector3d(cnt.X(),cnt.Y(),cnt.Z())); + gCircle->setCenter(Base::Vector3d(cnt.X(), cnt.Y(), cnt.Z())); GeometryFacade::setConstruction(gCircle, true); ExternalGeo.push_back(gCircle); @@ -6862,8 +7375,8 @@ void SketchObject::rebuildExternalGeometry() else { Part::GeomArcOfCircle* gArc = new Part::GeomArcOfCircle(); Handle(Geom_Curve) hCircle = new Geom_Circle(circle); - Handle(Geom_TrimmedCurve) tCurve = new Geom_TrimmedCurve(hCircle, curve.FirstParameter(), - curve.LastParameter()); + Handle(Geom_TrimmedCurve) tCurve = new Geom_TrimmedCurve( + hCircle, curve.FirstParameter(), curve.LastParameter()); gArc->setHandle(tCurve); GeometryFacade::setConstruction(gArc, true); ExternalGeo.push_back(gArc); @@ -6876,121 +7389,151 @@ void SketchObject::rebuildExternalGeometry() gp_Dir vec2 = curve.Circle().Axis().Direction(); gp_Circ origCircle = curve.Circle(); - if (vec1.IsNormal(vec2, Precision::Angular())) { // circle's normal vector in plane: + if (vec1.IsNormal( + vec2, Precision::Angular())) {// circle's normal vector in plane: // projection is a line // define center by projection gp_Pnt cnt = origCircle.Location(); - GeomAPI_ProjectPointOnSurf proj(cnt,gPlane); + GeomAPI_ProjectPointOnSurf proj(cnt, gPlane); cnt = proj.NearestPoint(); gp_Dir dirOrientation = gp_Dir(vec1 ^ vec2); gp_Dir dirLine(dirOrientation); - Part::GeomLineSegment * projectedSegment = new Part::GeomLineSegment(); - Geom_Line ligne(cnt, dirLine); // helper object to compute end points - gp_Pnt P1, P2; // end points of the segment, OCC style + Part::GeomLineSegment* projectedSegment = new Part::GeomLineSegment(); + Geom_Line ligne(cnt, dirLine);// helper object to compute end points + gp_Pnt P1, P2; // end points of the segment, OCC style ligne.D0(-origCircle.Radius(), P1); - ligne.D0( origCircle.Radius(), P2); + ligne.D0(origCircle.Radius(), P2); - if (!curve.IsClosed()) { // arc of circle + if (!curve.IsClosed()) {// arc of circle - gp_Pnt pntF = curve.Value(curve.FirstParameter()); // start point of arc of circle - gp_Pnt pntL = curve.Value(curve.LastParameter()); // end point of arc of circle + // start point of arc of circle + gp_Pnt pntF = curve.Value(curve.FirstParameter()); + // end point of arc of circle + gp_Pnt pntL = curve.Value(curve.LastParameter()); - double alpha = dirOrientation.AngleWithRef(curve.Circle().XAxis().Direction(), curve.Circle().Axis().Direction()); + double alpha = + dirOrientation.AngleWithRef(curve.Circle().XAxis().Direction(), + curve.Circle().Axis().Direction()); double baseAngle = curve.FirstParameter(); int tours = 0; double startAngle = baseAngle + alpha; // bring startAngle back in [-pi/2 , 3pi/2[ - while(startAngle < -M_PI/2.0 && tours < 10) { - startAngle = baseAngle + ++tours*2.0*M_PI + alpha; + while (startAngle < -M_PI / 2.0 && tours < 10) { + startAngle = baseAngle + ++tours * 2.0 * M_PI + alpha; } - while(startAngle >= 3.0*M_PI/2.0 && tours > -10) { - startAngle = baseAngle + --tours*2.0*M_PI + alpha; + while (startAngle >= 3.0 * M_PI / 2.0 && tours > -10) { + startAngle = baseAngle + --tours * 2.0 * M_PI + alpha; } - double endAngle = curve.LastParameter() + startAngle - baseAngle; // apply same offset to end angle + // apply same offset to end angle + double endAngle = curve.LastParameter() + startAngle - baseAngle; if (startAngle <= 0.0) { if (endAngle <= 0.0) { P1 = ProjPointOnPlane_XYZ(pntF, sketchPlane); P2 = ProjPointOnPlane_XYZ(pntL, sketchPlane); - } else { + } + else { if (endAngle <= fabs(startAngle)) { // P2 = P2 already defined P1 = ProjPointOnPlane_XYZ(pntF, sketchPlane); - } else if (endAngle < M_PI) { + } + else if (endAngle < M_PI) { // P2 = P2, already defined P1 = ProjPointOnPlane_XYZ(pntL, sketchPlane); - } else { + } + else { // P1 = P1, already defined // P2 = P2, already defined } } - } else if (startAngle < M_PI) { + } + else if (startAngle < M_PI) { if (endAngle < M_PI) { P1 = ProjPointOnPlane_XYZ(pntF, sketchPlane); P2 = ProjPointOnPlane_XYZ(pntL, sketchPlane); - } else if (endAngle < 2.0 * M_PI - startAngle) { + } + else if (endAngle < 2.0 * M_PI - startAngle) { P2 = ProjPointOnPlane_XYZ(pntF, sketchPlane); // P1 = P1, already defined - } else if (endAngle < 2.0 * M_PI) { + } + else if (endAngle < 2.0 * M_PI) { P2 = ProjPointOnPlane_XYZ(pntL, sketchPlane); // P1 = P1, already defined - } else { + } + else { // P1 = P1, already defined // P2 = P2, already defined } - } else { - if (endAngle < 2*M_PI) { + } + else { + if (endAngle < 2 * M_PI) { P1 = ProjPointOnPlane_XYZ(pntF, sketchPlane); P2 = ProjPointOnPlane_XYZ(pntL, sketchPlane); - } else if (endAngle < 4*M_PI - startAngle) { + } + else if (endAngle < 4 * M_PI - startAngle) { P1 = ProjPointOnPlane_XYZ(pntF, sketchPlane); // P2 = P2, already defined - } else if (endAngle < 3*M_PI) { + } + else if (endAngle < 3 * M_PI) { // P1 = P1, already defined P2 = ProjPointOnPlane_XYZ(pntL, sketchPlane); - } else { + } + else { // P1 = P1, already defined // P2 = P2, already defined } } } - Base::Vector3d p1(P1.X(),P1.Y(),P1.Z()); // ends of segment FCAD style - Base::Vector3d p2(P2.X(),P2.Y(),P2.Z()); - invPlm.multVec(p1,p1); - invPlm.multVec(p2,p2); + Base::Vector3d p1(P1.X(), P1.Y(), P1.Z());// ends of segment FCAD style + Base::Vector3d p2(P2.X(), P2.Y(), P2.Z()); + invPlm.multVec(p1, p1); + invPlm.multVec(p2, p2); projectedSegment->setPoints(p1, p2); GeometryFacade::setConstruction(projectedSegment, true); ExternalGeo.push_back(projectedSegment); } - else { // general case, full circle + else {// general case, full circle gp_Pnt cnt = origCircle.Location(); - GeomAPI_ProjectPointOnSurf proj(cnt,gPlane); - cnt = proj.NearestPoint(); // projection of circle center on sketch plane, 3D space - Base::Vector3d p(cnt.X(),cnt.Y(),cnt.Z()); // converting to FCAD style vector - invPlm.multVec(p,p); // transforming towards sketch's (x,y) coordinates + GeomAPI_ProjectPointOnSurf proj(cnt, gPlane); + // projection of circle center on sketch plane, 3D space + cnt = proj.NearestPoint(); + // converting to FCAD style vector + Base::Vector3d p(cnt.X(), cnt.Y(), cnt.Z()); + // transforming towards sketch's (x,y) coordinates + invPlm.multVec(p, p); - gp_Vec vecMajorAxis = vec1 ^ vec2; // major axis in 3D space + gp_Vec vecMajorAxis = vec1 ^ vec2;// major axis in 3D space - double minorRadius; // TODO use data type of vectors around... + double minorRadius;// TODO use data type of vectors around... double cosTheta; - cosTheta = fabs(vec1.Dot(vec2)); // cos of angle between the two planes, assuming vectirs are normalized to 1 + // cos of angle between the two planes, assuming vectirs are normalized + // to 1 + cosTheta = fabs(vec1.Dot(vec2)); minorRadius = origCircle.Radius() * cosTheta; - Base::Vector3d vectorMajorAxis(vecMajorAxis.X(),vecMajorAxis.Y(),vecMajorAxis.Z()); // maj axis into FCAD style vector - invRot.multVec(vectorMajorAxis, vectorMajorAxis); // transforming to sketch's (x,y) coordinates - vecMajorAxis.SetXYZ(gp_XYZ(vectorMajorAxis[0], vectorMajorAxis[1], vectorMajorAxis[2])); // back to OCC + // maj axis into FCAD style vector + Base::Vector3d vectorMajorAxis( + vecMajorAxis.X(), vecMajorAxis.Y(), vecMajorAxis.Z()); + // transforming to sketch's (x,y) coordinates + invRot.multVec(vectorMajorAxis, vectorMajorAxis); + // back to OCC + vecMajorAxis.SetXYZ( + gp_XYZ(vectorMajorAxis[0], vectorMajorAxis[1], vectorMajorAxis[2])); - gp_Ax2 refFrameEllipse(gp_Pnt(gp_XYZ(p[0], p[1], p[2])), gp_Vec(0, 0, 1), vecMajorAxis); // NB: force normal of ellipse to be normal of sketch's plane. - Handle(Geom_Ellipse) curve = new Geom_Ellipse(refFrameEllipse, origCircle.Radius(), minorRadius); + // NB: force normal of ellipse to be normal of sketch's plane. + gp_Ax2 refFrameEllipse( + gp_Pnt(gp_XYZ(p[0], p[1], p[2])), gp_Vec(0, 0, 1), vecMajorAxis); + Handle(Geom_Ellipse) curve = + new Geom_Ellipse(refFrameEllipse, origCircle.Radius(), minorRadius); Part::GeomEllipse* ellipse = new Part::GeomEllipse(); ellipse->setHandle(curve); GeometryFacade::setConstruction(ellipse, true); @@ -7011,12 +7554,14 @@ void SketchObject::rebuildExternalGeometry() gp_Dir origAxisMinorDir = elipsOrig.YAxis().Direction(); gp_Vec origAxisMinor = elipsOrig.MinorRadius() * gp_Vec(origAxisMinorDir); - // Here, it used to be a test for parallel direction between the sketchplane and the elipsOrig, in which - // the original ellipse would be copied and translated to the new position. - // The problem with that approach is that for the sketcher the normal vector is always (0,0,1). If the original - // ellipse was not on the XY plane, the copy will not be either. Then, the dimensions would be wrong because of the - // different major axis direction (which is not projected on the XY plane). So here, we default to the more general - // ellipse construction algorithm. + // Here, it used to be a test for parallel direction between the sketchplane and + // the elipsOrig, in which the original ellipse would be copied and translated + // to the new position. The problem with that approach is that for the sketcher + // the normal vector is always (0,0,1). If the original ellipse was not on the + // XY plane, the copy will not be either. Then, the dimensions would be wrong + // because of the different major axis direction (which is not projected on the + // XY plane). So here, we default to the more general ellipse construction + // algorithm. // // Doing that solves: // https://forum.freecad.org/viewtopic.php?f=3&t=55284#p477522 @@ -7032,7 +7577,7 @@ void SketchObject::rebuildExternalGeometry() gp_Vec2d PA = ProjVecOnPlane_UV(origAxisMajor, sketchPlane); gp_Vec2d PB = ProjVecOnPlane_UV(origAxisMinor, sketchPlane); double t_max = 2.0 * PA.Dot(PB) / (PA.SquareMagnitude() - PB.SquareMagnitude()); - t_max = 0.5 * atan(t_max); // gives new major axis is most cases, but not all + t_max = 0.5 * atan(t_max);// gives new major axis is most cases, but not all double t_min = t_max + 0.5 * M_PI; // ON_max = OM(t_max) gives the point, which projected on the sketch plane, @@ -7055,12 +7600,13 @@ void SketchObject::rebuildExternalGeometry() } double sens = sketchAx3.Direction().Dot(elipsOrig.Position().Direction()); - gp_Ax2 destCurveAx2(destCenter, - gp_Dir(0, 0, sens > 0.0 ? 1.0 : -1.0), - gp_Dir(destAxisMajor)); + gp_Ax2 destCurveAx2( + destCenter, gp_Dir(0, 0, sens > 0.0 ? 1.0 : -1.0), gp_Dir(destAxisMajor)); - if ((RDest - rDest) < (double) Precision::Confusion()) { // projection is a circle - Handle(Geom_Circle) curve = new Geom_Circle(destCurveAx2, 0.5 * (rDest + RDest)); + // projection is a circle + if ((RDest - rDest) < (double)Precision::Confusion()) { + Handle(Geom_Circle) curve = + new Geom_Circle(destCurveAx2, 0.5 * (rDest + RDest)); Part::GeomCircle* circle = new Part::GeomCircle(); circle->setHandle(curve); GeometryFacade::setConstruction(circle, true); @@ -7068,13 +7614,15 @@ void SketchObject::rebuildExternalGeometry() ExternalGeo.push_back(circle); } else { - if (sketchPlane.Position().Direction().IsNormal(elipsOrig.Position().Direction(), Precision::Angular())) { + if (sketchPlane.Position().Direction().IsNormal( + elipsOrig.Position().Direction(), Precision::Angular())) { gp_Vec start = gp_Vec(destCenter.XYZ()) + destAxisMajor; gp_Vec end = gp_Vec(destCenter.XYZ()) - destAxisMajor; - Part::GeomLineSegment * projectedSegment = new Part::GeomLineSegment(); - projectedSegment->setPoints(Base::Vector3d(start.X(), start.Y(), start.Z()), - Base::Vector3d(end.X(), end.Y(), end.Z())); + Part::GeomLineSegment* projectedSegment = new Part::GeomLineSegment(); + projectedSegment->setPoints( + Base::Vector3d(start.X(), start.Y(), start.Z()), + Base::Vector3d(end.X(), end.Y(), end.Z())); GeometryFacade::setConstruction(projectedSegment, true); ExternalGeo.push_back(projectedSegment); } @@ -7110,10 +7658,10 @@ void SketchObject::rebuildExternalGeometry() if (projCurve.GetType() == GeomAbs_Line) { gp_Pnt P1 = projCurve.Value(projCurve.FirstParameter()); gp_Pnt P2 = projCurve.Value(projCurve.LastParameter()); - Base::Vector3d p1(P1.X(),P1.Y(),P1.Z()); - Base::Vector3d p2(P2.X(),P2.Y(),P2.Z()); + Base::Vector3d p1(P1.X(), P1.Y(), P1.Z()); + Base::Vector3d p2(P2.X(), P2.Y(), P2.Z()); - if (Base::Distance(p1,p2) < Precision::Confusion()) { + if (Base::Distance(p1, p2) < Precision::Confusion()) { Base::Vector3d p = (p1 + p2) / 2; Part::GeomPoint* point = new Part::GeomPoint(p); GeometryFacade::setConstruction(point, true); @@ -7121,7 +7669,7 @@ void SketchObject::rebuildExternalGeometry() } else { Part::GeomLineSegment* line = new Part::GeomLineSegment(); - line->setPoints(p1,p2); + line->setPoints(p1, p2); GeometryFacade::setConstruction(line, true); ExternalGeo.push_back(line); } @@ -7135,7 +7683,7 @@ void SketchObject::rebuildExternalGeometry() if (P1.SquareDistance(P2) < Precision::Confusion()) { Part::GeomCircle* circle = new Part::GeomCircle(); circle->setRadius(c.Radius()); - circle->setCenter(Base::Vector3d(p.X(),p.Y(),p.Z())); + circle->setCenter(Base::Vector3d(p.X(), p.Y(), p.Z())); GeometryFacade::setConstruction(circle, true); ExternalGeo.push_back(circle); @@ -7143,18 +7691,23 @@ void SketchObject::rebuildExternalGeometry() else { Part::GeomArcOfCircle* arc = new Part::GeomArcOfCircle(); Handle(Geom_Curve) curve = new Geom_Circle(c); - Handle(Geom_TrimmedCurve) tCurve = new Geom_TrimmedCurve(curve, projCurve.FirstParameter(), - projCurve.LastParameter()); + Handle(Geom_TrimmedCurve) tCurve = + new Geom_TrimmedCurve(curve, + projCurve.FirstParameter(), + projCurve.LastParameter()); arc->setHandle(tCurve); GeometryFacade::setConstruction(arc, true); ExternalGeo.push_back(arc); } - } else if (projCurve.GetType() == GeomAbs_BSplineCurve) { - // Unfortunately, a normal projection of a circle can also give a Bspline - // Split the spline into arcs - GeomConvert_BSplineCurveKnotSplitting bSplineSplitter(projCurve.BSpline(), 2); - //int s = bSplineSplitter.NbSplits(); - if ((curve.GetType() == GeomAbs_Circle) && (bSplineSplitter.NbSplits() == 2)) { + } + else if (projCurve.GetType() == GeomAbs_BSplineCurve) { + // Unfortunately, a normal projection of a circle can also give + // a Bspline Split the spline into arcs + GeomConvert_BSplineCurveKnotSplitting bSplineSplitter( + projCurve.BSpline(), 2); + // int s = bSplineSplitter.NbSplits(); + if ((curve.GetType() == GeomAbs_Circle) + && (bSplineSplitter.NbSplits() == 2)) { // Result of projection is actually a circle... TColStd_Array1OfInteger splits(1, 2); bSplineSplitter.Splitting(splits); @@ -7166,16 +7719,20 @@ void SketchObject::rebuildExternalGeometry() Part::GeomCircle* circle = new Part::GeomCircle(); circle->setRadius(circ->Radius()); gp_Pnt center = circ->Axis().Location(); - circle->setCenter(Base::Vector3d(center.X(), center.Y(), center.Z())); + circle->setCenter( + Base::Vector3d(center.X(), center.Y(), center.Z())); GeometryFacade::setConstruction(circle, true); ExternalGeo.push_back(circle); - } else { - Part::GeomBSplineCurve* bspline = new Part::GeomBSplineCurve(projCurve.BSpline()); + } + else { + Part::GeomBSplineCurve* bspline = + new Part::GeomBSplineCurve(projCurve.BSpline()); GeometryFacade::setConstruction(bspline, true); ExternalGeo.push_back(bspline); } - } else if (projCurve.GetType() == GeomAbs_Hyperbola) { + } + else if (projCurve.GetType() == GeomAbs_Hyperbola) { gp_Hypr e = projCurve.Hyperbola(); gp_Pnt p = e.Location(); gp_Pnt P1 = projCurve.Value(projCurve.FirstParameter()); @@ -7189,21 +7746,26 @@ void SketchObject::rebuildExternalGeometry() Part::GeomHyperbola* hyperbola = new Part::GeomHyperbola(); hyperbola->setMajorRadius(e.MajorRadius()); hyperbola->setMinorRadius(e.MinorRadius()); - hyperbola->setCenter(Base::Vector3d(p.X(),p.Y(),p.Z())); - hyperbola->setAngleXU(-xdir.AngleWithRef(xdirref.XDirection(),normal)); + hyperbola->setCenter(Base::Vector3d(p.X(), p.Y(), p.Z())); + hyperbola->setAngleXU( + -xdir.AngleWithRef(xdirref.XDirection(), normal)); GeometryFacade::setConstruction(hyperbola, true); ExternalGeo.push_back(hyperbola); } else { - Part::GeomArcOfHyperbola* aoh = new Part::GeomArcOfHyperbola(); + Part::GeomArcOfHyperbola* aoh = + new Part::GeomArcOfHyperbola(); Handle(Geom_Curve) curve = new Geom_Hyperbola(e); - Handle(Geom_TrimmedCurve) tCurve = new Geom_TrimmedCurve(curve, projCurve.FirstParameter(), - projCurve.LastParameter()); + Handle(Geom_TrimmedCurve) tCurve = + new Geom_TrimmedCurve(curve, + projCurve.FirstParameter(), + projCurve.LastParameter()); aoh->setHandle(tCurve); GeometryFacade::setConstruction(aoh, true); ExternalGeo.push_back(aoh); } - } else if (projCurve.GetType() == GeomAbs_Parabola) { + } + else if (projCurve.GetType() == GeomAbs_Parabola) { gp_Parab e = projCurve.Parabola(); gp_Pnt p = e.Location(); gp_Pnt P1 = projCurve.Value(projCurve.FirstParameter()); @@ -7216,16 +7778,20 @@ void SketchObject::rebuildExternalGeometry() if (P1.SquareDistance(P2) < Precision::Confusion()) { Part::GeomParabola* parabola = new Part::GeomParabola(); parabola->setFocal(e.Focal()); - parabola->setCenter(Base::Vector3d(p.X(),p.Y(),p.Z())); - parabola->setAngleXU(-xdir.AngleWithRef(xdirref.XDirection(),normal)); + parabola->setCenter(Base::Vector3d(p.X(), p.Y(), p.Z())); + parabola->setAngleXU( + -xdir.AngleWithRef(xdirref.XDirection(), normal)); GeometryFacade::setConstruction(parabola, true); ExternalGeo.push_back(parabola); } else { - Part::GeomArcOfParabola* aop = new Part::GeomArcOfParabola(); + Part::GeomArcOfParabola* aop = + new Part::GeomArcOfParabola(); Handle(Geom_Curve) curve = new Geom_Parabola(e); - Handle(Geom_TrimmedCurve) tCurve = new Geom_TrimmedCurve(curve, projCurve.FirstParameter(), - projCurve.LastParameter()); + Handle(Geom_TrimmedCurve) tCurve = + new Geom_TrimmedCurve(curve, + projCurve.FirstParameter(), + projCurve.LastParameter()); aop->setHandle(tCurve); GeometryFacade::setConstruction(aop, true); ExternalGeo.push_back(aop); @@ -7237,8 +7803,8 @@ void SketchObject::rebuildExternalGeometry() gp_Pnt P1 = projCurve.Value(projCurve.FirstParameter()); gp_Pnt P2 = projCurve.Value(projCurve.LastParameter()); - //gp_Dir normal = e.Axis().Direction(); - gp_Dir normal = gp_Dir(0,0,1); + // gp_Dir normal = e.Axis().Direction(); + gp_Dir normal = gp_Dir(0, 0, 1); gp_Ax2 xdirref(p, normal); if (P1.SquareDistance(P2) < Precision::Confusion()) { @@ -7251,15 +7817,18 @@ void SketchObject::rebuildExternalGeometry() else { Part::GeomArcOfEllipse* aoe = new Part::GeomArcOfEllipse(); Handle(Geom_Curve) curve = new Geom_Ellipse(e); - Handle(Geom_TrimmedCurve) tCurve = new Geom_TrimmedCurve(curve, projCurve.FirstParameter(), - projCurve.LastParameter()); + Handle(Geom_TrimmedCurve) tCurve = + new Geom_TrimmedCurve(curve, + projCurve.FirstParameter(), + projCurve.LastParameter()); aoe->setHandle(tCurve); GeometryFacade::setConstruction(aoe, true); ExternalGeo.push_back(aoe); } } else { - throw Base::NotImplementedError("Not yet supported geometry for external geometry"); + throw Base::NotImplementedError( + "Not yet supported geometry for external geometry"); } } } @@ -7268,24 +7837,21 @@ void SketchObject::rebuildExternalGeometry() throw Base::CADKernelError(e.GetMessageString()); } } - } - break; - case TopAbs_VERTEX: - { + } break; + case TopAbs_VERTEX: { gp_Pnt P = BRep_Tool::Pnt(TopoDS::Vertex(refSubShape)); - GeomAPI_ProjectPointOnSurf proj(P,gPlane); + GeomAPI_ProjectPointOnSurf proj(P, gPlane); P = proj.NearestPoint(); - Base::Vector3d p(P.X(),P.Y(),P.Z()); - invPlm.multVec(p,p); + Base::Vector3d p(P.X(), P.Y(), P.Z()); + invPlm.multVec(p, p); Part::GeomPoint* point = new Part::GeomPoint(p); GeometryFacade::setConstruction(point, true); ExternalGeo.push_back(point); - } - break; - default: - throw Base::TypeError("Unknown type of geometry"); - break; + } break; + default: + throw Base::TypeError("Unknown type of geometry"); + break; } } @@ -7295,19 +7861,19 @@ void SketchObject::rebuildExternalGeometry() std::vector SketchObject::getCompleteGeometry() const { std::vector vals = getInternalGeometry(); - vals.insert(vals.end(), ExternalGeo.rbegin(), ExternalGeo.rend()); // in reverse order + vals.insert(vals.end(), ExternalGeo.rbegin(), ExternalGeo.rend());// in reverse order return vals; } GeoListFacade SketchObject::getGeoListFacade() const { std::vector facade; - facade.reserve( Geometry.getSize() + ExternalGeo.size() ); + facade.reserve(Geometry.getSize() + ExternalGeo.size()); - for(auto geo : Geometry.getValues()) + for (auto geo : Geometry.getValues()) facade.push_back(GeometryFacade::getFacade(geo)); - for(auto rit = ExternalGeo.rbegin(); rit != ExternalGeo.rend(); rit++) + for (auto rit = ExternalGeo.rbegin(); rit != ExternalGeo.rend(); rit++) facade.push_back(GeometryFacade::getFacade(*rit)); return GeoListFacade::getGeoListModel(std::move(facade), Geometry.getSize()); @@ -7317,58 +7883,67 @@ void SketchObject::rebuildVertexIndex() { VertexId2GeoId.resize(0); VertexId2PosId.resize(0); - int imax=getHighestCurveIndex(); - int i=0; - const std::vector< Part::Geometry * > geometry = getCompleteGeometry(); + int imax = getHighestCurveIndex(); + int i = 0; + const std::vector geometry = getCompleteGeometry(); if (geometry.size() <= 2) return; - for (std::vector< Part::Geometry * >::const_iterator it = geometry.begin(); - it != geometry.end()-2; ++it, i++) { + for (std::vector::const_iterator it = geometry.begin(); + it != geometry.end() - 2; + ++it, i++) { if (i > imax) - i = -getExternalGeometryCount(); + i = -getExternalGeometryCount(); if ((*it)->getTypeId() == Part::GeomPoint::getClassTypeId()) { VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::start); - } else if ((*it)->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + } + else if ((*it)->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::start); VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::end); - } else if ((*it)->getTypeId() == Part::GeomCircle::getClassTypeId()) { + } + else if ((*it)->getTypeId() == Part::GeomCircle::getClassTypeId()) { VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::mid); - } else if ((*it)->getTypeId() == Part::GeomEllipse::getClassTypeId()) { + } + else if ((*it)->getTypeId() == Part::GeomEllipse::getClassTypeId()) { VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::mid); - } else if ((*it)->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + } + else if ((*it)->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::start); VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::end); VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::mid); - } else if ((*it)->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { + } + else if ((*it)->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::start); VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::end); VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::mid); - } else if ((*it)->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + } + else if ((*it)->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::start); VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::end); VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::mid); - } else if ((*it)->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + } + else if ((*it)->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::start); VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::end); VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::mid); - } else if ((*it)->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { + } + else if ((*it)->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { VertexId2GeoId.push_back(i); VertexId2PosId.push_back(PointPos::start); VertexId2GeoId.push_back(i); @@ -7377,109 +7952,126 @@ void SketchObject::rebuildVertexIndex() } } -const std::vector< std::map > SketchObject::getCoincidenceGroups() +const std::vector> SketchObject::getCoincidenceGroups() { // this function is different from that in getCoincidentPoints in that: - // - getCoincidentPoints only considers direct coincidence (the points that are linked via a single coincidence) - // - this function provides an array of maps of points, each map containing the points that are coincident by virtue - // of any number of interrelated coincidence constraints (if coincidence 1-2 and coincidence 2-3, {1,2,3} are in that set) + // - getCoincidentPoints only considers direct coincidence (the points that are linked via a + // single coincidence) + // - this function provides an array of maps of points, each map containing the points that are + // coincident by virtue + // of any number of interrelated coincidence constraints (if coincidence 1-2 and coincidence + // 2-3, {1,2,3} are in that set) - const std::vector< Sketcher::Constraint * > &vals = Constraints.getValues(); + const std::vector& vals = Constraints.getValues(); - std::vector< std::map > coincidenttree; + std::vector> coincidenttree; // push the constraints - for (std::vector< Sketcher::Constraint * >::const_iterator it= vals.begin();it != vals.end(); ++it) { - if( (*it)->Type == Sketcher::Coincident ) { - int firstpresentin=-1; - int secondpresentin=-1; + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); + ++it) { + if ((*it)->Type == Sketcher::Coincident) { + int firstpresentin = -1; + int secondpresentin = -1; - int i=0; + int i = 0; - for(std::vector< std::map >::const_iterator iti = coincidenttree.begin(); iti != coincidenttree.end(); ++iti,i++) { + for (std::vector>::const_iterator iti = + coincidenttree.begin(); + iti != coincidenttree.end(); + ++iti, i++) { // First std::map::const_iterator filiterator; filiterator = (*iti).find((*it)->First); - if( filiterator != (*iti).end()) { - if((*it)->FirstPos == (*filiterator).second) + if (filiterator != (*iti).end()) { + if ((*it)->FirstPos == (*filiterator).second) firstpresentin = i; } // Second filiterator = (*iti).find((*it)->Second); - if( filiterator != (*iti).end()) { - if((*it)->SecondPos == (*filiterator).second) + if (filiterator != (*iti).end()) { + if ((*it)->SecondPos == (*filiterator).second) secondpresentin = i; } } - if ( firstpresentin!=-1 && secondpresentin!=-1) { + if (firstpresentin != -1 && secondpresentin != -1) { // we have to merge those sets into one - coincidenttree[firstpresentin].insert(coincidenttree[secondpresentin].begin(), coincidenttree[secondpresentin].end()); - coincidenttree.erase(coincidenttree.begin()+secondpresentin); + coincidenttree[firstpresentin].insert(coincidenttree[secondpresentin].begin(), + coincidenttree[secondpresentin].end()); + coincidenttree.erase(coincidenttree.begin() + secondpresentin); } - else if ( firstpresentin==-1 && secondpresentin==-1 ) { + else if (firstpresentin == -1 && secondpresentin == -1) { // we do not have any of the values, so create a setCursor std::map tmp; - tmp.insert(std::pair((*it)->First,(*it)->FirstPos)); - tmp.insert(std::pair((*it)->Second,(*it)->SecondPos)); + tmp.insert(std::pair((*it)->First, (*it)->FirstPos)); + tmp.insert(std::pair((*it)->Second, (*it)->SecondPos)); coincidenttree.push_back(tmp); } - else if ( firstpresentin != -1 ) { + else if (firstpresentin != -1) { // add to existing group - coincidenttree[firstpresentin].insert(std::pair((*it)->Second,(*it)->SecondPos)); + coincidenttree[firstpresentin].insert( + std::pair((*it)->Second, (*it)->SecondPos)); } - else { // secondpresentin != -1 + else {// secondpresentin != -1 // add to existing group - coincidenttree[secondpresentin].insert(std::pair((*it)->First,(*it)->FirstPos)); + coincidenttree[secondpresentin].insert( + std::pair((*it)->First, (*it)->FirstPos)); } - } } return coincidenttree; } -void SketchObject::isCoincidentWithExternalGeometry(int GeoId, bool &start_external, bool &mid_external, bool &end_external) { +void SketchObject::isCoincidentWithExternalGeometry(int GeoId, bool& start_external, + bool& mid_external, bool& end_external) +{ - start_external=false; - mid_external=false; - end_external=false; + start_external = false; + mid_external = false; + end_external = false; - const std::vector< std::map > coincidenttree = getCoincidenceGroups(); + const std::vector> coincidenttree = getCoincidenceGroups(); - for(std::vector< std::map >::const_iterator it = coincidenttree.begin(); it != coincidenttree.end(); ++it) { + for (std::vector>::const_iterator it = coincidenttree.begin(); + it != coincidenttree.end(); + ++it) { std::map::const_iterator geoId1iterator; geoId1iterator = (*it).find(GeoId); - if( geoId1iterator != (*it).end()) { + if (geoId1iterator != (*it).end()) { // If First is in this set and the first key in this ordered element key is external - if( (*it).begin()->first < 0 ) { - if( (*geoId1iterator).second == Sketcher::PointPos::start ) - start_external=true; - else if ( (*geoId1iterator).second == Sketcher::PointPos::mid ) - mid_external=true; - else if ( (*geoId1iterator).second == Sketcher::PointPos::end ) - end_external=true; + if ((*it).begin()->first < 0) { + if ((*geoId1iterator).second == Sketcher::PointPos::start) + start_external = true; + else if ((*geoId1iterator).second == Sketcher::PointPos::mid) + mid_external = true; + else if ((*geoId1iterator).second == Sketcher::PointPos::end) + end_external = true; } } } } -const std::map SketchObject::getAllCoincidentPoints(int GeoId, PointPos PosId) { +const std::map SketchObject::getAllCoincidentPoints(int GeoId, + PointPos PosId) +{ - const std::vector< std::map > coincidenttree = getCoincidenceGroups(); + const std::vector> coincidenttree = getCoincidenceGroups(); - for(std::vector< std::map >::const_iterator it = coincidenttree.begin(); it != coincidenttree.end(); ++it) { + for (std::vector>::const_iterator it = coincidenttree.begin(); + it != coincidenttree.end(); + ++it) { std::map::const_iterator geoId1iterator; geoId1iterator = (*it).find(GeoId); - if( geoId1iterator != (*it).end()) { + if (geoId1iterator != (*it).end()) { // If GeoId is in this set - if ((*geoId1iterator).second == PosId) // and posId matches + if ((*geoId1iterator).second == PosId)// and posId matches return (*it); } } @@ -7490,17 +8082,18 @@ const std::map SketchObject::getAllCoincidentPoints(int } -void SketchObject::getDirectlyCoincidentPoints(int GeoId, PointPos PosId, std::vector &GeoIdList, - std::vector &PosIdList) +void SketchObject::getDirectlyCoincidentPoints(int GeoId, PointPos PosId, + std::vector& GeoIdList, + std::vector& PosIdList) { - const std::vector &constraints = this->Constraints.getValues(); + const std::vector& constraints = this->Constraints.getValues(); GeoIdList.clear(); PosIdList.clear(); GeoIdList.push_back(GeoId); PosIdList.push_back(PosId); - for (std::vector::const_iterator it=constraints.begin(); - it != constraints.end(); ++it) { + for (std::vector::const_iterator it = constraints.begin(); it != constraints.end(); + ++it) { if ((*it)->Type == Sketcher::Coincident) { if ((*it)->First == GeoId && (*it)->FirstPos == PosId) { GeoIdList.push_back((*it)->Second); @@ -7518,8 +8111,8 @@ void SketchObject::getDirectlyCoincidentPoints(int GeoId, PointPos PosId, std::v } } -void SketchObject::getDirectlyCoincidentPoints(int VertexId, std::vector &GeoIdList, - std::vector &PosIdList) +void SketchObject::getDirectlyCoincidentPoints(int VertexId, std::vector& GeoIdList, + std::vector& PosIdList) { int GeoId; PointPos PosId; @@ -7527,30 +8120,30 @@ void SketchObject::getDirectlyCoincidentPoints(int VertexId, std::vector &G getDirectlyCoincidentPoints(GeoId, PosId, GeoIdList, PosIdList); } -bool SketchObject::arePointsCoincident(int GeoId1, PointPos PosId1, - int GeoId2, PointPos PosId2) +bool SketchObject::arePointsCoincident(int GeoId1, PointPos PosId1, int GeoId2, PointPos PosId2) { if (GeoId1 == GeoId2 && PosId1 == PosId2) return true; - const std::vector< std::map > coincidenttree = getCoincidenceGroups(); + const std::vector> coincidenttree = getCoincidenceGroups(); - for(std::vector< std::map >::const_iterator it = coincidenttree.begin(); it != coincidenttree.end(); ++it) { + for (std::vector>::const_iterator it = coincidenttree.begin(); + it != coincidenttree.end(); + ++it) { std::map::const_iterator geoId1iterator; geoId1iterator = (*it).find(GeoId1); - if( geoId1iterator != (*it).end()) { + if (geoId1iterator != (*it).end()) { // If First is in this set std::map::const_iterator geoId2iterator; geoId2iterator = (*it).find(GeoId2); - if( geoId2iterator != (*it).end()) { + if (geoId2iterator != (*it).end()) { // If Second is in this set - if ((*geoId1iterator).second == PosId1 && - (*geoId2iterator).second == PosId2) + if ((*geoId1iterator).second == PosId1 && (*geoId2iterator).second == PosId2) return true; } } @@ -7559,20 +8152,21 @@ bool SketchObject::arePointsCoincident(int GeoId1, PointPos PosId1, return false; } -void SketchObject::getConstraintIndices (int GeoId, std::vector &constraintList) +void SketchObject::getConstraintIndices(int GeoId, std::vector& constraintList) { - const std::vector &constraints = this->Constraints.getValues(); + const std::vector& constraints = this->Constraints.getValues(); int i = 0; - for (std::vector::const_iterator it = constraints.begin(); it != constraints.end(); ++it) { - if ((*it)->First == GeoId || (*it)->Second == GeoId || (*it)->Third == GeoId) { - constraintList.push_back(i); - } - ++i; + for (std::vector::const_iterator it = constraints.begin(); it != constraints.end(); + ++it) { + if ((*it)->First == GeoId || (*it)->Second == GeoId || (*it)->Third == GeoId) { + constraintList.push_back(i); + } + ++i; } } -void SketchObject::appendConflictMsg(const std::vector &conflicting, std::string &msg) +void SketchObject::appendConflictMsg(const std::vector& conflicting, std::string& msg) { appendConstraintsMsg(conflicting, "Please remove the following conflicting constraint:\n", @@ -7580,7 +8174,7 @@ void SketchObject::appendConflictMsg(const std::vector &conflicting, std::s msg); } -void SketchObject::appendRedundantMsg(const std::vector &redundant, std::string &msg) +void SketchObject::appendRedundantMsg(const std::vector& redundant, std::string& msg) { appendConstraintsMsg(redundant, "Please remove the following redundant constraint:", @@ -7588,7 +8182,8 @@ void SketchObject::appendRedundantMsg(const std::vector &redundant, std::st msg); } -void SketchObject::appendMalformedConstraintsMsg(const std::vector &malformed, std::string &msg) +void SketchObject::appendMalformedConstraintsMsg(const std::vector& malformed, + std::string& msg) { appendConstraintsMsg(malformed, "Please remove the following malformed constraint:", @@ -7596,10 +8191,9 @@ void SketchObject::appendMalformedConstraintsMsg(const std::vector &malform msg); } -void SketchObject::appendConstraintsMsg(const std::vector &vector, - const std::string &singularmsg, - const std::string &pluralmsg, - std::string &msg) +void SketchObject::appendConstraintsMsg(const std::vector& vector, + const std::string& singularmsg, + const std::string& pluralmsg, std::string& msg) { std::stringstream ss; if (msg.length() > 0) @@ -7610,7 +8204,7 @@ void SketchObject::appendConstraintsMsg(const std::vector &vector, else ss << pluralmsg; ss << vector[0] << std::endl; - for (unsigned int i=1; i < vector.size(); i++) + for (unsigned int i = 1; i < vector.size(); i++) ss << ", " << vector[i]; ss << "\n"; } @@ -7618,45 +8212,50 @@ void SketchObject::appendConstraintsMsg(const std::vector &vector, } -void SketchObject::getGeometryWithDependentParameters(std::vector>& geometrymap) +void SketchObject::getGeometryWithDependentParameters( + std::vector>& geometrymap) { auto geos = getInternalGeometry(); int geoid = 0; - for(auto geo : geos) { - if(geo) { - if(geo->hasExtension(Sketcher::SolverGeometryExtension::getClassTypeId())) { + for (auto geo : geos) { + if (geo) { + if (geo->hasExtension(Sketcher::SolverGeometryExtension::getClassTypeId())) { auto solvext = std::static_pointer_cast( - geo->getExtension(Sketcher::SolverGeometryExtension::getClassTypeId()).lock()); + geo->getExtension(Sketcher::SolverGeometryExtension::getClassTypeId()).lock()); - if (solvext->getGeometry() == Sketcher::SolverGeometryExtension::NotFullyConstraint) { - // The solver differentiates whether the parameters that are dependent are not those - // of start, end, mid, and assigns them to the edge (edge params = curve params - parms of start, end, mid). - // The user looking at the UI expects that the edge of a NotFullyConstraint geometry - // will always move, even if the edge parameters are independent, for example if mid is - // the only dependent parameter. In other words, the user could reasonably restrict the edge - // to reach a fully constrained element. Under this understanding, the edge parameter would - // always be dependent, unless the element is fully constrained. + if (solvext->getGeometry() + == Sketcher::SolverGeometryExtension::NotFullyConstraint) { + // The solver differentiates whether the parameters that are dependent are not + // those of start, end, mid, and assigns them to the edge (edge params = curve + // params - parms of start, end, mid). The user looking at the UI expects that + // the edge of a NotFullyConstraint geometry will always move, even if the edge + // parameters are independent, for example if mid is the only dependent + // parameter. In other words, the user could reasonably restrict the edge to + // reach a fully constrained element. Under this understanding, the edge + // parameter would always be dependent, unless the element is fully constrained. // - // While this is ok from a user visual expectation point of view, it leads to a loss of information - // of whether restricting the point start, end, mid that is dependent may suffice, or even if such - // points are restricted, the edge would still need to be restricted. + // While this is ok from a user visual expectation point of view, it leads to a + // loss of information of whether restricting the point start, end, mid that is + // dependent may suffice, or even if such points are restricted, the edge would + // still need to be restricted. // - // Because Python gets the information in this function, it would lead to Python users having access - // to a lower amount of detail. + // Because Python gets the information in this function, it would lead to Python + // users having access to a lower amount of detail. // - // For this reason, this function returns edge as dependent parameter if and only if constraining the - // parameters of the points would not suffice to constraint the element. + // For this reason, this function returns edge as dependent parameter if and + // only if constraining the parameters of the points would not suffice to + // constraint the element. if (solvext->getEdge() == SolverGeometryExtension::Dependent) - geometrymap.emplace_back(geoid,Sketcher::PointPos::none); + geometrymap.emplace_back(geoid, Sketcher::PointPos::none); if (solvext->getStart() == SolverGeometryExtension::Dependent) - geometrymap.emplace_back(geoid,Sketcher::PointPos::start); + geometrymap.emplace_back(geoid, Sketcher::PointPos::start); if (solvext->getEnd() == SolverGeometryExtension::Dependent) - geometrymap.emplace_back(geoid,Sketcher::PointPos::start); + geometrymap.emplace_back(geoid, Sketcher::PointPos::start); if (solvext->getMid() == SolverGeometryExtension::Dependent) - geometrymap.emplace_back(geoid,Sketcher::PointPos::start); + geometrymap.emplace_back(geoid, Sketcher::PointPos::start); } } } @@ -7665,10 +8264,10 @@ void SketchObject::getGeometryWithDependentParameters(std::vector= -extGeoCount && geoId < intGeoCount); geoId = constraint->Second; - ret = ret && ((geoId == GeoEnum::GeoUndef && !requireSecond) - || - (geoId >= -extGeoCount && geoId < intGeoCount) ); + ret = ret + && ((geoId == GeoEnum::GeoUndef && !requireSecond) + || (geoId >= -extGeoCount && geoId < intGeoCount)); geoId = constraint->Third; - ret = ret && ((geoId == GeoEnum::GeoUndef && !requireThird) - || - (geoId >= -extGeoCount && geoId < intGeoCount) ); + ret = ret + && ((geoId == GeoEnum::GeoUndef && !requireThird) + || (geoId >= -extGeoCount && geoId < intGeoCount)); return ret; } @@ -7731,14 +8330,14 @@ bool SketchObject::evaluateConstraints() const int intGeoCount = getHighestCurveIndex() + 1; int extGeoCount = getExternalGeometryCount(); - std::vector geometry = getCompleteGeometry(); - const std::vector& constraints = Constraints.getValuesForce(); + std::vector geometry = getCompleteGeometry(); + const std::vector& constraints = Constraints.getValuesForce(); if (static_cast(geometry.size()) != extGeoCount + intGeoCount) return false; if (geometry.size() < 2) return false; - std::vector::const_iterator it; + std::vector::const_iterator it; for (it = constraints.begin(); it != constraints.end(); ++it) { if (!evaluateConstraint(*it)) return false; @@ -7754,14 +8353,15 @@ bool SketchObject::evaluateConstraints() const void SketchObject::validateConstraints() { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); - std::vector geometry = getCompleteGeometry(); - const std::vector& constraints = Constraints.getValuesForce(); + std::vector geometry = getCompleteGeometry(); + const std::vector& constraints = Constraints.getValuesForce(); - std::vector newConstraints; + std::vector newConstraints; newConstraints.reserve(constraints.size()); - std::vector::const_iterator it; + std::vector::const_iterator it; for (it = constraints.begin(); it != constraints.end(); ++it) { bool valid = evaluateConstraint(*it); if (valid) @@ -7777,9 +8377,10 @@ void SketchObject::validateConstraints() } } -std::string SketchObject::validateExpression(const App::ObjectIdentifier &path, std::shared_ptr expr) +std::string SketchObject::validateExpression(const App::ObjectIdentifier& path, + std::shared_ptr expr) { - const App::Property * prop = path.getProperty(); + const App::Property* prop = path.getProperty(); assert(expr); @@ -7787,7 +8388,7 @@ std::string SketchObject::validateExpression(const App::ObjectIdentifier &path, return "Property not found"; if (prop == &Constraints) { - const Constraint * constraint = Constraints.getConstraint(path); + const Constraint* constraint = Constraints.getConstraint(path); if (!constraint->isDriving) return "Reference constraints cannot be set!"; @@ -7795,42 +8396,44 @@ std::string SketchObject::validateExpression(const App::ObjectIdentifier &path, auto deps = expr->getDeps(); auto it = deps.find(this); - if (it!=deps.end()) { + if (it != deps.end()) { auto it2 = it->second.find("Constraints"); if (it2 != it->second.end()) { - for (auto &oid : it2->second) { - const Constraint * constraint = Constraints.getConstraint(oid); + for (auto& oid : it2->second) { + const Constraint* constraint = Constraints.getConstraint(oid); if (!constraint->isDriving) - return "Reference constraint from this sketch cannot be used in this expression."; + return "Reference constraint from this sketch cannot be used in this " + "expression."; } } } return ""; } -//This function is necessary for precalculation of an angle when adding -// an angle constraint. It is also used here, in SketchObject, to -// lock down the type of tangency/perpendicularity. +// This function is necessary for precalculation of an angle when adding +// an angle constraint. It is also used here, in SketchObject, to +// lock down the type of tangency/perpendicularity. double SketchObject::calculateAngleViaPoint(int GeoId1, int GeoId2, double px, double py) { // Temporary sketch based calculation. Slow, but guaranteed consistency with constraints. Sketcher::Sketch sk; - const Part::Geometry *p1=this->getGeometry(GeoId1); - const Part::Geometry *p2=this->getGeometry(GeoId2); + const Part::Geometry* p1 = this->getGeometry(GeoId1); + const Part::Geometry* p2 = this->getGeometry(GeoId2); if (p1 && p2) { int i1 = sk.addGeometry(this->getGeometry(GeoId1)); int i2 = sk.addGeometry(this->getGeometry(GeoId2)); - return sk.calculateAngleViaPoint(i1,i2,px,py); + return sk.calculateAngleViaPoint(i1, i2, px, py); } else throw Base::ValueError("Null geometry in calculateAngleViaPoint"); } -void SketchObject::constraintsRenamed(const std::map &renamed) +void SketchObject::constraintsRenamed( + const std::map& renamed) { ExpressionEngine.renameExpressions(renamed); @@ -7838,7 +8441,7 @@ void SketchObject::constraintsRenamed(const std::maprenameObjectIdentifiers(renamed); } -void SketchObject::constraintsRemoved(const std::set &removed) +void SketchObject::constraintsRemoved(const std::set& removed) { std::set::const_iterator i = removed.begin(); @@ -7848,45 +8451,46 @@ void SketchObject::constraintsRemoved(const std::set &rem } } -//Tests if the provided point lies exactly in a curve (satisfies -// point-on-object constraint). It is used to decide whether it is nesessary to -// constrain a point onto curves when 3-element selection tangent-via-point-like -// constraints are applied. +// Tests if the provided point lies exactly in a curve (satisfies +// point-on-object constraint). It is used to decide whether it is nesessary to +// constrain a point onto curves when 3-element selection tangent-via-point-like +// constraints are applied. bool SketchObject::isPointOnCurve(int geoIdCurve, double px, double py) { - //DeepSOIC: this may be slow, but I wanted to reuse the existing code + // DeepSOIC: this may be slow, but I wanted to reuse the existing code Sketcher::Sketch sk; int icrv = sk.addGeometry(this->getGeometry(geoIdCurve)); Base::Vector3d pp; - pp.x = px; pp.y = py; + pp.x = px; + pp.y = py; Part::GeomPoint p(pp); int ipnt = sk.addPoint(p); int icstr = sk.addPointOnObjectConstraint(ipnt, Sketcher::PointPos::start, icrv); double err = sk.calculateConstraintError(icstr); - return err*err < 10.0*sk.getSolverPrecision(); + return err * err < 10.0 * sk.getSolverPrecision(); } -//This one was done just for fun to see to what precision the constraints are solved. +// This one was done just for fun to see to what precision the constraints are solved. double SketchObject::calculateConstraintError(int ConstrId) { Sketcher::Sketch sk; - const std::vector &clist = this->Constraints.getValues(); + const std::vector& clist = this->Constraints.getValues(); if (ConstrId < 0 || ConstrId >= int(clist.size())) return std::numeric_limits::quiet_NaN(); Constraint* cstr = clist[ConstrId]->clone(); - double result=0.0; - try{ + double result = 0.0; + try { std::vector GeoIdList; int g; GeoIdList.push_back(cstr->First); GeoIdList.push_back(cstr->Second); GeoIdList.push_back(cstr->Third); - //add only necessary geometry to the sketch - for(std::size_t i=0; igetGeometry(g)); } } @@ -7896,7 +8500,8 @@ double SketchObject::calculateConstraintError(int ConstrId) cstr->Third = GeoIdList[2]; int icstr = sk.addConstraint(cstr); result = sk.calculateConstraintError(icstr); - } catch(...) {//cleanup + } + catch (...) {// cleanup delete cstr; throw; } @@ -7904,11 +8509,11 @@ double SketchObject::calculateConstraintError(int ConstrId) return result; } -PyObject *SketchObject::getPyObject() +PyObject* SketchObject::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new SketchObjectPy(this),true); + PythonObject = Py::Object(new SketchObjectPy(this), true); } return Py::new_reference_to(PythonObject); } @@ -7918,13 +8523,13 @@ unsigned int SketchObject::getMemSize() const return 0; } -void SketchObject::Save(Writer &writer) const +void SketchObject::Save(Writer& writer) const { // save the father classes Part::Part2DObject::Save(writer); } -void SketchObject::Restore(XMLReader &reader) +void SketchObject::Restore(XMLReader& reader) { // read the father classes Part::Part2DObject::Restore(reader); @@ -7946,47 +8551,63 @@ void SketchObject::onChanged(const App::Property* prop) auto doc = getDocument(); - if(doc && doc->isPerformingTransaction()) { // undo/redo + if (doc && doc->isPerformingTransaction()) {// undo/redo setStatus(App::PendingTransactionUpdate, true); } else { - if(!internaltransaction) { // internal sketchobject operations changing both geometry and constraints will explicitly perform an update - if(prop == &Geometry) { - if(managedoperation || isRestoring()) { - acceptGeometry(); // if geometry changed, the constraint geometry indices must be updated + if (!internaltransaction) { + // internal sketchobject operations changing both geometry and constraints will + // explicitly perform an update + if (prop == &Geometry) { + if (managedoperation || isRestoring()) { + // if geometry changed, the constraint geometry indices must be updated + acceptGeometry(); } - else { // this change was not effect via SketchObject, but using direct access to properties, check input data + else { + // this change was not effect via SketchObject, but using direct access to + // properties, check input data - // declares constraint invalid if indices go beyond the geometry and any call to getValues with return an empty list until this is fixed. - bool invalidinput = Constraints.checkConstraintIndices(getHighestCurveIndex(),-getExternalGeometryCount()); + // declares constraint invalid if indices go beyond the geometry and any + // call to getValues with return an empty list until this is fixed. + bool invalidinput = Constraints.checkConstraintIndices( + getHighestCurveIndex(), -getExternalGeometryCount()); - if(!invalidinput) { + if (!invalidinput) { acceptGeometry(); } else { - Base::Console().Error("SketchObject::onChanged(): Unmanaged change of Geometry Property results in invalid constraint indices\n"); + Base::Console().Error( + "SketchObject::onChanged(): Unmanaged change of Geometry Property " + "results in invalid constraint indices\n"); } } } - else { // Change is in Constraints + else {// Change is in Constraints - if(managedoperation || isRestoring()) { + if (managedoperation || isRestoring()) { Constraints.checkGeometry(getCompleteGeometry()); } - else { // this change was not effect via SketchObject, but using direct access to properties, check input data + else { + // this change was not effect via SketchObject, but using direct access to + // properties, check input data - // declares constraint invalid if indices go beyond the geometry and any call to getValues with return an empty list until this is fixed. - bool invalidinput = Constraints.checkConstraintIndices(getHighestCurveIndex(),-getExternalGeometryCount()); + // declares constraint invalid if indices go beyond the geometry and any + // call to getValues with return an empty list until this is fixed. + bool invalidinput = Constraints.checkConstraintIndices( + getHighestCurveIndex(), -getExternalGeometryCount()); - if(!invalidinput) { - if (Constraints.checkGeometry(getCompleteGeometry())) { // if there are invalid geometry indices in the constraints, we need to update them + if (!invalidinput) { + if (Constraints.checkGeometry(getCompleteGeometry())) { + // if there are invalid geometry indices in the constraints, we need + // to update them acceptGeometry(); } } else { - Base::Console().Error("SketchObject::onChanged(): Unmanaged change of Constraint Property results in invalid constraint indices\n"); + Base::Console().Error( + "SketchObject::onChanged(): Unmanaged change of Constraint " + "Property results in invalid constraint indices\n"); } - } } } @@ -8020,14 +8641,15 @@ void SketchObject::onChanged(const App::Property* prop) void SketchObject::onUndoRedoFinished() { - // upon undo/redo, PropertyConstraintList does not have updated valid geometry keys, which results in empty constraint lists - // when using getValues + // upon undo/redo, PropertyConstraintList does not have updated valid geometry keys, which + // results in empty constraint lists when using getValues // // The sketch will also have invalid vertex indices, requiring a call to rebuildVertexIndex // - // Historically this was "solved" by issuing a recompute, which is absolutely unnecessary and prevents solve() from working before - // such a recompute - Constraints.checkConstraintIndices(getHighestCurveIndex(),-getExternalGeometryCount()); // in case it is redoing an operation with invalid data. + // Historically this was "solved" by issuing a recompute, which is absolutely unnecessary and + // prevents solve() from working before such a recompute in case it is redoing an operation with + // invalid data. + Constraints.checkConstraintIndices(getHighestCurveIndex(), -getExternalGeometryCount()); acceptGeometry(); synchroniseGeometryState(); solve(); @@ -8035,9 +8657,9 @@ void SketchObject::onUndoRedoFinished() void SketchObject::synchroniseGeometryState() { - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); - for(size_t i = 0 ; i < vals.size() ; i++) { + for (size_t i = 0; i < vals.size(); i++) { auto gf = GeometryFacade::getFacade(vals[i]); auto facadeInternalAlignment = gf->getInternalType(); @@ -8047,26 +8669,26 @@ void SketchObject::synchroniseGeometryState() bool constraintBlockedState = false; for (auto cstr : Constraints.getValues()) { - if(cstr->First == int(i)) { + if (cstr->First == int(i)) { getInternalTypeState(cstr, constraintInternalAlignment); getBlockedState(cstr, constraintBlockedState); } } - if(constraintInternalAlignment != facadeInternalAlignment) + if (constraintInternalAlignment != facadeInternalAlignment) gf->setInternalType(constraintInternalAlignment); - if(constraintBlockedState != facadeBlockedState) + if (constraintBlockedState != facadeBlockedState) gf->setBlocked(constraintBlockedState); - } } -bool SketchObject::getInternalTypeState(const Constraint * cstr, Sketcher::InternalType::InternalType & internaltypestate) const +bool SketchObject::getInternalTypeState( + const Constraint* cstr, Sketcher::InternalType::InternalType& internaltypestate) const { - if(cstr->Type == InternalAlignment) { + if (cstr->Type == InternalAlignment) { - switch(cstr->AlignmentType){ + switch (cstr->AlignmentType) { case Undef: case NumInternalAlignmentType: internaltypestate = InternalType::None; @@ -8112,9 +8734,9 @@ bool SketchObject::getInternalTypeState(const Constraint * cstr, Sketcher::Inter return false; } -bool SketchObject::getBlockedState(const Constraint * cstr, bool & blockedstate) const +bool SketchObject::getBlockedState(const Constraint* cstr, bool& blockedstate) const { - if(cstr->Type == Block) { + if (cstr->Type == Block) { blockedstate = true; return true; } @@ -8156,17 +8778,18 @@ void SketchObject::migrateSketch() { bool noextensions = false; - for( const auto & g : getInternalGeometry() ) - if(!g->hasExtension(SketchGeometryExtension::getClassTypeId())) // no extension - legacy file + for (const auto& g : getInternalGeometry()) + // no extension - legacy file + if (!g->hasExtension(SketchGeometryExtension::getClassTypeId())) noextensions = true; - if(noextensions) { - for( auto c : Constraints.getValues()) { + if (noextensions) { + for (auto c : Constraints.getValues()) { addGeometryState(c); // Convert B-Spline controlpoints radius/diameter constraints to Weight constraints - if(c->Type == InternalAlignment && c->AlignmentType == BSplineControlPoint) { + if (c->Type == InternalAlignment && c->AlignmentType == BSplineControlPoint) { int circlegeoid = c->First; int bsplinegeoid = c->Second; @@ -8174,15 +8797,14 @@ void SketchObject::migrateSketch() std::vector weights = bsp->getWeights(); - for( auto ccp : Constraints.getValues()) { + for (auto ccp : Constraints.getValues()) { - if( (ccp->Type == Radius || ccp->Type == Diameter ) && - ccp->First == circlegeoid ) { + if ((ccp->Type == Radius || ccp->Type == Diameter) + && ccp->First == circlegeoid) { - if(c->InternalAlignmentIndex < int(weights.size())) { + if (c->InternalAlignmentIndex < int(weights.size())) { ccp->Type = Weight; ccp->setValue(weights[c->InternalAlignmentIndex]); - } } } @@ -8190,28 +8812,27 @@ void SketchObject::migrateSketch() } // Construction migration to extension - for( auto g : Geometry.getValues()) { + for (auto g : Geometry.getValues()) { - if(g->hasExtension(Part::GeometryMigrationExtension::getClassTypeId())) - { + if (g->hasExtension(Part::GeometryMigrationExtension::getClassTypeId())) { auto ext = std::static_pointer_cast( - g->getExtension(Part::GeometryMigrationExtension::getClassTypeId()).lock()); + g->getExtension(Part::GeometryMigrationExtension::getClassTypeId()).lock()); - if(ext->testMigrationType(Part::GeometryMigrationExtension::Construction)) - { - auto gf = GeometryFacade::getFacade(g); // at this point IA geometry is already migrated + if (ext->testMigrationType(Part::GeometryMigrationExtension::Construction)) { + // at this point IA geometry is already migrated + auto gf = GeometryFacade::getFacade(g); - bool oldconstr = ext->getConstruction(); + bool oldconstr = ext->getConstruction(); - if( g->getTypeId() == Part::GeomPoint::getClassTypeId() && !gf->isInternalAligned()) + if (g->getTypeId() == Part::GeomPoint::getClassTypeId() + && !gf->isInternalAligned()) oldconstr = true; - GeometryFacade::setConstruction(g,oldconstr); + GeometryFacade::setConstruction(g, oldconstr); } g->deleteExtension(Part::GeometryMigrationExtension::getClassTypeId()); } - } } @@ -8219,52 +8840,53 @@ void SketchObject::migrateSketch() auto constraints = Constraints.getValues(); auto geometries = getInternalGeometry(); - auto parabolafound = std::find_if(geometries.begin(), geometries.end(), - [](auto g){ - return g->getTypeId() == Part::GeomArcOfParabola::getClassTypeId(); - }); + auto parabolafound = std::find_if(geometries.begin(), geometries.end(), [](auto g) { + return g->getTypeId() == Part::GeomArcOfParabola::getClassTypeId(); + }); - if(parabolafound != geometries.end()) { + if (parabolafound != geometries.end()) { - auto focalaxisfound = std::find_if(constraints.begin(), constraints.end(), - [](auto c){ - return c->Type == InternalAlignment && c->AlignmentType == ParabolaFocalAxis; - }); + auto focalaxisfound = std::find_if(constraints.begin(), constraints.end(), [](auto c) { + return c->Type == InternalAlignment && c->AlignmentType == ParabolaFocalAxis; + }); - // There are parabolas and there isn't an IA axis. (1) there are no axis or (2) there is a legacy construction line - if(focalaxisfound == constraints.end()) { + // There are parabolas and there isn't an IA axis. (1) there are no axis or (2) there is a + // legacy construction line + if (focalaxisfound == constraints.end()) { // maps parabola geoid to focusgeoid - std::map parabolageoid2focusgeoid; + std::map parabolageoid2focusgeoid; // populate parabola and focus geoids - for(const auto & c : constraints) { - if(c->Type == InternalAlignment && c->AlignmentType == ParabolaFocus) { + for (const auto& c : constraints) { + if (c->Type == InternalAlignment && c->AlignmentType == ParabolaFocus) { parabolageoid2focusgeoid[c->Second] = {c->First}; } } // maps axis geoid to parabolageoid - std::map axisgeoid2parabolageoid; + std::map axisgeoid2parabolageoid; // populate axis geoid - for(const auto & [parabolageoid, focusgeoid] : parabolageoid2focusgeoid ) { + for (const auto& [parabolageoid, focusgeoid] : parabolageoid2focusgeoid) { // look for a line from focusgeoid:start to Geoid:mid_external std::vector focusgeoidlistgeoidlist; std::vector focusposidlist; - getDirectlyCoincidentPoints(focusgeoid, Sketcher::PointPos::start, focusgeoidlistgeoidlist, - focusposidlist); + getDirectlyCoincidentPoints( + focusgeoid, Sketcher::PointPos::start, focusgeoidlistgeoidlist, focusposidlist); std::vector parabgeoidlistgeoidlist; std::vector parabposidlist; - getDirectlyCoincidentPoints(parabolageoid, Sketcher::PointPos::mid, parabgeoidlistgeoidlist, + getDirectlyCoincidentPoints(parabolageoid, + Sketcher::PointPos::mid, + parabgeoidlistgeoidlist, parabposidlist); if (!focusgeoidlistgeoidlist.empty() && !parabgeoidlistgeoidlist.empty()) { - std::size_t i,j; - for(i=0;i newconstraints; + std::vector newconstraints; newconstraints.reserve(constraints.size()); - for(const auto & c : constraints) { + for (const auto& c : constraints) { - if(c->Type != Coincident) { + if (c->Type != Coincident) { newconstraints.push_back(c); } else { - auto axismajorcoincidentfound = std::find_if(axisgeoid2parabolageoid.begin(), axisgeoid2parabolageoid.end(), - [&] (const auto & pair) { - auto parabolageoid = pair.second; - auto axisgeoid = pair.first; - return (c->First == axisgeoid && c->Second == parabolageoid && c->SecondPos == PointPos::mid) || - (c->Second == axisgeoid && c->First == parabolageoid && c->FirstPos == PointPos::mid); - }); + auto axismajorcoincidentfound = + std::find_if(axisgeoid2parabolageoid.begin(), + axisgeoid2parabolageoid.end(), + [&](const auto& pair) { + auto parabolageoid = pair.second; + auto axisgeoid = pair.first; + return (c->First == axisgeoid && c->Second == parabolageoid + && c->SecondPos == PointPos::mid) + || (c->Second == axisgeoid && c->First == parabolageoid + && c->FirstPos == PointPos::mid); + }); - if(axismajorcoincidentfound != axisgeoid2parabolageoid.end()) { - continue; // we skip this coincident, the other coincident on axis will be substituted by internal geometry constraint + if (axismajorcoincidentfound != axisgeoid2parabolageoid.end()) { + // we skip this coincident, the other coincident on axis will be substituted + // by internal geometry constraint + continue; } - auto focuscoincidentfound = std::find_if(axisgeoid2parabolageoid.begin(), axisgeoid2parabolageoid.end(), - [&] (const auto & pair) { - auto parabolageoid = pair.second; - auto axisgeoid = pair.first; - auto focusgeoid = parabolageoid2focusgeoid[parabolageoid]; - return (c->First == axisgeoid && c->Second == focusgeoid && c->SecondPos == PointPos::start) || - (c->Second == axisgeoid && c->First == focusgeoid && c->FirstPos == PointPos::start); - }); + auto focuscoincidentfound = + std::find_if(axisgeoid2parabolageoid.begin(), + axisgeoid2parabolageoid.end(), + [&](const auto& pair) { + auto parabolageoid = pair.second; + auto axisgeoid = pair.first; + auto focusgeoid = parabolageoid2focusgeoid[parabolageoid]; + return (c->First == axisgeoid && c->Second == focusgeoid + && c->SecondPos == PointPos::start) + || (c->Second == axisgeoid && c->First == focusgeoid + && c->FirstPos == PointPos::start); + }); - if(focuscoincidentfound != axisgeoid2parabolageoid.end()) { - Sketcher::Constraint *newConstr = new Sketcher::Constraint(); + if (focuscoincidentfound != axisgeoid2parabolageoid.end()) { + Sketcher::Constraint* newConstr = new Sketcher::Constraint(); newConstr->Type = Sketcher::InternalAlignment; newConstr->AlignmentType = Sketcher::ParabolaFocalAxis; - newConstr->First = focuscoincidentfound->first; // axis geoid + newConstr->First = focuscoincidentfound->first;// axis geoid newConstr->FirstPos = Sketcher::PointPos::none; - newConstr->Second = focuscoincidentfound->second; // parabola geoid + newConstr->Second = focuscoincidentfound->second;// parabola geoid newConstr->SecondPos = Sketcher::PointPos::none; newconstraints.push_back(newConstr); addGeometryState(newConstr); - continue; // we skip the coincident, as we have substituted it by internal geometry constraint + // we skip the coincident, as we have substituted it by internal geometry + // constraint + continue; } newconstraints.push_back(c); @@ -8323,12 +8957,16 @@ void SketchObject::migrateSketch() Constraints.setValues(std::move(newconstraints)); - Base::Console().Critical(this->getFullName(),QT_TRANSLATE_NOOP("Notifications","Parabolas were migrated. Migrated files won't open in previous versions of FreeCAD!!\n")); + Base::Console().Critical( + this->getFullName(), + QT_TRANSLATE_NOOP("Notifications", + "Parabolas were migrated. Migrated files won't open in previous " + "versions of FreeCAD!!\n")); } } } -void SketchObject::getGeoVertexIndex(int VertexId, int &GeoId, PointPos &PosId) const +void SketchObject::getGeoVertexIndex(int VertexId, int& GeoId, PointPos& PosId) const { if (VertexId < 0 || VertexId >= int(VertexId2GeoId.size())) { GeoId = GeoEnum::GeoUndef; @@ -8341,53 +8979,54 @@ void SketchObject::getGeoVertexIndex(int VertexId, int &GeoId, PointPos &PosId) int SketchObject::getVertexIndexGeoPos(int GeoId, PointPos PosId) const { - for(std::size_t i=0;i &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); - std::vector< Constraint * > newVals(vals);//modifiable copy of pointers array + std::vector newVals(vals);// modifiable copy of pointers array - for(size_t i=0; iType == Tangent || newVals[i]->Type == Perpendicular ){ - //create a constraint copy, affect it, replace the pointer + for (size_t i = 0; i < newVals.size(); i++) { + if (newVals[i]->Type == Tangent || newVals[i]->Type == Perpendicular) { + // create a constraint copy, affect it, replace the pointer cntToBeAffected++; - Constraint *constNew = newVals[i]->clone(); + Constraint* constNew = newVals[i]->clone(); bool ret = AutoLockTangencyAndPerpty(newVals[i], /*bForce=*/true, bLock); if (ret) cntSuccess++; newVals[i] = constNew; - Base::Console().Log("Constraint%i will be affected\n", - i+1); + Base::Console().Log("Constraint%i will be affected\n", i + 1); } } this->Constraints.setValues(std::move(newVals)); Base::Console().Log("ChangeConstraintsLocking: affected %i of %i tangent/perp constraints\n", - cntSuccess, cntToBeAffected); + cntSuccess, + cntToBeAffected); return cntSuccess; } @@ -8403,69 +9042,90 @@ bool SketchObject::constraintHasExpression(int constrid) const /*! - * \brief SketchObject::port_reversedExternalArcs finds constraints that link to endpoints of external-geometry arcs, - * and swaps the endpoints in the constraints. This is needed after CCW emulation was introduced, to port old sketches. - * \param justAnalyze if true, nothing is actually done - only the number of constraints to be affected is returned. - * \return the number of constraints changed/to be changed. + * \brief SketchObject::port_reversedExternalArcs finds constraints that link to endpoints of + * external-geometry arcs, and swaps the endpoints in the constraints. This is needed after CCW + * emulation was introduced, to port old sketches. \param justAnalyze if true, nothing is actually + * done - only the number of constraints to be affected is returned. \return the number of + * constraints changed/to be changed. */ int SketchObject::port_reversedExternalArcs(bool justAnalyze) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); int cntToBeAffected = 0;//==cntSuccess+cntFail - const std::vector< Constraint * > &vals = this->Constraints.getValues(); + const std::vector& vals = this->Constraints.getValues(); - std::vector< Constraint * > newVals(vals);//modifiable copy of pointers array + std::vector newVals(vals);// modifiable copy of pointers array - for(std::size_t ic = 0; icFirst; posId = newVals[ic]->FirstPos; break; - case 2: geoId=newVals[ic]->Second; posId = newVals[ic]->SecondPos; break; - case 3: geoId=newVals[ic]->Third; posId = newVals[ic]->ThirdPos; break; + switch (ig) { + case 1: + geoId = newVals[ic]->First; + posId = newVals[ic]->FirstPos; + break; + case 2: + geoId = newVals[ic]->Second; + posId = newVals[ic]->SecondPos; + break; + case 3: + geoId = newVals[ic]->Third; + posId = newVals[ic]->ThirdPos; + break; } - if ( geoId <= GeoEnum::RefExt && - (posId==Sketcher::PointPos::start || posId==Sketcher::PointPos::end)){ - //we are dealing with a link to an endpoint of external geom - Part::Geometry* g = this->ExternalGeo[-geoId-1]; - if (g->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()){ - const Part::GeomArcOfCircle *segm = static_cast(g); - if (segm->isReversed()){ - //Gotcha! a link to an endpoint of external arc that is reversed. - //create a constraint copy, affect it, replace the pointer + if (geoId <= GeoEnum::RefExt + && (posId == Sketcher::PointPos::start || posId == Sketcher::PointPos::end)) { + // we are dealing with a link to an endpoint of external geom + Part::Geometry* g = this->ExternalGeo[-geoId - 1]; + if (g->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* segm = + static_cast(g); + if (segm->isReversed()) { + // Gotcha! a link to an endpoint of external arc that is reversed. + // create a constraint copy, affect it, replace the pointer if (!affected) constNew = newVals[ic]->clone(); - affected=true; - //Do the fix on temp vars - if(posId == Sketcher::PointPos::start) + affected = true; + // Do the fix on temp vars + if (posId == Sketcher::PointPos::start) posId = Sketcher::PointPos::end; else if (posId == Sketcher::PointPos::end) posId = Sketcher::PointPos::start; } } } - if (!affected) continue; - //Propagate the fix made on temp vars to the constraint - switch (ig){ - case 1: constNew->First = geoId; constNew->FirstPos = posId; break; - case 2: constNew->Second = geoId; constNew->SecondPos = posId; break; - case 3: constNew->Third = geoId; constNew->ThirdPos = posId; break; + if (!affected) + continue; + // Propagate the fix made on temp vars to the constraint + switch (ig) { + case 1: + constNew->First = geoId; + constNew->FirstPos = posId; + break; + case 2: + constNew->Second = geoId; + constNew->SecondPos = posId; + break; + case 3: + constNew->Third = geoId; + constNew->ThirdPos = posId; + break; } } - if (affected){ + if (affected) { cntToBeAffected++; newVals[ic] = constNew; - Base::Console().Log("Constraint%i will be affected\n", - ic+1); + Base::Console().Log("Constraint%i will be affected\n", ic + 1); }; } - if(!justAnalyze){ + if (!justAnalyze) { this->Constraints.setValues(std::move(newVals)); Base::Console().Log("Swapped start/end of reversed external arcs in %i constraints\n", cntToBeAffected); @@ -8474,48 +9134,52 @@ int SketchObject::port_reversedExternalArcs(bool justAnalyze) return cntToBeAffected; } -///Locks tangency/perpendicularity type of such a constraint. -///The constraint passed must be writable (i.e. the one that is not -/// yet in the constraint list). -///Tangency type (internal/external) is derived from current geometry -/// the constraint refers to. -///Same for perpendicularity type. +/// Locks tangency/perpendicularity type of such a constraint. +/// The constraint passed must be writable (i.e. the one that is not +/// yet in the constraint list). +/// Tangency type (internal/external) is derived from current geometry +/// the constraint refers to. +/// Same for perpendicularity type. /// -///This function catches exceptions, because it's not a reason to -/// not create a constraint if tangency/perp-ty type cannot be determined. +/// This function catches exceptions, because it's not a reason to +/// not create a constraint if tangency/perp-ty type cannot be determined. /// -///Arguments: -/// cstr - pointer to a constraint to be locked/unlocked -/// bForce - specifies whether to ignore the already locked constraint or not. -/// bLock - specifies whether to lock the constraint or not (if bForce is -/// true, the constraint gets unlocked, otherwise nothing is done at all). +/// Arguments: +/// cstr - pointer to a constraint to be locked/unlocked +/// bForce - specifies whether to ignore the already locked constraint or not. +/// bLock - specifies whether to lock the constraint or not (if bForce is +/// true, the constraint gets unlocked, otherwise nothing is done at all). /// -///Return values: -/// true - success. -/// false - fail (this indicates an error, or that a constraint locking isn't supported). -bool SketchObject::AutoLockTangencyAndPerpty(Constraint *cstr, bool bForce, bool bLock) +/// Return values: +/// true - success. +/// false - fail (this indicates an error, or that a constraint locking isn't supported). +bool SketchObject::AutoLockTangencyAndPerpty(Constraint* cstr, bool bForce, bool bLock) { try { - //assert ( cstr->Type == Tangent || cstr->Type == Perpendicular); - if(cstr->getValue() != 0.0 && ! bForce) /*tangency type already set. If not bForce - don't touch.*/ + // assert ( cstr->Type == Tangent || cstr->Type == Perpendicular); + /*tangency type already set. If not bForce - don't touch.*/ + if (cstr->getValue() != 0.0 && !bForce) return true; - if(!bLock){ - cstr->setValue(0.0);//reset - } else { - //decide on tangency type. Write the angle value into the datum field of the constraint. + if (!bLock) { + cstr->setValue(0.0);// reset + } + else { + // decide on tangency type. Write the angle value into the datum field of the + // constraint. int geoId1, geoId2, geoIdPt; PointPos posPt; geoId1 = cstr->First; geoId2 = cstr->Second; geoIdPt = cstr->Third; posPt = cstr->ThirdPos; - if (geoIdPt == GeoEnum::GeoUndef){//not tangent-via-point, try endpoint-to-endpoint... + if (geoIdPt == GeoEnum::GeoUndef) {// not tangent-via-point, try endpoint-to-endpoint... - // First check if it is a tangency at knot constraint, if not continue with checking for endpoints. - // Endpoint constraints make use of the AngleViaPoint framework at solver level, so they need locking - // angle calculation, tangency at knot constraint does not. + // First check if it is a tangency at knot constraint, if not continue with checking + // for endpoints. Endpoint constraints make use of the AngleViaPoint framework at + // solver level, so they need locking angle calculation, tangency at knot constraint + // does not. auto geof = getGeometryFacade(cstr->First); - if(geof->isInternalType(InternalType::BSplineKnotPoint)) { + if (geof->isInternalType(InternalType::BSplineKnotPoint)) { // there is point that is a B-Spline knot in a two element constraint // this is not implement using AngleViaPoint (TangencyViaPoint) return false; @@ -8524,54 +9188,73 @@ bool SketchObject::AutoLockTangencyAndPerpty(Constraint *cstr, bool bForce, bool geoIdPt = cstr->First; posPt = cstr->FirstPos; } - if (posPt == PointPos::none){//not endpoint-to-curve and not endpoint-to-endpoint tangent (is simple tangency) - //no tangency lockdown is implemented for simple tangency. Do nothing. + if (posPt == PointPos::none) { + // not endpoint-to-curve and not endpoint-to-endpoint tangent (is simple tangency) + // no tangency lockdown is implemented for simple tangency. Do nothing. return false; } else { Base::Vector3d p = getPoint(geoIdPt, posPt); - //this piece of code is also present in Sketch.cpp, correct for offset - //and to do the autodecision for old sketches. - double angleOffset = 0.0;//the difference between the datum value and the actual angle to apply. (datum=angle+offset) - double angleDesire = 0.0;//the desired angle value (and we are to decide if 180* should be added to it) - if (cstr->Type == Tangent) {angleOffset = -M_PI/2; angleDesire = 0.0;} - if (cstr->Type == Perpendicular) {angleOffset = 0; angleDesire = M_PI/2;} + // this piece of code is also present in Sketch.cpp, correct for offset + // and to do the autodecision for old sketches. + // the difference between the datum value and the actual angle to apply. + // (datum=angle+offset) + double angleOffset = 0.0; + // the desired angle value (and we are to decide if 180* should be added to it) + double angleDesire = 0.0; + if (cstr->Type == Tangent) { + angleOffset = -M_PI / 2; + angleDesire = 0.0; + } + if (cstr->Type == Perpendicular) { + angleOffset = 0; + angleDesire = M_PI / 2; + } double angleErr = calculateAngleViaPoint(geoId1, geoId2, p.x, p.y) - angleDesire; - //bring angleErr to -pi..pi - if (angleErr > M_PI) angleErr -= M_PI*2; - if (angleErr < -M_PI) angleErr += M_PI*2; + // bring angleErr to -pi..pi + if (angleErr > M_PI) + angleErr -= M_PI * 2; + if (angleErr < -M_PI) + angleErr += M_PI * 2; - //the autodetector - if(fabs(angleErr) > M_PI/2 ) + // the autodetector + if (fabs(angleErr) > M_PI / 2) angleDesire += M_PI; - cstr->setValue(angleDesire + angleOffset); //external tangency. The angle stored is offset by Pi/2 so that a value of 0.0 is invalid and treated as "undecided". + // external tangency. The angle stored is offset by Pi/2 so that a value of 0.0 is + // invalid and treated as "undecided". + cstr->setValue(angleDesire + angleOffset); } } } - catch (Base::Exception& e){ - //failure to determine tangency type is not a big deal, so a warning. + catch (Base::Exception& e) { + // failure to determine tangency type is not a big deal, so a warning. Base::Console().Warning("Error in AutoLockTangency. %s \n", e.what()); return false; } return true; } -void SketchObject::setExpression(const App::ObjectIdentifier &path, std::shared_ptr expr) +void SketchObject::setExpression(const App::ObjectIdentifier& path, + std::shared_ptr expr) { DocumentObject::setExpression(path, expr); - if(noRecomputes) {// if we do not have a recompute, the sketch must be solved to update the DoF of the solver, constraints and UI + if (noRecomputes) { + // if we do not have a recompute, the sketch must be solved to update the DoF of the solver, + // constraints and UI try { auto res = ExpressionEngine.execute(); - if(res) { - FC_ERR("Failed to recompute " << ExpressionEngine.getFullName() << ": " << res->Why); + if (res) { + FC_ERR("Failed to recompute " << ExpressionEngine.getFullName() << ": " + << res->Why); delete res; } - } catch (Base::Exception &e) { + } + catch (Base::Exception& e) { e.ReportException(); FC_ERR("Failed to recompute " << ExpressionEngine.getFullName() << ": " << e.what()); } @@ -8604,65 +9287,65 @@ int SketchObject::detectMissingEqualityConstraints(double precision) return analyser->detectMissingEqualityConstraints(precision); } -std::vector & SketchObject::getMissingPointOnPointConstraints() +std::vector& SketchObject::getMissingPointOnPointConstraints() { return analyser->getMissingPointOnPointConstraints(); } -std::vector & SketchObject::getMissingVerticalHorizontalConstraints() +std::vector& SketchObject::getMissingVerticalHorizontalConstraints() { return analyser->getMissingVerticalHorizontalConstraints(); } -std::vector & SketchObject::getMissingLineEqualityConstraints() +std::vector& SketchObject::getMissingLineEqualityConstraints() { return analyser->getMissingLineEqualityConstraints(); } -std::vector & SketchObject::getMissingRadiusConstraints() +std::vector& SketchObject::getMissingRadiusConstraints() { return analyser->getMissingRadiusConstraints(); } -void SketchObject::setMissingRadiusConstraints(std::vector &cl) +void SketchObject::setMissingRadiusConstraints(std::vector& cl) { - if(analyser) + if (analyser) analyser->setMissingRadiusConstraints(cl); } void SketchObject::setMissingLineEqualityConstraints(std::vector& cl) { - if(analyser) + if (analyser) analyser->setMissingLineEqualityConstraints(cl); } void SketchObject::setMissingVerticalHorizontalConstraints(std::vector& cl) { - if(analyser) + if (analyser) analyser->setMissingVerticalHorizontalConstraints(cl); } void SketchObject::setMissingPointOnPointConstraints(std::vector& cl) { - if(analyser) + if (analyser) analyser->setMissingPointOnPointConstraints(cl); } void SketchObject::makeMissingPointOnPointCoincident(bool onebyone) { - if(analyser) + if (analyser) analyser->makeMissingPointOnPointCoincident(onebyone); } void SketchObject::makeMissingVerticalHorizontal(bool onebyone) { - if(analyser) + if (analyser) analyser->makeMissingVerticalHorizontal(onebyone); } void SketchObject::makeMissingEquality(bool onebyone) { - if(analyser) + if (analyser) analyser->makeMissingEquality(onebyone); } @@ -8670,13 +9353,14 @@ int SketchObject::autoRemoveRedundants(bool updategeo) { auto redundants = getLastRedundant(); - if(redundants.empty()) + if (redundants.empty()) return 0; - for(size_t i=0;iName != name) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); Constraint* copy = item->clone(); copy->Name = name; @@ -8695,7 +9380,9 @@ int SketchObject::renameConstraint(int GeoId, std::string name) Constraints.set1Value(GeoId, copy); delete copy; - solverNeedsUpdate = true; // make sure any prospective solver access updates the constraint pointer that just got invalidated + // make sure any prospective solver access updates the constraint pointer that just got + // invalidated + solverNeedsUpdate = true; return 0; } @@ -8706,7 +9393,7 @@ std::vector SketchObject::getOpenVertices() const { std::vector points; - if(analyser) + if (analyser) points = analyser->getOpenVertices(); return points; @@ -8716,30 +9403,30 @@ std::vector SketchObject::getOpenVertices() const int SketchObject::setGeometryId(int GeoId, long id) { - Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. + // no need to check input data validity as this is an sketchobject managed operation. + Base::StateLocker lock(managedoperation, true); if (GeoId < 0 || GeoId >= int(Geometry.getValues().size())) return -1; - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); - - std::vector< Part::Geometry * > newVals(vals); + std::vector newVals(vals); // deep copy - for(size_t i=0; iclone(); - if((int)i == GeoId) { + if ((int)i == GeoId) { auto gf = GeometryFacade::getFacade(newVals[i]); gf->setId(id); } } - // There is not actual internal transaction going on here, however neither the geometry indices nor the vertices need to be updated - // so this is a convenient way of preventing it. + // There is not actual internal transaction going on here, however neither the geometry indices + // nor the vertices need to be updated so this is a convenient way of preventing it. { Base::StateLocker lock(internaltransaction, true); this->Geometry.setValues(std::move(newVals)); @@ -8748,32 +9435,37 @@ int SketchObject::setGeometryId(int GeoId, long id) return 0; } -int SketchObject::getGeometryId(int GeoId, long &id) const +int SketchObject::getGeometryId(int GeoId, long& id) const { - if (GeoId < 0 || GeoId >= int(Geometry.getValues().size())) + if (GeoId < 0 || GeoId >= int(Geometry.getValues().size())) return -1; - const std::vector< Part::Geometry * > &vals = getInternalGeometry(); + const std::vector& vals = getInternalGeometry(); - auto gf = GeometryFacade::getFacade(vals[GeoId]); + auto gf = GeometryFacade::getFacade(vals[GeoId]); - id = gf->getId(); + id = gf->getId(); - return 0; + return 0; } // Python Sketcher feature --------------------------------------------------------- -namespace App { +namespace App +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Sketcher::SketchObjectPython, Sketcher::SketchObject) -template<> const char* Sketcher::SketchObjectPython::getViewProviderName() const { +template<> +const char* Sketcher::SketchObjectPython::getViewProviderName() const +{ return "SketcherGui::ViewProviderPython"; } -template<> PyObject* Sketcher::SketchObjectPython::getPyObject() { +template<> +PyObject* Sketcher::SketchObjectPython::getPyObject() +{ if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new FeaturePythonPyT(this),true); + PythonObject = Py::Object(new FeaturePythonPyT(this), true); } return Py::new_reference_to(PythonObject); } @@ -8781,4 +9473,4 @@ template<> PyObject* Sketcher::SketchObjectPython::getPyObject() { // explicit template instantiation template class SketcherExport FeaturePythonT; -} +}// namespace App diff --git a/src/Mod/Sketcher/App/SketchObject.h b/src/Mod/Sketcher/App/SketchObject.h index 9447fec986..e00df5403c 100644 --- a/src/Mod/Sketcher/App/SketchObject.h +++ b/src/Mod/Sketcher/App/SketchObject.h @@ -43,7 +43,7 @@ namespace Sketcher class SketchAnalysis; -class SketcherExport SketchObject : public Part::Part2DObject +class SketcherExport SketchObject: public Part::Part2DObject { PROPERTY_HEADER_WITH_OVERRIDE(Sketcher::SketchObject); @@ -56,34 +56,38 @@ public: The Geometry list contains the non-external Part::Geometry objects in the sketch. The list may be accessed directly, or indirectly via getInternalGeometry(). - Many of the methods in this class take geoId and posId parameters. A GeoId is a unique identifier for - geometry in the Sketch. geoId >= 0 means an index in the Geometry list. geoId < 0 refers to sketch - axes and external geometry. posId is a PointPos enum, documented in Constraint.h. + Many of the methods in this class take geoId and posId parameters. A GeoId is a unique + identifier for geometry in the Sketch. geoId >= 0 means an index in the Geometry list. geoId < + 0 refers to sketch axes and external geometry. posId is a PointPos enum, documented in + Constraint.h. */ - Part ::PropertyGeometryList Geometry; + Part ::PropertyGeometryList Geometry; Sketcher::PropertyConstraintList Constraints; - App ::PropertyLinkSubList ExternalGeometry; - App ::PropertyBool FullyConstrained; + App ::PropertyLinkSubList ExternalGeometry; + App ::PropertyBool FullyConstrained; /** @name methods override Feature */ //@{ short mustExecute() const override; - /// recalculate the Feature (if no recompute is needed see also solve() and solverNeedsUpdate boolean) - App::DocumentObjectExecReturn *execute() override; + /// recalculate the Feature (if no recompute is needed see also solve() and solverNeedsUpdate + /// boolean) + App::DocumentObjectExecReturn* execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "SketcherGui::ViewProviderSketch"; } //@} /** SketchObject can work in two modes: Recompute Mode and noRecomputes Mode - - In Recompute Mode, a recompute is necessary after each geometry addition to update the solver DoF (default) - - In NoRecomputes Mode, no recompute is necessary after a geometry addition. If a recompute is triggered - it is just less efficient. + - In Recompute Mode, a recompute is necessary after each geometry addition to update the + solver DoF (default) + - In NoRecomputes Mode, no recompute is necessary after a geometry addition. If a recompute + is triggered it is just less efficient. - This flag does not regulate whether this object will recompute or not if execute() or a recompute() is actually executed, - it just regulates whether the solver is called or not (i.e. whether it relies on - the solve of execute for the calculation) + This flag does not regulate whether this object will recompute or not if execute() or a + recompute() is actually executed, it just regulates whether the solver is called or not (i.e. + whether it relies on the solve of execute for the calculation) */ bool noRecomputes; @@ -92,24 +96,22 @@ public: \param geo - the geometry \retval bool - true if the geometry is supported */ - bool isSupportedGeometry(const Part::Geometry *geo) const; + bool isSupportedGeometry(const Part::Geometry* geo) const; /*! - \brief Add geometry to a sketch - It adds a copy with a different uuid (internally uses copy() instead of clone()) - \param geo - geometry to add - \param construction - true for construction lines - \retval int - GeoId of added element + \brief Add geometry to a sketch - It adds a copy with a different uuid (internally uses copy() + instead of clone()) \param geo - geometry to add \param construction - true for construction + lines \retval int - GeoId of added element */ - int addGeometry(const Part::Geometry *geo, bool construction=false); + int addGeometry(const Part::Geometry* geo, bool construction = false); /*! - \brief Add geometry to a sketch using up the provided newgeo. Caveat: It will use the provided newgeo with the uuid it has. - This is different from the addGeometry method with a naked pointer, where a different uuid is ensured. The caller is responsible - for provided a new or existing uuid, as necessary. - \param geo - geometry to add - \param construction - true for construction lines - \retval int - GeoId of added element + \brief Add geometry to a sketch using up the provided newgeo. Caveat: It will use the provided + newgeo with the uuid it has. This is different from the addGeometry method with a naked + pointer, where a different uuid is ensured. The caller is responsible for provided a new or + existing uuid, as necessary. \param geo - geometry to add \param construction - true for + construction lines \retval int - GeoId of added element */ - int addGeometry(std::unique_ptr newgeo, bool construction=false); + int addGeometry(std::unique_ptr newgeo, bool construction = false); /*! \brief Add multiple geometry elements to a sketch @@ -117,12 +119,12 @@ public: \param construction - true for construction lines \retval int - GeoId of last added element */ - int addGeometry(const std::vector &geoList, bool construction=false); + int addGeometry(const std::vector& geoList, bool construction = false); /*! \brief Deletes indicated geometry (by geoid). \param GeoId - the geometry to delete - \param deleteinternalgeo - if true deletes the associated and unconstraint internal geometry, otherwise deletes only the GeoId - \retval int - 0 if successful + \param deleteinternalgeo - if true deletes the associated and unconstraint internal geometry, + otherwise deletes only the GeoId \retval int - 0 if successful */ int delGeometry(int GeoId, bool deleteinternalgeo = true); /// Deletes just the GeoIds indicated, it does not look for internal geometry @@ -134,25 +136,25 @@ public: /// deletes all the constraints of the sketch int deleteAllConstraints(); /// add all constraints in the list - int addConstraints(const std::vector &ConstraintList); + int addConstraints(const std::vector& ConstraintList); /// Copy the constraints instead of cloning them and copying the expressions if any - int addCopyOfConstraints(const SketchObject &orig); + int addCopyOfConstraints(const SketchObject& orig); /// add constraint - int addConstraint(const Constraint *constraint); + int addConstraint(const Constraint* constraint); /// add constraint int addConstraint(std::unique_ptr constraint); /// delete constraint int delConstraint(int ConstrId); - /** deletes a group of constraints at once, if norecomputes is active, the default behaviour is that - * it will solve the sketch. + /** deletes a group of constraints at once, if norecomputes is active, the default behaviour is + * that it will solve the sketch. * - * If updating the Geometry property as a consequence of a (successful) solve() is not wanted, updategeometry=false, - * prevents the update. This allows to update the solve status (e.g. dof), without updating the geometry (i.e. make it - * move to fulfil the constraints). + * If updating the Geometry property as a consequence of a (successful) solve() is not wanted, + * updategeometry=false, prevents the update. This allows to update the solve status (e.g. dof), + * without updating the geometry (i.e. make it move to fulfil the constraints). */ - int delConstraints(std::vector ConstrIds, bool updategeometry=true); - int delConstraintOnPoint(int GeoId, PointPos PosId, bool onlyCoincident=true); - int delConstraintOnPoint(int VertexId, bool onlyCoincident=true); + int delConstraints(std::vector ConstrIds, bool updategeometry = true); + int delConstraintOnPoint(int GeoId, PointPos PosId, bool onlyCoincident = true); + int delConstraintOnPoint(int VertexId, bool onlyCoincident = true); /// Deletes all constraints referencing an external geometry int delConstraintsToExternal(); /// transfers all constraints of a point to a new point @@ -160,9 +162,9 @@ public: bool doNotTransformTangencies = false); /// Carbon copy another sketch geometry and constraints - int carbonCopy(App::DocumentObject * pObj, bool construction = true); + int carbonCopy(App::DocumentObject* pObj, bool construction = true); /// add an external geometry reference - int addExternal(App::DocumentObject *Obj, const char* SubName); + int addExternal(App::DocumentObject* Obj, const char* SubName); /** delete external * ExtGeoId >= 0 with 0 corresponding to the first user defined * external geometry @@ -178,23 +180,30 @@ public: * id==-2 for the vertical sketch axis * id<=-3 for user defined projected external geometries, */ - template < typename GeometryT = Part::Geometry, - typename = typename std::enable_if< - std::is_base_of::type>::value - >::type - > - const GeometryT * getGeometry(int GeoId) const; + template::type>::value>::type> + const GeometryT* getGeometry(int GeoId) const; std::unique_ptr getGeometryFacade(int GeoId) const; /// returns a list of all internal geometries - const std::vector &getInternalGeometry() const { return Geometry.getValues(); } + const std::vector& getInternalGeometry() const + { + return Geometry.getValues(); + } /// returns a list of projected external geometries - const std::vector &getExternalGeometry() const { return ExternalGeo; } + const std::vector& getExternalGeometry() const + { + return ExternalGeo; + } /// rebuilds external geometry (projection onto the sketch plane) void rebuildExternalGeometry(); /// returns the number of external Geometry entities - int getExternalGeometryCount() const { return ExternalGeo.size(); } + int getExternalGeometryCount() const + { + return ExternalGeo.size(); + } /// retrieves a vector containing both normal and external Geometry (including the sketch axes) std::vector getCompleteGeometry() const; @@ -214,30 +223,35 @@ public: */ int setUpSketch(); - /** Performs a full analysis of the addition of additional constraints without adding them to the sketch object */ - int diagnoseAdditionalConstraints(std::vector additionalconstraints); + /** Performs a full analysis of the addition of additional constraints without adding them to + * the sketch object */ + int diagnoseAdditionalConstraints(std::vector additionalconstraints); - /** solves the sketch and updates the geometry, but not all the dependent features (does not recompute) - When a recompute is necessary, recompute triggers execute() which solves the sketch and updates all dependent features - When a solve only is necessary (e.g. DoF changed), solve() solves the sketch and - updates the geometry (if updateGeoAfterSolving==true), but does not trigger any recompute. - @return 0 if no error, if error, the following codes in this order of priority: -4 if overconstrained, - -3 if conflicting, -1 if solver error, -2 if redundant constraints + /** solves the sketch and updates the geometry, but not all the dependent features (does not + recompute) When a recompute is necessary, recompute triggers execute() which solves the + sketch and updates all dependent features When a solve only is necessary (e.g. DoF changed), + solve() solves the sketch and updates the geometry (if updateGeoAfterSolving==true), but does + not trigger any recompute. + @return 0 if no error, if error, the following codes in this order of priority: -4 if + overconstrained, -3 if conflicting, -1 if solver error, -2 if redundant constraints */ - int solve(bool updateGeoAfterSolving=true); + int solve(bool updateGeoAfterSolving = true); /// set the datum of a Distance or Angle constraint and solve int setDatum(int ConstrId, double Datum); /// set the driving status of this constraint and solve int setDriving(int ConstrId, bool isdriving); /// get the driving status of this constraint - int getDriving(int ConstrId, bool &isdriving); + int getDriving(int ConstrId, bool& isdriving); /// toggle the driving status of this constraint - int toggleDriving(int ConstrId) {return setDriving(ConstrId, !Constraints.getValues()[ConstrId]->isDriving);} + int toggleDriving(int ConstrId) + { + return setDriving(ConstrId, !Constraints.getValues()[ConstrId]->isDriving); + } /// set the driving status of this constraint and solve int setActive(int ConstrId, bool isactive); /// get the driving status of this constraint - int getActive(int ConstrId, bool &isactive); + int getActive(int ConstrId, bool& isactive); /// toggle the driving status of this constraint int toggleActive(int ConstrId); @@ -251,11 +265,12 @@ public: /// set the driving status of a group of constraints at once int setVirtualSpace(std::vector constrIds, bool isinvirtualspace); /// get the driving status of this constraint - int getVirtualSpace(int ConstrId, bool &isinvirtualspace) const; + int getVirtualSpace(int ConstrId, bool& isinvirtualspace) const; /// toggle the driving status of this constraint int toggleVirtualSpace(int ConstrId); /// move this point to a new location and solve - int movePoint(int GeoId, PointPos PosId, const Base::Vector3d& toPoint, bool relative=false, bool updateGeoBeforeMoving=false); + int movePoint(int GeoId, PointPos PosId, const Base::Vector3d& toPoint, bool relative = false, + bool updateGeoBeforeMoving = false); /// retrieves the coordinates of a point Base::Vector3d getPoint(int GeoId, PointPos PosId) const; @@ -271,44 +286,46 @@ public: \param createCorner - keep geoId/pos as a Point and keep as many constraints as possible \retval - 0 on success, -1 on failure */ - int fillet(int geoId, PointPos pos, double radius, bool trim=true, bool preserveCorner=false); + int fillet(int geoId, PointPos pos, double radius, bool trim = true, + bool preserveCorner = false); /*! \brief More general form of fillet \param geoId1, geoId2 - geoId for two lines (which don't necessarily have to coincide) - \param refPnt1, refPnt2 - reference points on the input geometry, used to influence the free fillet variables - \param radius - fillet radius - \param trim - if false, leaves the original lines untouched - \param preserveCorner - if the lines are coincident, place a Point where they meet and keep as many - of the existing constraints as possible - \retval - 0 on success, -1 on failure + \param refPnt1, refPnt2 - reference points on the input geometry, used to influence the free + fillet variables \param radius - fillet radius \param trim - if false, leaves the original + lines untouched \param preserveCorner - if the lines are coincident, place a Point where they + meet and keep as many of the existing constraints as possible \retval - 0 on success, -1 on + failure */ - int fillet(int geoId1, int geoId2, - const Base::Vector3d& refPnt1, const Base::Vector3d& refPnt2, - double radius, bool trim=true, bool createCorner=false); + int fillet(int geoId1, int geoId2, const Base::Vector3d& refPnt1, const Base::Vector3d& refPnt2, + double radius, bool trim = true, bool createCorner = false); /// trim a curve int trim(int geoId, const Base::Vector3d& point); /// extend a curve int extend(int geoId, double increment, PointPos endPoint); /// split a curve - int split(int geoId, const Base::Vector3d &point); + int split(int geoId, const Base::Vector3d& point); /*! \brief Join one or two curves at the given end points \details The combined curve will be a b-spline \param geoId1, posId1, geoId2, posId2: the end points to join \retval - 0 on success, -1 on failure */ - int join(int geoId1, Sketcher::PointPos posId1, - int geoId2, Sketcher::PointPos posId2); + int join(int geoId1, Sketcher::PointPos posId1, int geoId2, Sketcher::PointPos posId2); /// adds symmetric geometric elements with respect to the refGeoId (line or point) - int addSymmetric(const std::vector &geoIdList, int refGeoId, Sketcher::PointPos refPosId=Sketcher::PointPos::none); - /// with default parameters adds a copy of the geometric elements displaced by the displacement vector. - /// It creates an array of csize elements in the direction of the displacement vector by rsize elements in the - /// direction perpendicular to the displacement vector, wherein the modulus of this perpendicular vector is scaled by perpscale. - int addCopy(const std::vector &geoIdList, const Base::Vector3d& displacement, bool moveonly = false, bool clone=false, int csize=2, int rsize=1, bool constraindisplacement = false, double perpscale = 1.0); + int addSymmetric(const std::vector& geoIdList, int refGeoId, + Sketcher::PointPos refPosId = Sketcher::PointPos::none); + /// with default parameters adds a copy of the geometric elements displaced by the displacement + /// vector. It creates an array of csize elements in the direction of the displacement vector by + /// rsize elements in the direction perpendicular to the displacement vector, wherein the + /// modulus of this perpendicular vector is scaled by perpscale. + int addCopy(const std::vector& geoIdList, const Base::Vector3d& displacement, + bool moveonly = false, bool clone = false, int csize = 2, int rsize = 1, + bool constraindisplacement = false, double perpscale = 1.0); - int removeAxesAlignment(const std::vector &geoIdList); + int removeAxesAlignment(const std::vector& geoIdList); /// Exposes all internal geometry of an object supporting internal geometry /*! * \return -1 on error @@ -317,15 +334,16 @@ public: /*! \brief Deletes all unused (not further constrained) internal geometry \param GeoId - the geometry having the internal geometry to delete - \param delgeoid - if true in addition to the unused internal geometry also deletes the GeoId geometry - \retval int - returns -1 on error, otherwise the number of deleted elements + \param delgeoid - if true in addition to the unused internal geometry also deletes the GeoId + geometry \retval int - returns -1 on error, otherwise the number of deleted elements */ - int deleteUnusedInternalGeometry(int GeoId, bool delgeoid=false); + int deleteUnusedInternalGeometry(int GeoId, bool delgeoid = false); /*! \brief Approximates the given geometry with a B-spline \param GeoId - the geometry to approximate - \param delgeoid - if true in addition to the unused internal geometry also deletes the GeoId geometry - \retval bool - returns true if the approximation succeeded, or false if it did not succeed. + \param delgeoid - if true in addition to the unused internal geometry also deletes the GeoId + geometry \retval bool - returns true if the approximation succeeded, or false if it did not + succeed. */ bool convertToNURBS(int GeoId); @@ -333,7 +351,8 @@ public: \brief Increases the degree of a BSpline by degreeincrement, which defaults to 1 \param GeoId - the geometry of type bspline to increase the degree \param degreeincrement - the increment in number of degrees to effect - \retval bool - returns true if the increase in degree succeeded, or false if it did not succeed. + \retval bool - returns true if the increase in degree succeeded, or false if it did not + succeed. */ bool increaseBSplineDegree(int GeoId, int degreeincrement = 1); @@ -341,32 +360,40 @@ public: \brief Decreases the degree of a BSpline by degreedecrement, which defaults to 1 \param GeoId - the geometry of type bspline to increase the degree \param degreedecrement - the decrement in number of degrees to effect - \retval bool - returns true if the decrease in degree succeeded, or false if it did not succeed. + \retval bool - returns true if the decrease in degree succeeded, or false if it did not + succeed. */ bool decreaseBSplineDegree(int GeoId, int degreedecrement = 1); /*! - \brief Increases or Decreases the multiplicity of a BSpline knot by the multiplicityincr param, which defaults to 1, if the result is multiplicity zero, the knot is removed - \param GeoId - the geometry of type bspline to increase the degree - \param knotIndex - the index of the knot to modify (note that index is OCC consistent, so 1<=knotindex<=knots) - \param multiplicityincr - the increment (positive value) or decrement (negative value) of multiplicity of the knot + \brief Increases or Decreases the multiplicity of a BSpline knot by the multiplicityincr param, + which defaults to 1, if the result is multiplicity zero, the knot is removed \param GeoId - the + geometry of type bspline to increase the degree \param knotIndex - the index of the knot to + modify (note that index is OCC consistent, so 1<=knotindex<=knots) \param multiplicityincr - + the increment (positive value) or decrement (negative value) of multiplicity of the knot \retval bool - returns true if the operation succeeded, or false if it did not succeed. */ bool modifyBSplineKnotMultiplicity(int GeoId, int knotIndex, int multiplicityincr = 1); /*! - \brief Inserts a knot in the BSpline at `param` with given `multiplicity`. If the knot already exists, its multiplicity is increased by `multiplicity`. - \param GeoId - the geometry of type bspline to increase the degree - \param param - the parameter value where the knot is to be placed - \param multiplicity - multiplicity of the inserted knot - \retval bool - returns true if the operation succeeded, or false if it did not succeed. + \brief Inserts a knot in the BSpline at `param` with given `multiplicity`. If the knot already + exists, its multiplicity is increased by `multiplicity`. \param GeoId - the geometry of type + bspline to increase the degree \param param - the parameter value where the knot is to be + placed \param multiplicity - multiplicity of the inserted knot \retval bool - returns true if + the operation succeeded, or false if it did not succeed. */ bool insertBSplineKnot(int GeoId, double param, int multiplicity = 1); /// retrieves for a Vertex number the corresponding GeoId and PosId - void getGeoVertexIndex(int VertexId, int &GeoId, PointPos &PosId) const; - int getHighestVertexIndex() const { return VertexId2GeoId.size() - 1; } // Most recently created - int getHighestCurveIndex() const { return Geometry.getSize() - 1; } + void getGeoVertexIndex(int VertexId, int& GeoId, PointPos& PosId) const; + int getHighestVertexIndex() const + { + return VertexId2GeoId.size() - 1; + }// Most recently created + int getHighestCurveIndex() const + { + return Geometry.getSize() - 1; + } void rebuildVertexIndex(); /// retrieves for a GeoId and PosId the Vertex number @@ -374,28 +401,32 @@ public: // retrieves an array of maps, each map containing the points that are coincidence by virtue of // any number of direct or indirect coincidence constraints - const std::vector< std::map > getCoincidenceGroups(); - // returns if the given geoId is fixed (coincident) with external geometry on any of the possible relevant points - void isCoincidentWithExternalGeometry(int GeoId, bool &start_external, bool &mid_external, bool &end_external); - // returns a map containing all the GeoIds that are coincident with the given point as keys, and the PosIds as values associated - // with the keys. + const std::vector> getCoincidenceGroups(); + // returns if the given geoId is fixed (coincident) with external geometry on any of the + // possible relevant points + void isCoincidentWithExternalGeometry(int GeoId, bool& start_external, bool& mid_external, + bool& end_external); + // returns a map containing all the GeoIds that are coincident with the given point as keys, and + // the PosIds as values associated with the keys. const std::map getAllCoincidentPoints(int GeoId, PointPos PosId); - /// retrieves for a Vertex number a list with all coincident points (sharing a single coincidence constraint) - void getDirectlyCoincidentPoints(int GeoId, PointPos PosId, std::vector &GeoIdList, - std::vector &PosIdList); - void getDirectlyCoincidentPoints(int VertexId, std::vector &GeoIdList, std::vector &PosIdList); + /// retrieves for a Vertex number a list with all coincident points (sharing a single + /// coincidence constraint) + void getDirectlyCoincidentPoints(int GeoId, PointPos PosId, std::vector& GeoIdList, + std::vector& PosIdList); + void getDirectlyCoincidentPoints(int VertexId, std::vector& GeoIdList, + std::vector& PosIdList); bool arePointsCoincident(int GeoId1, PointPos PosId1, int GeoId2, PointPos PosId2); /// returns a list of indices of all constraints involving given GeoId - void getConstraintIndices(int GeoId, std::vector &constraintList); + void getConstraintIndices(int GeoId, std::vector& constraintList); /// generates a warning message about constraint conflicts and appends it to the given message - static void appendConflictMsg(const std::vector &conflicting, std::string &msg); + static void appendConflictMsg(const std::vector& conflicting, std::string& msg); /// generates a warning message about redundant constraints and appends it to the given message - static void appendRedundantMsg(const std::vector &redundant, std::string &msg); + static void appendRedundantMsg(const std::vector& redundant, std::string& msg); /// generates a warning message about malformed constraints and appends it to the given message - static void appendMalformedConstraintsMsg(const std::vector &malformed, std::string &msg); + static void appendMalformedConstraintsMsg(const std::vector& malformed, std::string& msg); double calculateAngleViaPoint(int geoId1, int geoId2, double px, double py); bool isPointOnCurve(int geoIdCurve, double px, double py); @@ -404,23 +435,24 @@ public: /// returns whether a given constraint has an associated expression or not bool constraintHasExpression(int constrid) const; - ///porting functions + /// porting functions int port_reversedExternalArcs(bool justAnalyze); // from base class - PyObject *getPyObject() override; + PyObject* getPyObject() override; unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; /// returns the number of construction lines (to be used as axes) int getAxisCount() const override; - /// retrieves an axis iterating through the construction lines of the sketch (indices start at 0) + /// retrieves an axis iterating through the construction lines of the sketch (indices start at + /// 0) Base::Axis getAxis(int axId) const override; /// verify and accept the assigned geometry void acceptGeometry() override; /// Check if constraint has invalid indexes - bool evaluateConstraint(const Constraint *constraint) const; + bool evaluateConstraint(const Constraint* constraint) const; /// Check for constraints with invalid indexes bool evaluateConstraints() const; /// Remove constraints with invalid indexes @@ -431,109 +463,170 @@ public: void validateExternalLinks(); /// gets DoF of last solver execution - inline int getLastDoF() const {return lastDoF;} + inline int getLastDoF() const + { + return lastDoF; + } /// gets HasConflicts status of last solver execution - inline bool getLastHasConflicts() const {return lastHasConflict;} + inline bool getLastHasConflicts() const + { + return lastHasConflict; + } /// gets HasRedundancies status of last solver execution - inline bool getLastHasRedundancies() const {return lastHasRedundancies;} + inline bool getLastHasRedundancies() const + { + return lastHasRedundancies; + } /// gets HasRedundancies status of last solver execution - inline bool getLastHasPartialRedundancies() const {return lastHasPartialRedundancies;} + inline bool getLastHasPartialRedundancies() const + { + return lastHasPartialRedundancies; + } /// gets HasMalformedConstraints status of last solver execution - inline bool getLastHasMalformedConstraints() const {return lastHasMalformedConstraints;} + inline bool getLastHasMalformedConstraints() const + { + return lastHasMalformedConstraints; + } /// gets solver status of last solver execution - inline int getLastSolverStatus() const {return lastSolverStatus;} + inline int getLastSolverStatus() const + { + return lastSolverStatus; + } /// gets solver SolveTime of last solver execution - inline float getLastSolveTime() const {return lastSolveTime;} + inline float getLastSolveTime() const + { + return lastSolveTime; + } /// gets the conflicting constraints of the last solver execution - inline const std::vector &getLastConflicting() const { return lastConflicting; } + inline const std::vector& getLastConflicting() const + { + return lastConflicting; + } /// gets the redundant constraints of last solver execution - inline const std::vector &getLastRedundant() const { return lastRedundant; } + inline const std::vector& getLastRedundant() const + { + return lastRedundant; + } /// gets the redundant constraints of last solver execution - inline const std::vector &getLastPartiallyRedundant() const { return lastPartiallyRedundant; } + inline const std::vector& getLastPartiallyRedundant() const + { + return lastPartiallyRedundant; + } /// gets the redundant constraints of last solver execution - inline const std::vector &getLastMalformedConstraints() const { return lastMalformedConstraints; } + inline const std::vector& getLastMalformedConstraints() const + { + return lastMalformedConstraints; + } public: /* Solver exposed interface */ /// gets the solved sketch as a reference - inline const Sketch &getSolvedSketch() const {return solvedSketch;} - /// enables/disables solver initial solution recalculation when moving point mode (useful for dragging) - inline void setRecalculateInitialSolutionWhileMovingPoint(bool recalculateInitialSolutionWhileMovingPoint) - {solvedSketch.setRecalculateInitialSolutionWhileMovingPoint(recalculateInitialSolutionWhileMovingPoint);} - /// Forwards a request for a temporary initMove to the solver using the current sketch state as a reference (enables dragging) - inline int initTemporaryMove(int geoId, PointPos pos, bool fine=true); - /// Forwards a request for a temporary initBSplinePieceMove to the solver using the current sketch state as a reference (enables dragging) - inline int initTemporaryBSplinePieceMove(int geoId, PointPos pos, const Base::Vector3d& firstPoint, bool fine=true); - /** Forwards a request for point or curve temporary movement to the solver using the current state as a reference (enables dragging). - * NOTE: A temporary move operation must always be preceded by a initTemporaryMove() operation. + inline const Sketch& getSolvedSketch() const + { + return solvedSketch; + } + /// enables/disables solver initial solution recalculation when moving point mode (useful for + /// dragging) + inline void + setRecalculateInitialSolutionWhileMovingPoint(bool recalculateInitialSolutionWhileMovingPoint) + { + solvedSketch.setRecalculateInitialSolutionWhileMovingPoint( + recalculateInitialSolutionWhileMovingPoint); + } + /// Forwards a request for a temporary initMove to the solver using the current sketch state as + /// a reference (enables dragging) + inline int initTemporaryMove(int geoId, PointPos pos, bool fine = true); + /// Forwards a request for a temporary initBSplinePieceMove to the solver using the current + /// sketch state as a reference (enables dragging) + inline int initTemporaryBSplinePieceMove(int geoId, PointPos pos, + const Base::Vector3d& firstPoint, bool fine = true); + /** Forwards a request for point or curve temporary movement to the solver using the current + * state as a reference (enables dragging). NOTE: A temporary move operation must always be + * preceded by a initTemporaryMove() operation. */ - inline int moveTemporaryPoint(int geoId, PointPos pos, Base::Vector3d toPoint, bool relative=false); + inline int moveTemporaryPoint(int geoId, PointPos pos, Base::Vector3d toPoint, + bool relative = false); /// forwards a request to update an extension of a geometry of the solver to the solver. - inline void updateSolverExtension(int geoId, std::unique_ptr && ext) - { return solvedSketch.updateExtension(geoId, std::move(ext));} + inline void updateSolverExtension(int geoId, std::unique_ptr&& ext) + { + return solvedSketch.updateExtension(geoId, std::move(ext)); + } public: - /// returns the geometric elements/vertex which the solver detects as having dependent parameters. - /// these parameters relate to not fully constraint edges/vertices. - void getGeometryWithDependentParameters(std::vector>& geometrymap); + /// returns the geometric elements/vertex which the solver detects as having dependent + /// parameters. these parameters relate to not fully constraint edges/vertices. + void getGeometryWithDependentParameters(std::vector>& geometrymap); /// Flag to allow external geometry from other bodies than the one this sketch belongs to - bool isAllowedOtherBody() const { + bool isAllowedOtherBody() const + { return allowOtherBody; } - void setAllowOtherBody(bool on) { + void setAllowOtherBody(bool on) + { allowOtherBody = on; } /// Flag to allow carbon copy from misaligned geometry - bool isAllowedUnaligned() const { + bool isAllowedUnaligned() const + { return allowUnaligned; } - void setAllowUnaligned(bool on) { + void setAllowUnaligned(bool on) + { allowUnaligned = on; } - enum eReasonList{ + enum eReasonList + { rlAllowed, rlOtherDoc, rlCircularReference, rlOtherPart, rlOtherBody, - rlOtherBodyWithLinks, // for carbon copy - rlNotASketch, // for carbon copy - rlNonParallel, // for carbon copy - rlAxesMisaligned, // for carbon copy - rlOriginsMisaligned // for carbon copy + rlOtherBodyWithLinks,// for carbon copy + rlNotASketch, // for carbon copy + rlNonParallel, // for carbon copy + rlAxesMisaligned, // for carbon copy + rlOriginsMisaligned // for carbon copy }; /// Return true if this object is allowed as external geometry for the /// sketch. rsn argument receives the reason for disallowing. - bool isExternalAllowed(App::Document *pDoc, App::DocumentObject *pObj, eReasonList* rsn = nullptr) const; + bool isExternalAllowed(App::Document* pDoc, App::DocumentObject* pObj, + eReasonList* rsn = nullptr) const; - bool isCarbonCopyAllowed(App::Document *pDoc, App::DocumentObject *pObj, bool & xinv, bool & yinv, eReasonList* rsn = nullptr) const; + bool isCarbonCopyAllowed(App::Document* pDoc, App::DocumentObject* pObj, bool& xinv, bool& yinv, + eReasonList* rsn = nullptr) const; - bool isPerformingInternalTransaction() const {return internaltransaction;}; + bool isPerformingInternalTransaction() const + { + return internaltransaction; + }; - /** retrieves intersection points of this curve with the closest two curves around a point of this curve. + /** retrieves intersection points of this curve with the closest two curves around a point of + * this curve. * - it includes internal and external intersecting geometry. * - it returns GeoEnum::GeoUndef if no intersection is found. */ - bool seekTrimPoints(int GeoId, const Base::Vector3d &point, - int &GeoId1, Base::Vector3d &intersect1, - int &GeoId2, Base::Vector3d &intersect2); + bool seekTrimPoints(int GeoId, const Base::Vector3d& point, int& GeoId1, + Base::Vector3d& intersect1, int& GeoId2, Base::Vector3d& intersect2); + public: // Analyser functions - int autoConstraint(double precision = Precision::Confusion() * 1000, double angleprecision = M_PI/20, bool includeconstruction = true); + int autoConstraint(double precision = Precision::Confusion() * 1000, + double angleprecision = M_PI / 20, bool includeconstruction = true); - int detectMissingPointOnPointConstraints(double precision = Precision::Confusion() * 1000, bool includeconstruction = true); - void analyseMissingPointOnPointCoincident(double angleprecision = M_PI/8); - int detectMissingVerticalHorizontalConstraints(double angleprecision = M_PI/8); + int detectMissingPointOnPointConstraints(double precision = Precision::Confusion() * 1000, + bool includeconstruction = true); + void analyseMissingPointOnPointCoincident(double angleprecision = M_PI / 8); + int detectMissingVerticalHorizontalConstraints(double angleprecision = M_PI / 8); int detectMissingEqualityConstraints(double precision); - std::vector &getMissingPointOnPointConstraints(); - std::vector &getMissingVerticalHorizontalConstraints(); - std::vector &getMissingLineEqualityConstraints(); - std::vector &getMissingRadiusConstraints(); + std::vector& getMissingPointOnPointConstraints(); + std::vector& getMissingVerticalHorizontalConstraints(); + std::vector& getMissingLineEqualityConstraints(); + std::vector& getMissingRadiusConstraints(); - void setMissingRadiusConstraints(std::vector &cl); + void setMissingRadiusConstraints(std::vector& cl); void setMissingLineEqualityConstraints(std::vector& cl); void setMissingVerticalHorizontalConstraints(std::vector& cl); void setMissingPointOnPointConstraints(std::vector& cl); @@ -551,9 +644,9 @@ public: // Validation routines std::vector getOpenVertices() const; -public: // geometry extension functionalities for single element sketch object user convenience +public:// geometry extension functionalities for single element sketch object user convenience int setGeometryId(int GeoId, long id); - int getGeometryId(int GeoId, long &id) const; + int getGeometryId(int GeoId, long& id) const; protected: /// get called by the container when a property has changed @@ -561,28 +654,31 @@ protected: void onDocumentRestored() override; void restoreFinished() override; - void setExpression(const App::ObjectIdentifier &path, std::shared_ptr expr) override; + void setExpression(const App::ObjectIdentifier& path, + std::shared_ptr expr) override; - std::string validateExpression(const App::ObjectIdentifier &path, std::shared_ptr expr); + std::string validateExpression(const App::ObjectIdentifier& path, + std::shared_ptr expr); - void constraintsRenamed(const std::map &renamed); - void constraintsRemoved(const std::set &removed); + void constraintsRenamed(const std::map& renamed); + void constraintsRemoved(const std::set& removed); /*! \brief Returns a list of supported geometries from the input list \param geoList - the geometry list \retval list - the supported geometry list */ - std::vector supportedGeometry(const std::vector &geoList) const; + std::vector + supportedGeometry(const std::vector& geoList) const; /*! \brief Transfer constraints on lines being filleted. - Since filleting moves the endpoints of the input geometry, existing constraints may no longer be - sensible. If fillet() was called with preserveCorner=false, the constraints are simply deleted. - But if the lines are coincident and preserveCorner=true, we can preserve most constraints on the - old end points by moving them to the preserved corner, or transforming distance constraints on - straight lines into point-to-point distance constraints. + Since filleting moves the endpoints of the input geometry, existing constraints may no longer + be sensible. If fillet() was called with preserveCorner=false, the constraints are simply + deleted. But if the lines are coincident and preserveCorner=true, we can preserve most + constraints on the old end points by moving them to the preserved corner, or transforming + distance constraints on straight lines into point-to-point distance constraints. \param geoId1, podId1, geoId2, posId2 - The two lines that have just been filleted */ @@ -597,43 +693,39 @@ protected: // migration functions void migrateSketch(); - static void appendConstraintsMsg(const std::vector &vector, - const std::string & singularmsg, - const std::string & pluralmsg, - std::string &msg); + static void appendConstraintsMsg(const std::vector& vector, const std::string& singularmsg, + const std::string& pluralmsg, std::string& msg); // retrieves redundant, conflicting and malformed constraint information from the solver void retrieveSolverDiagnostics(); // retrieves whether a geometry blocked state corresponds to this constraint // returns true of the constraint is of Block type, false otherwise - bool getBlockedState(const Constraint * cstr, bool & blockedstate) const; + bool getBlockedState(const Constraint* cstr, bool& blockedstate) const; // retrieves the geometry blocked state corresponding to this constraint // returns true of the constraint is of InternalAlignment type, false otherwise - bool getInternalTypeState(const Constraint * cstr, Sketcher::InternalType::InternalType & internaltypestate) const; + bool getInternalTypeState(const Constraint* cstr, + Sketcher::InternalType::InternalType& internaltypestate) const; - // Checks whether the geometry state stored in the geometry extension matches the current sketcher situation (e.g. constraints) - // and corrects the state if not matching. + // Checks whether the geometry state stored in the geometry extension matches the current + // sketcher situation (e.g. constraints) and corrects the state if not matching. void synchroniseGeometryState(); // helper function to create a new constraint and move it to the Constraint Property - void addConstraint( Sketcher::ConstraintType constrType, - int firstGeoId, - Sketcher::PointPos firstPos, - int secondGeoId = GeoEnum::GeoUndef, - Sketcher::PointPos secondPos = Sketcher::PointPos::none, - int thirdGeoId = GeoEnum::GeoUndef, - Sketcher::PointPos thirdPos = Sketcher::PointPos::none); + void addConstraint(Sketcher::ConstraintType constrType, int firstGeoId, + Sketcher::PointPos firstPos, int secondGeoId = GeoEnum::GeoUndef, + Sketcher::PointPos secondPos = Sketcher::PointPos::none, + int thirdGeoId = GeoEnum::GeoUndef, + Sketcher::PointPos thirdPos = Sketcher::PointPos::none); // creates a new constraint - std::unique_ptr createConstraint( Sketcher::ConstraintType constrType, - int firstGeoId, - Sketcher::PointPos firstPos, - int secondGeoId = GeoEnum::GeoUndef, - Sketcher::PointPos secondPos = Sketcher::PointPos::none, - int thirdGeoId = GeoEnum::GeoUndef, - Sketcher::PointPos thirdPos = Sketcher::PointPos::none); + std::unique_ptr + createConstraint(Sketcher::ConstraintType constrType, int firstGeoId, + Sketcher::PointPos firstPos, int secondGeoId = GeoEnum::GeoUndef, + Sketcher::PointPos secondPos = Sketcher::PointPos::none, + int thirdGeoId = GeoEnum::GeoUndef, + Sketcher::PointPos thirdPos = Sketcher::PointPos::none); private: /// Flag to allow external geometry from other bodies than the one this sketch belongs to @@ -642,15 +734,16 @@ private: /// Flag to allow carbon copy from misaligned geometry bool allowUnaligned; - std::vector ExternalGeo; + std::vector ExternalGeo; std::vector VertexId2GeoId; std::vector VertexId2PosId; Sketch solvedSketch; - /** this internal flag indicate that an operation modifying the geometry, but not the DoF of the sketch took place (e.g. toggle construction), - so if next action is a movement of a point (movePoint), the geometry must be updated first. + /** this internal flag indicate that an operation modifying the geometry, but not the DoF of the + sketch took place (e.g. toggle construction), so if next action is a movement of a point + (movePoint), the geometry must be updated first. */ bool solverNeedsUpdate; @@ -672,73 +765,79 @@ private: bool AutoLockTangencyAndPerpty(Constraint* cstr, bool bForce = false, bool bLock = true); - // Geometry Extensions is used to store on geometry a state that is enforced by pre-existing constraints - // Like Block constraint and InternalAlignment constraint. This enables (more) convenient handling in ViewProviderSketch - // and solver. + // Geometry Extensions is used to store on geometry a state that is enforced by pre-existing + // constraints Like Block constraint and InternalAlignment constraint. This enables (more) + // convenient handling in ViewProviderSketch and solver. // - // These functions are responsible for updating the Geometry State, currently Geometry Mode (Blocked) and - // Geometry InternalType (BSplineKnot, BSplinePole). + // These functions are responsible for updating the Geometry State, currently Geometry Mode + // (Blocked) and Geometry InternalType (BSplineKnot, BSplinePole). // // The data life model for handling this state is as follows: - // 1. Upon restore, any migration is handled to set the status for legacy files (backwards compatibility) - // 2. Functionality adding constraints (of the relevant type) calls addGeometryState to set the status - // 3. Functionality removing constraints (of the relevant type) calls removeGeometryState to remove the status + // 1. Upon restore, any migration is handled to set the status for legacy files (backwards + // compatibility) + // 2. Functionality adding constraints (of the relevant type) calls addGeometryState to set the + // status + // 3. Functionality removing constraints (of the relevant type) calls removeGeometryState to + // remove the status // 4. Save mechanism will ensure persistence. void addGeometryState(const Constraint* cstr) const; void removeGeometryState(const Constraint* cstr) const; - SketchAnalysis * analyser; + SketchAnalysis* analyser; bool internaltransaction; - bool managedoperation; // indicates whether changes to properties are the deed of SketchObject or not (for input validation) + // indicates whether changes to properties are the deed of SketchObject or not (for input + // validation) + bool managedoperation; }; -inline int SketchObject::initTemporaryMove(int geoId, PointPos pos, bool fine/*=true*/) +inline int SketchObject::initTemporaryMove(int geoId, PointPos pos, bool fine /*=true*/) { // if a previous operation did not update the geometry (including geometry extensions) // or constraints (including any deleted pointer, as in renameConstraint) of the solver, // here we update them before starting a temporary operation. - if(solverNeedsUpdate) + if (solverNeedsUpdate) solve(); - return solvedSketch.initMove(geoId,pos,fine); + return solvedSketch.initMove(geoId, pos, fine); } -inline int SketchObject::initTemporaryBSplinePieceMove(int geoId, PointPos pos, const Base::Vector3d& firstPoint, bool fine) +inline int SketchObject::initTemporaryBSplinePieceMove(int geoId, PointPos pos, + const Base::Vector3d& firstPoint, bool fine) { // if a previous operation did not update the geometry (including geometry extensions) // or constraints (including any deleted pointer, as in renameConstraint) of the solver, // here we update them before starting a temporary operation. - if(solverNeedsUpdate) + if (solverNeedsUpdate) solve(); - return solvedSketch.initBSplinePieceMove(geoId,pos,firstPoint,fine); + return solvedSketch.initBSplinePieceMove(geoId, pos, firstPoint, fine); } -inline int SketchObject::moveTemporaryPoint(int geoId, PointPos pos, Base::Vector3d toPoint, bool relative/*=false*/) +inline int SketchObject::moveTemporaryPoint(int geoId, PointPos pos, Base::Vector3d toPoint, + bool relative /*=false*/) { return solvedSketch.movePoint(geoId, pos, toPoint, relative); } -template < typename GeometryT, - typename > -const GeometryT * SketchObject::getGeometry(int GeoId) const +template +const GeometryT* SketchObject::getGeometry(int GeoId) const { if (GeoId >= 0) { - const std::vector &geomlist = getInternalGeometry(); + const std::vector& geomlist = getInternalGeometry(); if (GeoId < int(geomlist.size())) - return static_cast(geomlist[GeoId]); + return static_cast(geomlist[GeoId]); } else if (-GeoId <= int(ExternalGeo.size())) - return static_cast(ExternalGeo[-GeoId-1]); + return static_cast(ExternalGeo[-GeoId - 1]); return nullptr; } using SketchObjectPython = App::FeaturePythonT; -} //namespace Sketcher +}// namespace Sketcher -#endif // SKETCHER_SKETCHOBJECT_H +#endif// SKETCHER_SKETCHOBJECT_H diff --git a/src/Mod/Sketcher/App/SketchObjectPyImp.cpp b/src/Mod/Sketcher/App/SketchObjectPyImp.cpp index 20aac8aa42..c6ab5ead85 100644 --- a/src/Mod/Sketcher/App/SketchObjectPyImp.cpp +++ b/src/Mod/Sketcher/App/SketchObjectPyImp.cpp @@ -22,10 +22,10 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include +#include +#include -# include +#include #endif #include @@ -38,7 +38,9 @@ // inclusion of the generated files (generated out of SketchObjectSFPy.xml) #include "SketchObjectPy.h" + #include "SketchObjectPy.cpp" + // other python types #include "ConstraintPy.h" #include "GeometryFacadePy.h" @@ -52,7 +54,7 @@ std::string SketchObjectPy::representation() const return ""; } -PyObject* SketchObjectPy::solve(PyObject *args) +PyObject* SketchObjectPy::solve(PyObject* args) { if (!PyArg_ParseTuple(args, "")) return nullptr; @@ -60,24 +62,24 @@ PyObject* SketchObjectPy::solve(PyObject *args) return Py_BuildValue("i", ret); } -PyObject* SketchObjectPy::addGeometry(PyObject *args) +PyObject* SketchObjectPy::addGeometry(PyObject* args) { - PyObject *pcObj; - PyObject* construction; // this is an optional argument default false + PyObject* pcObj; + PyObject* construction;// this is an optional argument default false bool isConstruction; if (!PyArg_ParseTuple(args, "OO!", &pcObj, &PyBool_Type, &construction)) { PyErr_Clear(); if (!PyArg_ParseTuple(args, "O", &pcObj)) return nullptr; else - isConstruction=false; + isConstruction = false; } else { isConstruction = Base::asBoolean(construction); } if (PyObject_TypeCheck(pcObj, &(Part::GeometryPy::Type))) { - Part::Geometry *geo = static_cast(pcObj)->getGeometryPtr(); + Part::Geometry* geo = static_cast(pcObj)->getGeometryPtr(); int ret; // An arc created with Part.Arc will be converted into a Part.ArcOfCircle if (geo->getTypeId() == Part::GeomTrimmedCurve::getClassTypeId()) { @@ -88,13 +90,13 @@ PyObject* SketchObjectPy::addGeometry(PyObject *args) // create the definition struct for that geom Part::GeomArcOfCircle aoc; aoc.setHandle(trim); - ret = this->getSketchObjectPtr()->addGeometry(&aoc,isConstruction); + ret = this->getSketchObjectPtr()->addGeometry(&aoc, isConstruction); } else if (!ellipse.IsNull()) { // create the definition struct for that geom Part::GeomArcOfEllipse aoe; aoe.setHandle(trim); - ret = this->getSketchObjectPtr()->addGeometry(&aoe,isConstruction); + ret = this->getSketchObjectPtr()->addGeometry(&aoe, isConstruction); } else { std::stringstream str; @@ -103,16 +105,16 @@ PyObject* SketchObjectPy::addGeometry(PyObject *args) return nullptr; } } - else if (geo->getTypeId() == Part::GeomPoint::getClassTypeId() || - geo->getTypeId() == Part::GeomCircle::getClassTypeId() || - geo->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() || - geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() || - geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - ret = this->getSketchObjectPtr()->addGeometry(geo,isConstruction); + else if (geo->getTypeId() == Part::GeomPoint::getClassTypeId() + || geo->getTypeId() == Part::GeomCircle::getClassTypeId() + || geo->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() + || geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() + || geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + ret = this->getSketchObjectPtr()->addGeometry(geo, isConstruction); } else { std::stringstream str; @@ -122,20 +124,22 @@ PyObject* SketchObjectPy::addGeometry(PyObject *args) } return Py::new_reference_to(Py::Long(ret)); } - else if (PyObject_TypeCheck(pcObj, &(PyList_Type)) || - PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { - std::vector geoList; - std::vector > tmpList; + else if (PyObject_TypeCheck(pcObj, &(PyList_Type)) + || PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { + std::vector geoList; + std::vector> tmpList; Py::Sequence list(pcObj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(Part::GeometryPy::Type))) { - Part::Geometry *geo = static_cast((*it).ptr())->getGeometryPtr(); + Part::Geometry* geo = static_cast((*it).ptr())->getGeometryPtr(); // An arc created with Part.Arc will be converted into a Part.ArcOfCircle if (geo->getTypeId() == Part::GeomTrimmedCurve::getClassTypeId()) { - Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast(geo->handle()); + Handle(Geom_TrimmedCurve) trim = + Handle(Geom_TrimmedCurve)::DownCast(geo->handle()); Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast(trim->BasisCurve()); - Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast(trim->BasisCurve()); + Handle(Geom_Ellipse) ellipse = + Handle(Geom_Ellipse)::DownCast(trim->BasisCurve()); if (!circle.IsNull()) { // create the definition struct for that geom std::shared_ptr aoc(new Part::GeomArcOfCircle()); @@ -157,15 +161,15 @@ PyObject* SketchObjectPy::addGeometry(PyObject *args) return nullptr; } } - else if (geo->getTypeId() == Part::GeomPoint::getClassTypeId() || - geo->getTypeId() == Part::GeomCircle::getClassTypeId() || - geo->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() || - geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() || - geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + else if (geo->getTypeId() == Part::GeomPoint::getClassTypeId() + || geo->getTypeId() == Part::GeomCircle::getClassTypeId() + || geo->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() + || geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() + || geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { geoList.push_back(geo); } else { @@ -177,10 +181,10 @@ PyObject* SketchObjectPy::addGeometry(PyObject *args) } } - int ret = this->getSketchObjectPtr()->addGeometry(geoList,isConstruction) + 1; + int ret = this->getSketchObjectPtr()->addGeometry(geoList, isConstruction) + 1; std::size_t numGeo = geoList.size(); Py::Tuple tuple(numGeo); - for (std::size_t i=0; i geoIdList; Py::Sequence list(pcObj); @@ -226,7 +229,7 @@ PyObject* SketchObjectPy::delGeometries(PyObject *args) geoIdList.push_back(PyLong_AsLong((*it).ptr())); } - if(this->getSketchObjectPtr()->delGeometries(geoIdList)) { + if (this->getSketchObjectPtr()->delGeometries(geoIdList)) { std::stringstream str; str << "Not able to delete geometries"; PyErr_SetString(PyExc_ValueError, str.str().c_str()); @@ -234,7 +237,6 @@ PyObject* SketchObjectPy::delGeometries(PyObject *args) } Py_Return; - } std::string error = std::string("type must be list of GeoIds, not "); @@ -242,7 +244,7 @@ PyObject* SketchObjectPy::delGeometries(PyObject *args) throw Py::TypeError(error); } -PyObject* SketchObjectPy::deleteAllGeometry(PyObject *args) +PyObject* SketchObjectPy::deleteAllGeometry(PyObject* args) { if (!PyArg_ParseTuple(args, "")) return nullptr; @@ -257,7 +259,7 @@ PyObject* SketchObjectPy::deleteAllGeometry(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::deleteAllConstraints(PyObject *args) +PyObject* SketchObjectPy::deleteAllConstraints(PyObject* args) { if (!PyArg_ParseTuple(args, "")) return nullptr; @@ -273,7 +275,7 @@ PyObject* SketchObjectPy::deleteAllConstraints(PyObject *args) } -PyObject* SketchObjectPy::toggleConstruction(PyObject *args) +PyObject* SketchObjectPy::toggleConstruction(PyObject* args) { int Index; if (!PyArg_ParseTuple(args, "i", &Index)) @@ -289,10 +291,10 @@ PyObject* SketchObjectPy::toggleConstruction(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::setConstruction(PyObject *args) +PyObject* SketchObjectPy::setConstruction(PyObject* args) { int Index; - PyObject *Mode; + PyObject* Mode; if (!PyArg_ParseTuple(args, "iO!", &Index, &PyBool_Type, &Mode)) return nullptr; @@ -306,7 +308,7 @@ PyObject* SketchObjectPy::setConstruction(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::getConstruction(PyObject *args) +PyObject* SketchObjectPy::getConstruction(PyObject* args) { int Index; if (!PyArg_ParseTuple(args, "i", &Index)) @@ -314,24 +316,24 @@ PyObject* SketchObjectPy::getConstruction(PyObject *args) auto gf = this->getSketchObjectPtr()->getGeometryFacade(Index); - if(gf) + if (gf) return Py::new_reference_to(Py::Boolean(gf->getConstruction())); std::stringstream str; str << "Not able to retrieve construction mode of a geometry with the given index: " << Index; PyErr_SetString(PyExc_ValueError, str.str().c_str()); return nullptr; - } -PyObject* SketchObjectPy::addConstraint(PyObject *args) +PyObject* SketchObjectPy::addConstraint(PyObject* args) { - PyObject *pcObj; + PyObject* pcObj; if (!PyArg_ParseTuple(args, "O", &pcObj)) return nullptr; if (PyObject_TypeCheck(pcObj, &(Sketcher::ConstraintPy::Type))) { - Sketcher::Constraint *constr = static_cast(pcObj)->getConstraintPtr(); + Sketcher::Constraint* constr = + static_cast(pcObj)->getConstraintPtr(); if (!this->getSketchObjectPtr()->evaluateConstraint(constr)) { PyErr_SetString(PyExc_IndexError, "Constraint has invalid indexes"); return nullptr; @@ -348,25 +350,27 @@ PyObject* SketchObjectPy::addConstraint(PyObject *args) // however, the geometry changed after the command was committed, so the point that // moved do not go back to the position where it was. // - // N.B.: However, the solve itself may be inhibited in cases where groups of geometry/constraints - // are added together, because in that case undoing will also make the geometry disappear. + // N.B.: However, the solve itself may be inhibited in cases where groups of + // geometry/constraints + // are added together, because in that case undoing will also make the geometry + // disappear. this->getSketchObjectPtr()->solve(); // if the geometry moved during the solve, then the initial solution is invalid - // at this point, so a point movement may not work in cases where redundant constraints exist. - // this forces recalculation of the initial solution (not a full solve) - if(this->getSketchObjectPtr()->noRecomputes) { + // at this point, so a point movement may not work in cases where redundant constraints + // exist. this forces recalculation of the initial solution (not a full solve) + if (this->getSketchObjectPtr()->noRecomputes) { this->getSketchObjectPtr()->setUpSketch(); - this->getSketchObjectPtr()->Constraints.touch(); // update solver information + this->getSketchObjectPtr()->Constraints.touch();// update solver information } return Py::new_reference_to(Py::Long(ret)); } - else if (PyObject_TypeCheck(pcObj, &(PyList_Type)) || - PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { + else if (PyObject_TypeCheck(pcObj, &(PyList_Type)) + || PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { std::vector values; Py::Sequence list(pcObj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(ConstraintPy::Type))) { - Constraint *con = static_cast((*it).ptr())->getConstraintPtr(); + Constraint* con = static_cast((*it).ptr())->getConstraintPtr(); values.push_back(con); } } @@ -380,7 +384,7 @@ PyObject* SketchObjectPy::addConstraint(PyObject *args) int ret = getSketchObjectPtr()->addConstraints(values) + 1; std::size_t numCon = values.size(); Py::Tuple tuple(numCon); - for (std::size_t i=0; i &vals = getSketchObjectPtr()->Constraints.getValues(); + const std::vector& vals = + getSketchObjectPtr()->Constraints.getValues(); for (std::size_t i = 0; i < vals.size(); ++i) { if (static_cast(i) != Index && Name == vals[i]->Name) { PyErr_SetString(PyExc_ValueError, "Duplicate constraint not allowed"); @@ -448,7 +453,7 @@ PyObject* SketchObjectPy::renameConstraint(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::getIndexByName(PyObject *args) +PyObject* SketchObjectPy::getIndexByName(PyObject* args) { char* utf8Name; if (!PyArg_ParseTuple(args, "et", "utf-8", &utf8Name)) @@ -462,7 +467,7 @@ PyObject* SketchObjectPy::getIndexByName(PyObject *args) return nullptr; } - const std::vector< Sketcher::Constraint * > &vals = getSketchObjectPtr()->Constraints.getValues(); + const std::vector& vals = getSketchObjectPtr()->Constraints.getValues(); for (std::size_t i = 0; i < vals.size(); ++i) { if (Name == vals[i]->Name) { return Py_BuildValue("i", i); @@ -473,15 +478,15 @@ PyObject* SketchObjectPy::getIndexByName(PyObject *args) return nullptr; } -PyObject* SketchObjectPy::carbonCopy(PyObject *args) +PyObject* SketchObjectPy::carbonCopy(PyObject* args) { - char *ObjectName; - PyObject *construction = Py_True; + char* ObjectName; + PyObject* construction = Py_True; if (!PyArg_ParseTuple(args, "s|O!:Give an object", &ObjectName, &PyBool_Type, &construction)) return nullptr; Sketcher::SketchObject* skObj = this->getSketchObjectPtr(); - App::DocumentObject * Obj = skObj->getDocument()->getObject(ObjectName); + App::DocumentObject* Obj = skObj->getDocument()->getObject(ObjectName); if (!Obj) { std::stringstream str; @@ -490,7 +495,8 @@ PyObject* SketchObjectPy::carbonCopy(PyObject *args) return nullptr; } // check if this type of external geometry is allowed - if (!skObj->isExternalAllowed(Obj->getDocument(), Obj) && (Obj->getTypeId() != Sketcher::SketchObject::getClassTypeId())) { + if (!skObj->isExternalAllowed(Obj->getDocument(), Obj) + && (Obj->getTypeId() != Sketcher::SketchObject::getClassTypeId())) { std::stringstream str; str << ObjectName << " is not allowed for a carbon copy operation in this sketch"; PyErr_SetString(PyExc_ValueError, str.str().c_str()); @@ -508,16 +514,16 @@ PyObject* SketchObjectPy::carbonCopy(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::addExternal(PyObject *args) +PyObject* SketchObjectPy::addExternal(PyObject* args) { - char *ObjectName; - char *SubName; - if (!PyArg_ParseTuple(args, "ss:Give an object and subelement name", &ObjectName,&SubName)) + char* ObjectName; + char* SubName; + if (!PyArg_ParseTuple(args, "ss:Give an object and subelement name", &ObjectName, &SubName)) return nullptr; // get the target object for the external link Sketcher::SketchObject* skObj = this->getSketchObjectPtr(); - App::DocumentObject * Obj = skObj->getDocument()->getObject(ObjectName); + App::DocumentObject* Obj = skObj->getDocument()->getObject(ObjectName); if (!Obj) { std::stringstream str; str << ObjectName << " does not exist in the document"; @@ -533,7 +539,7 @@ PyObject* SketchObjectPy::addExternal(PyObject *args) } // add the external - if (skObj->addExternal(Obj,SubName) < 0) { + if (skObj->addExternal(Obj, SubName) < 0) { std::stringstream str; str << "Not able to add external shape element"; PyErr_SetString(PyExc_ValueError, str.str().c_str()); @@ -543,7 +549,7 @@ PyObject* SketchObjectPy::addExternal(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::delExternal(PyObject *args) +PyObject* SketchObjectPy::delExternal(PyObject* args) { int Index; if (!PyArg_ParseTuple(args, "i", &Index)) @@ -559,14 +565,17 @@ PyObject* SketchObjectPy::delExternal(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::delConstraintOnPoint(PyObject *args) +PyObject* SketchObjectPy::delConstraintOnPoint(PyObject* args) { - int Index, pos=-1; + int Index, pos = -1; if (!PyArg_ParseTuple(args, "i|i", &Index, &pos)) return nullptr; - if (pos >= static_cast(Sketcher::PointPos::none) && pos <= static_cast(Sketcher::PointPos::mid)) { // This is the whole range of valid positions - if (this->getSketchObjectPtr()->delConstraintOnPoint(Index,static_cast(pos))) { + if (pos >= static_cast(Sketcher::PointPos::none) + && pos <= static_cast(Sketcher::PointPos::mid)) { + // This is the whole range of valid positions + if (this->getSketchObjectPtr()->delConstraintOnPoint( + Index, static_cast(pos))) { std::stringstream str; str << "Not able to delete a constraint on point with the given index: " << Index << " and position: " << pos; @@ -574,7 +583,7 @@ PyObject* SketchObjectPy::delConstraintOnPoint(PyObject *args) return nullptr; } } - else if (pos==-1) { + else if (pos == -1) { if (this->getSketchObjectPtr()->delConstraintOnPoint(Index)) { std::stringstream str; str << "Not able to delete a constraint on point with the given index: " << Index; @@ -590,16 +599,16 @@ PyObject* SketchObjectPy::delConstraintOnPoint(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::setDatum(PyObject *args) +PyObject* SketchObjectPy::setDatum(PyObject* args) { double Datum; - int Index; + int Index; PyObject* object; Base::Quantity Quantity; do { // handle (int,Quantity) - if (PyArg_ParseTuple(args,"iO!", &Index, &(Base::QuantityPy::Type), &object)) { + if (PyArg_ParseTuple(args, "iO!", &Index, &(Base::QuantityPy::Type), &object)) { Quantity = *(static_cast(object)->getQuantityPtr()); if (Quantity.getUnit() == Base::Unit::Angle) { Datum = Base::toRadians(Quantity.getValue()); @@ -621,7 +630,7 @@ PyObject* SketchObjectPy::setDatum(PyObject *args) // handle (string,Quantity) char* constrName; PyErr_Clear(); - if (PyArg_ParseTuple(args,"sO!", &constrName, &(Base::QuantityPy::Type), &object)) { + if (PyArg_ParseTuple(args, "sO!", &constrName, &(Base::QuantityPy::Type), &object)) { Quantity = *(static_cast(object)->getQuantityPtr()); if (Quantity.getUnit() == Base::Unit::Angle) { Datum = Base::toRadians(Quantity.getValue()); @@ -632,8 +641,10 @@ PyObject* SketchObjectPy::setDatum(PyObject *args) int i = 0; Index = -1; - const std::vector& vals = this->getSketchObjectPtr()->Constraints.getValues(); - for (std::vector::const_iterator it = vals.begin(); it != vals.end(); ++it, ++i) { + const std::vector& vals = + this->getSketchObjectPtr()->Constraints.getValues(); + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); + ++it, ++i) { if ((*it)->Name == constrName) { Index = i; break; @@ -657,8 +668,10 @@ PyObject* SketchObjectPy::setDatum(PyObject *args) Quantity.setValue(Datum); int i = 0; Index = -1; - const std::vector& vals = this->getSketchObjectPtr()->Constraints.getValues(); - for (std::vector::const_iterator it = vals.begin(); it != vals.end(); ++it, ++i) { + const std::vector& vals = + this->getSketchObjectPtr()->Constraints.getValues(); + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); + ++it, ++i) { if ((*it)->Name == constrName) { Index = i; break; @@ -679,10 +692,9 @@ PyObject* SketchObjectPy::setDatum(PyObject *args) // error handling PyErr_SetString(PyExc_TypeError, "Wrong arguments"); return nullptr; - } - while (false); + } while (false); - int err=this->getSketchObjectPtr()->setDatum(Index, Datum); + int err = this->getSketchObjectPtr()->setDatum(Index, Datum); if (err) { std::stringstream str; if (err == -1) @@ -690,7 +702,8 @@ PyObject* SketchObjectPy::setDatum(PyObject *args) else if (err == -3) str << "Cannot set the datum because the sketch contains conflicting constraints"; else if (err == -2) - str << "Datum " << (const char*)Quantity.getUserString().toUtf8() << " for the constraint with index " << Index << " is invalid"; + str << "Datum " << (const char*)Quantity.getUserString().toUtf8() + << " for the constraint with index " << Index << " is invalid"; else if (err == -4) str << "Negative datum values are not valid for the constraint with index " << Index; else if (err == -5) @@ -698,7 +711,9 @@ PyObject* SketchObjectPy::setDatum(PyObject *args) else if (err == -6) str << "Cannot set the datum because of invalid geometry"; else - str << "Unexpected problem at setting datum " << (const char*)Quantity.getUserString().toUtf8() << " for the constraint with index " << Index; + str << "Unexpected problem at setting datum " + << (const char*)Quantity.getUserString().toUtf8() + << " for the constraint with index " << Index; PyErr_SetString(PyExc_ValueError, str.str().c_str()); return nullptr; } @@ -706,14 +721,14 @@ PyObject* SketchObjectPy::setDatum(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::getDatum(PyObject *args) +PyObject* SketchObjectPy::getDatum(PyObject* args) { const std::vector& vals = this->getSketchObjectPtr()->Constraints.getValues(); Constraint* constr = nullptr; do { int index = 0; - if (PyArg_ParseTuple(args,"i", &index)) { + if (PyArg_ParseTuple(args, "i", &index)) { if (index < 0 || index >= static_cast(vals.size())) { PyErr_SetString(PyExc_IndexError, "index out of range"); return nullptr; @@ -725,9 +740,10 @@ PyObject* SketchObjectPy::getDatum(PyObject *args) PyErr_Clear(); char* name; - if (PyArg_ParseTuple(args,"s", &name)) { + if (PyArg_ParseTuple(args, "s", &name)) { int id = 0; - for (std::vector::const_iterator it = vals.begin(); it != vals.end(); ++it, ++id) { + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); + ++it, ++id) { if (Sketcher::PropertyConstraintList::getConstraintName((*it)->Name, id) == name) { constr = *it; break; @@ -748,16 +764,11 @@ PyObject* SketchObjectPy::getDatum(PyObject *args) // error handling PyErr_SetString(PyExc_TypeError, "Wrong arguments"); return nullptr; - } - while (false); + } while (false); ConstraintType type = constr->Type; - if (type != Distance && - type != DistanceX && - type != DistanceY && - type != Radius && - type != Diameter && - type != Angle) { + if (type != Distance && type != DistanceX && type != DistanceY && type != Radius + && type != Diameter && type != Angle) { PyErr_SetString(PyExc_TypeError, "Constraint is not a datum"); return nullptr; } @@ -775,7 +786,7 @@ PyObject* SketchObjectPy::getDatum(PyObject *args) return new Base::QuantityPy(new Base::Quantity(datum)); } -PyObject* SketchObjectPy::setDriving(PyObject *args) +PyObject* SketchObjectPy::setDriving(PyObject* args) { PyObject* driving; int constrid; @@ -793,7 +804,7 @@ PyObject* SketchObjectPy::setDriving(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::setDatumsDriving(PyObject *args) +PyObject* SketchObjectPy::setDatumsDriving(PyObject* args) { PyObject* driving; @@ -810,7 +821,7 @@ PyObject* SketchObjectPy::setDatumsDriving(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::moveDatumsToEnd(PyObject *args) +PyObject* SketchObjectPy::moveDatumsToEnd(PyObject* args) { if (!PyArg_ParseTuple(args, "")) return nullptr; @@ -826,7 +837,7 @@ PyObject* SketchObjectPy::moveDatumsToEnd(PyObject *args) } -PyObject* SketchObjectPy::getDriving(PyObject *args) +PyObject* SketchObjectPy::getDriving(PyObject* args) { int constrid; bool driving; @@ -842,7 +853,7 @@ PyObject* SketchObjectPy::getDriving(PyObject *args) return Py::new_reference_to(Py::Boolean(driving)); } -PyObject* SketchObjectPy::toggleDriving(PyObject *args) +PyObject* SketchObjectPy::toggleDriving(PyObject* args) { int constrid; @@ -859,7 +870,7 @@ PyObject* SketchObjectPy::toggleDriving(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::setVirtualSpace(PyObject *args) +PyObject* SketchObjectPy::setVirtualSpace(PyObject* args) { PyObject* invirtualspace; PyObject* id_or_ids; @@ -868,8 +879,8 @@ PyObject* SketchObjectPy::setVirtualSpace(PyObject *args) return nullptr; } - if (PyObject_TypeCheck(id_or_ids, &(PyList_Type)) || - PyObject_TypeCheck(id_or_ids, &(PyTuple_Type))) { + if (PyObject_TypeCheck(id_or_ids, &(PyList_Type)) + || PyObject_TypeCheck(id_or_ids, &(PyTuple_Type))) { std::vector constrIds; Py::Sequence list(id_or_ids); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { @@ -878,22 +889,24 @@ PyObject* SketchObjectPy::setVirtualSpace(PyObject *args) } try { - int ret = this->getSketchObjectPtr()->setVirtualSpace(constrIds, Base::asBoolean(invirtualspace)); + int ret = this->getSketchObjectPtr()->setVirtualSpace(constrIds, + Base::asBoolean(invirtualspace)); - if(ret == -1) + if (ret == -1) throw Py::TypeError("Impossible to set virtual space!"); - } - catch(const Base::ValueError & e) { + catch (const Base::ValueError& e) { throw Py::ValueError(e.getMessage()); } Py_Return; } - else if(PyLong_Check(id_or_ids)) { - if (this->getSketchObjectPtr()->setVirtualSpace(PyLong_AsLong(id_or_ids), Base::asBoolean(invirtualspace))) { + else if (PyLong_Check(id_or_ids)) { + if (this->getSketchObjectPtr()->setVirtualSpace(PyLong_AsLong(id_or_ids), + Base::asBoolean(invirtualspace))) { std::stringstream str; - str << "Not able set virtual space for constraint with the given index: " << PyLong_AsLong(id_or_ids); + str << "Not able set virtual space for constraint with the given index: " + << PyLong_AsLong(id_or_ids); PyErr_SetString(PyExc_ValueError, str.str().c_str()); return nullptr; } @@ -904,10 +917,9 @@ PyObject* SketchObjectPy::setVirtualSpace(PyObject *args) std::string error = std::string("type must be list of Constraint Ids, not "); error += id_or_ids->ob_type->tp_name; throw Py::TypeError(error); - } -PyObject* SketchObjectPy::getVirtualSpace(PyObject *args) +PyObject* SketchObjectPy::getVirtualSpace(PyObject* args) { int constrid; bool invirtualspace; @@ -923,7 +935,7 @@ PyObject* SketchObjectPy::getVirtualSpace(PyObject *args) return Py::new_reference_to(Py::Boolean(invirtualspace)); } -PyObject* SketchObjectPy::toggleVirtualSpace(PyObject *args) +PyObject* SketchObjectPy::toggleVirtualSpace(PyObject* args) { int constrid; @@ -940,7 +952,7 @@ PyObject* SketchObjectPy::toggleVirtualSpace(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::setActive(PyObject *args) +PyObject* SketchObjectPy::setActive(PyObject* args) { PyObject* isactive; int constrid; @@ -950,7 +962,8 @@ PyObject* SketchObjectPy::setActive(PyObject *args) if (this->getSketchObjectPtr()->setActive(constrid, Base::asBoolean(isactive))) { std::stringstream str; - str << "Not able set active/disabled status for constraint with the given index: " << constrid; + str << "Not able set active/disabled status for constraint with the given index: " + << constrid; PyErr_SetString(PyExc_ValueError, str.str().c_str()); return nullptr; } @@ -958,7 +971,7 @@ PyObject* SketchObjectPy::setActive(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::getActive(PyObject *args) +PyObject* SketchObjectPy::getActive(PyObject* args) { int constrid; bool isactive; @@ -974,7 +987,7 @@ PyObject* SketchObjectPy::getActive(PyObject *args) return Py::new_reference_to(Py::Boolean(isactive)); } -PyObject* SketchObjectPy::toggleActive(PyObject *args) +PyObject* SketchObjectPy::toggleActive(PyObject* args) { int constrid; @@ -991,29 +1004,31 @@ PyObject* SketchObjectPy::toggleActive(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::movePoint(PyObject *args) +PyObject* SketchObjectPy::movePoint(PyObject* args) { - PyObject *pcObj; + PyObject* pcObj; int GeoId, PointType; - int relative=0; + int relative = 0; - if (!PyArg_ParseTuple(args, "iiO!|i", &GeoId, &PointType, &(Base::VectorPy::Type), &pcObj, &relative)) + if (!PyArg_ParseTuple( + args, "iiO!|i", &GeoId, &PointType, &(Base::VectorPy::Type), &pcObj, &relative)) return nullptr; Base::Vector3d v1 = static_cast(pcObj)->value(); - if (this->getSketchObjectPtr()->movePoint(GeoId,static_cast(PointType),v1,(relative>0))) { + if (this->getSketchObjectPtr()->movePoint( + GeoId, static_cast(PointType), v1, (relative > 0))) { std::stringstream str; - str << "Not able to move point with the id and type: (" << GeoId << ", " << PointType << ")"; + str << "Not able to move point with the id and type: (" << GeoId << ", " << PointType + << ")"; PyErr_SetString(PyExc_ValueError, str.str().c_str()); return nullptr; } Py_Return; - } -PyObject* SketchObjectPy::getGeoVertexIndex(PyObject *args) +PyObject* SketchObjectPy::getGeoVertexIndex(PyObject* args) { int index; if (!PyArg_ParseTuple(args, "i", &index)) @@ -1029,7 +1044,7 @@ PyObject* SketchObjectPy::getGeoVertexIndex(PyObject *args) return Py::new_reference_to(tuple); } -PyObject* SketchObjectPy::getPoint(PyObject *args) +PyObject* SketchObjectPy::getPoint(PyObject* args) { int GeoId, PointType; if (!PyArg_ParseTuple(args, "ii", &GeoId, &PointType)) @@ -1046,10 +1061,11 @@ PyObject* SketchObjectPy::getPoint(PyObject *args) return nullptr; } - return new Base::VectorPy(new Base::Vector3d(obj->getPoint(GeoId,static_cast(PointType)))); + return new Base::VectorPy( + new Base::Vector3d(obj->getPoint(GeoId, static_cast(PointType)))); } -PyObject* SketchObjectPy::getAxis(PyObject *args) +PyObject* SketchObjectPy::getAxis(PyObject* args) { int AxId; if (!PyArg_ParseTuple(args, "i", &AxId)) @@ -1058,27 +1074,39 @@ PyObject* SketchObjectPy::getAxis(PyObject *args) return new Base::AxisPy(new Base::Axis(this->getSketchObjectPtr()->getAxis(AxId))); } -PyObject* SketchObjectPy::fillet(PyObject *args) +PyObject* SketchObjectPy::fillet(PyObject* args) { PyObject *pcObj1, *pcObj2; int geoId1, geoId2, posId1; - int trim=true; + int trim = true; PyObject* createCorner = Py_False; double radius; // Two Lines, radius - if (PyArg_ParseTuple(args, "iiO!O!d|iO!", &geoId1, &geoId2, &(Base::VectorPy::Type), &pcObj1, &(Base::VectorPy::Type), &pcObj2, - &radius, &trim, &PyBool_Type, &createCorner)) { - // The i for &trim should probably have been a bool like &createCorner, but we'll leave it an int for backward - // compatibility (and because python will accept a bool there anyway) + if (PyArg_ParseTuple(args, + "iiO!O!d|iO!", + &geoId1, + &geoId2, + &(Base::VectorPy::Type), + &pcObj1, + &(Base::VectorPy::Type), + &pcObj2, + &radius, + &trim, + &PyBool_Type, + &createCorner)) { + // The i for &trim should probably have been a bool like &createCorner, but we'll leave it + // an int for backward compatibility (and because python will accept a bool there anyway) Base::Vector3d v1 = static_cast(pcObj1)->value(); Base::Vector3d v2 = static_cast(pcObj2)->value(); - if (this->getSketchObjectPtr()->fillet(geoId1, geoId2, v1, v2, radius, trim, Base::asBoolean(createCorner))) { + if (this->getSketchObjectPtr()->fillet( + geoId1, geoId2, v1, v2, radius, trim, Base::asBoolean(createCorner))) { std::stringstream str; - str << "Not able to fillet curves with ids : (" << geoId1 << ", " << geoId2 << ") and points (" << v1.x << ", " << v1.y << ", " << v1.z << ") & " - << "(" << v2.x << ", " << v2.y << ", " << v2.z << ")"; + str << "Not able to fillet curves with ids : (" << geoId1 << ", " << geoId2 + << ") and points (" << v1.x << ", " << v1.y << ", " << v1.z << ") & " + << "(" << v2.x << ", " << v2.y << ", " << v2.z << ")"; THROWM(Base::ValueError, str.str().c_str()) return nullptr; } @@ -1087,26 +1115,32 @@ PyObject* SketchObjectPy::fillet(PyObject *args) PyErr_Clear(); // Point, radius - if (PyArg_ParseTuple(args, "iid|iO!", &geoId1, &posId1, &radius, &trim, &PyBool_Type, &createCorner)) { - if (this->getSketchObjectPtr()->fillet(geoId1, static_cast(posId1), radius, trim, - Base::asBoolean(createCorner))) { + if (PyArg_ParseTuple( + args, "iid|iO!", &geoId1, &posId1, &radius, &trim, &PyBool_Type, &createCorner)) { + if (this->getSketchObjectPtr()->fillet(geoId1, + static_cast(posId1), + radius, + trim, + Base::asBoolean(createCorner))) { std::stringstream str; - str << "Not able to fillet point with ( geoId: " << geoId1 << ", PointPos: " << posId1 << " )"; + str << "Not able to fillet point with ( geoId: " << geoId1 << ", PointPos: " << posId1 + << " )"; PyErr_SetString(PyExc_ValueError, str.str().c_str()); return nullptr; } Py_Return; } - PyErr_SetString(PyExc_TypeError, "fillet() method accepts:\n" - "-- int,int,Vector,Vector,float,[bool],[bool]\n" - "-- int,int,float,[bool],[bool]\n"); + PyErr_SetString(PyExc_TypeError, + "fillet() method accepts:\n" + "-- int,int,Vector,Vector,float,[bool],[bool]\n" + "-- int,int,float,[bool],[bool]\n"); return nullptr; } -PyObject* SketchObjectPy::trim(PyObject *args) +PyObject* SketchObjectPy::trim(PyObject* args) { - PyObject *pcObj; + PyObject* pcObj; int GeoId; if (!PyArg_ParseTuple(args, "iO!", &GeoId, &(Base::VectorPy::Type), &pcObj)) @@ -1114,7 +1148,7 @@ PyObject* SketchObjectPy::trim(PyObject *args) Base::Vector3d v1 = static_cast(pcObj)->value(); - if (this->getSketchObjectPtr()->trim(GeoId,v1)) { + if (this->getSketchObjectPtr()->trim(GeoId, v1)) { std::stringstream str; str << "Not able to trim curve with the given index: " << GeoId; PyErr_SetString(PyExc_ValueError, str.str().c_str()); @@ -1124,30 +1158,33 @@ PyObject* SketchObjectPy::trim(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::extend(PyObject *args) +PyObject* SketchObjectPy::extend(PyObject* args) { double increment; int endPoint; int GeoId; if (PyArg_ParseTuple(args, "idi", &GeoId, &increment, &endPoint)) { - if (this->getSketchObjectPtr()->extend(GeoId, increment, static_cast(endPoint))) { + if (this->getSketchObjectPtr()->extend( + GeoId, increment, static_cast(endPoint))) { std::stringstream str; - str << "Not able to extend geometry with id : (" << GeoId << ") for increment (" << increment << ") and point position (" << endPoint << ")"; + str << "Not able to extend geometry with id : (" << GeoId << ") for increment (" + << increment << ") and point position (" << endPoint << ")"; PyErr_SetString(PyExc_ValueError, str.str().c_str()); return nullptr; } Py_Return; } - PyErr_SetString(PyExc_TypeError, "extend() method accepts:\n" - "-- int,float,int\n"); + PyErr_SetString(PyExc_TypeError, + "extend() method accepts:\n" + "-- int,float,int\n"); return nullptr; } -PyObject* SketchObjectPy::split(PyObject *args) +PyObject* SketchObjectPy::split(PyObject* args) { - PyObject *pcObj; + PyObject* pcObj; int GeoId; if (!PyArg_ParseTuple(args, "iO!", &GeoId, &(Base::VectorPy::Type), &pcObj)) @@ -1155,21 +1192,21 @@ PyObject* SketchObjectPy::split(PyObject *args) Base::Vector3d v1 = static_cast(pcObj)->value(); try { - if (this->getSketchObjectPtr()->split(GeoId,v1)) { + if (this->getSketchObjectPtr()->split(GeoId, v1)) { std::stringstream str; str << "Not able to split curve with the given index: " << GeoId; PyErr_SetString(PyExc_ValueError, str.str().c_str()); return nullptr; } } - catch (const Base::ValueError & e) { + catch (const Base::ValueError& e) { throw Py::ValueError(e.getMessage()); } Py_Return; } -PyObject* SketchObjectPy::join(PyObject *args) +PyObject* SketchObjectPy::join(PyObject* args) { int GeoId1(Sketcher::GeoEnum::GeoUndef), GeoId2(Sketcher::GeoEnum::GeoUndef); int PosId1 = static_cast(Sketcher::PointPos::none), @@ -1178,12 +1215,11 @@ PyObject* SketchObjectPy::join(PyObject *args) if (!PyArg_ParseTuple(args, "iiii", &GeoId1, &PosId1, &GeoId2, &PosId2)) return 0; - if (this->getSketchObjectPtr()->join(GeoId1, (Sketcher::PointPos) PosId1, - GeoId2, (Sketcher::PointPos) PosId2)) { + if (this->getSketchObjectPtr()->join( + GeoId1, (Sketcher::PointPos)PosId1, GeoId2, (Sketcher::PointPos)PosId2)) { std::stringstream str; - str << "Not able to join the curves with end points: (" - << GeoId1 << ", " << PosId1 << "), (" - << GeoId2 << ", " << PosId2 << ")"; + str << "Not able to join the curves with end points: (" << GeoId1 << ", " << PosId1 + << "), (" << GeoId2 << ", " << PosId2 << ")"; PyErr_SetString(PyExc_ValueError, str.str().c_str()); return 0; } @@ -1191,17 +1227,16 @@ PyObject* SketchObjectPy::join(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::addSymmetric(PyObject *args) +PyObject* SketchObjectPy::addSymmetric(PyObject* args) { - PyObject *pcObj; + PyObject* pcObj; int refGeoId; int refPosId = static_cast(Sketcher::PointPos::none); if (!PyArg_ParseTuple(args, "Oi|i", &pcObj, &refGeoId, &refPosId)) return nullptr; - if (PyObject_TypeCheck(pcObj, &(PyList_Type)) || - PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { + if (PyObject_TypeCheck(pcObj, &(PyList_Type)) || PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { std::vector geoIdList; Py::Sequence list(pcObj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { @@ -1209,14 +1244,16 @@ PyObject* SketchObjectPy::addSymmetric(PyObject *args) geoIdList.push_back(PyLong_AsLong((*it).ptr())); } - int ret = this->getSketchObjectPtr()->addSymmetric(geoIdList,refGeoId,static_cast(refPosId)) + 1; + int ret = this->getSketchObjectPtr()->addSymmetric( + geoIdList, refGeoId, static_cast(refPosId)) + + 1; - if(ret == -1) + if (ret == -1) throw Py::TypeError("Symmetric operation unsuccessful!"); std::size_t numGeo = geoIdList.size(); Py::Tuple tuple(numGeo); - for (std::size_t i=0; i(pcVect)->value(); - if (PyObject_TypeCheck(pcObj, &(PyList_Type)) || - PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { + if (PyObject_TypeCheck(pcObj, &(PyList_Type)) || PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { std::vector geoIdList; Py::Sequence list(pcObj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { @@ -1249,24 +1286,25 @@ PyObject* SketchObjectPy::addCopy(PyObject *args) } try { - int ret = this->getSketchObjectPtr()->addCopy(geoIdList, vect, false, Base::asBoolean(clone)) + 1; + int ret = + this->getSketchObjectPtr()->addCopy(geoIdList, vect, false, Base::asBoolean(clone)) + + 1; - if(ret == -1) + if (ret == -1) throw Py::TypeError("Copy operation unsuccessful!"); std::size_t numGeo = geoIdList.size(); Py::Tuple tuple(numGeo); - for (std::size_t i=0; i(pcVect)->value(); - if (PyObject_TypeCheck(pcObj, &(PyList_Type)) || - PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { + if (PyObject_TypeCheck(pcObj, &(PyList_Type)) || PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { std::vector geoIdList; Py::Sequence list(pcObj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { @@ -1292,9 +1329,9 @@ PyObject* SketchObjectPy::addMove(PyObject *args) geoIdList.push_back(PyLong_AsLong((*it).ptr())); } - this->getSketchObjectPtr()->addCopy(geoIdList, vect, true); + this->getSketchObjectPtr()->addCopy(geoIdList, vect, true); - Py_Return; + Py_Return; } std::string error = std::string("type must be list of GeoIds, not "); @@ -1302,38 +1339,53 @@ PyObject* SketchObjectPy::addMove(PyObject *args) throw Py::TypeError(error); } -PyObject* SketchObjectPy::addRectangularArray(PyObject *args) +PyObject* SketchObjectPy::addRectangularArray(PyObject* args) { PyObject *pcObj, *pcVect; - int rows,cols; - double perpscale=1.0; - PyObject* constraindisplacement= Py_False; - PyObject* clone= Py_False; + int rows, cols; + double perpscale = 1.0; + PyObject* constraindisplacement = Py_False; + PyObject* clone = Py_False; - if (!PyArg_ParseTuple(args, "OO!O!ii|O!d", &pcObj, &(Base::VectorPy::Type), &pcVect, - &PyBool_Type, &clone, &rows, &cols, &PyBool_Type, &constraindisplacement,&perpscale)) + if (!PyArg_ParseTuple(args, + "OO!O!ii|O!d", + &pcObj, + &(Base::VectorPy::Type), + &pcVect, + &PyBool_Type, + &clone, + &rows, + &cols, + &PyBool_Type, + &constraindisplacement, + &perpscale)) return nullptr; Base::Vector3d vect = static_cast(pcVect)->value(); - if (PyObject_TypeCheck(pcObj, &(PyList_Type)) || - PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { + if (PyObject_TypeCheck(pcObj, &(PyList_Type)) || PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { std::vector geoIdList; Py::Sequence list(pcObj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { - if (PyLong_Check((*it).ptr())) - geoIdList.push_back(PyLong_AsLong((*it).ptr())); + if (PyLong_Check((*it).ptr())) + geoIdList.push_back(PyLong_AsLong((*it).ptr())); } try { - int ret = this->getSketchObjectPtr()->addCopy(geoIdList,vect, false, Base::asBoolean(clone), - rows, cols, Base::asBoolean(constraindisplacement), perpscale) + 1; + int ret = this->getSketchObjectPtr()->addCopy(geoIdList, + vect, + false, + Base::asBoolean(clone), + rows, + cols, + Base::asBoolean(constraindisplacement), + perpscale) + + 1; - if(ret == -1) + if (ret == -1) throw Py::TypeError("Copy operation unsuccessful!"); - } - catch(const Base::ValueError & e) { + catch (const Base::ValueError& e) { throw Py::ValueError(e.getMessage()); } @@ -1345,15 +1397,14 @@ PyObject* SketchObjectPy::addRectangularArray(PyObject *args) throw Py::TypeError(error); } -PyObject* SketchObjectPy::removeAxesAlignment(PyObject *args) +PyObject* SketchObjectPy::removeAxesAlignment(PyObject* args) { - PyObject *pcObj; + PyObject* pcObj; if (!PyArg_ParseTuple(args, "O", &pcObj)) return nullptr; - if (PyObject_TypeCheck(pcObj, &(PyList_Type)) || - PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { + if (PyObject_TypeCheck(pcObj, &(PyList_Type)) || PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { std::vector geoIdList; Py::Sequence list(pcObj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { @@ -1363,7 +1414,7 @@ PyObject* SketchObjectPy::removeAxesAlignment(PyObject *args) int ret = this->getSketchObjectPtr()->removeAxesAlignment(geoIdList) + 1; - if(ret == -1) + if (ret == -1) throw Py::TypeError("Operation unsuccessful!"); Py_Return; @@ -1374,16 +1425,16 @@ PyObject* SketchObjectPy::removeAxesAlignment(PyObject *args) throw Py::TypeError(error); } -PyObject* SketchObjectPy::calculateAngleViaPoint(PyObject *args) +PyObject* SketchObjectPy::calculateAngleViaPoint(PyObject* args) { - int GeoId1=0, GeoId2=0; - double px=0, py=0; + int GeoId1 = 0, GeoId2 = 0; + double px = 0, py = 0; if (!PyArg_ParseTuple(args, "iidd", &GeoId1, &GeoId2, &px, &py)) return nullptr; SketchObject* obj = this->getSketchObjectPtr(); - if (GeoId1 > obj->getHighestCurveIndex() || -GeoId1 > obj->getExternalGeometryCount() || - GeoId2 > obj->getHighestCurveIndex() || -GeoId2 > obj->getExternalGeometryCount() ) { + if (GeoId1 > obj->getHighestCurveIndex() || -GeoId1 > obj->getExternalGeometryCount() + || GeoId2 > obj->getHighestCurveIndex() || -GeoId2 > obj->getExternalGeometryCount()) { PyErr_SetString(PyExc_ValueError, "Invalid geometry Id"); return nullptr; } @@ -1392,10 +1443,10 @@ PyObject* SketchObjectPy::calculateAngleViaPoint(PyObject *args) return Py::new_reference_to(Py::Float(ang)); } -PyObject* SketchObjectPy::isPointOnCurve(PyObject *args) +PyObject* SketchObjectPy::isPointOnCurve(PyObject* args) { - int GeoId=GeoEnum::GeoUndef; - double px=0, py=0; + int GeoId = GeoEnum::GeoUndef; + double px = 0, py = 0; if (!PyArg_ParseTuple(args, "idd", &GeoId, &px, &py)) return nullptr; @@ -1408,9 +1459,9 @@ PyObject* SketchObjectPy::isPointOnCurve(PyObject *args) return Py::new_reference_to(Py::Boolean(obj->isPointOnCurve(GeoId, px, py))); } -PyObject* SketchObjectPy::calculateConstraintError(PyObject *args) +PyObject* SketchObjectPy::calculateConstraintError(PyObject* args) { - int ic=-1; + int ic = -1; if (!PyArg_ParseTuple(args, "i", &ic)) return nullptr; @@ -1424,9 +1475,9 @@ PyObject* SketchObjectPy::calculateConstraintError(PyObject *args) return Py::new_reference_to(Py::Float(err)); } -PyObject* SketchObjectPy::changeConstraintsLocking(PyObject *args) +PyObject* SketchObjectPy::changeConstraintsLocking(PyObject* args) { - int bLock=0; + int bLock = 0; if (!PyArg_ParseTuple(args, "i", &bLock)) return nullptr; @@ -1437,15 +1488,15 @@ PyObject* SketchObjectPy::changeConstraintsLocking(PyObject *args) return Py::new_reference_to(Py::Long(naff)); } -//Deprecated -PyObject* SketchObjectPy::ExposeInternalGeometry(PyObject *args) +// Deprecated +PyObject* SketchObjectPy::ExposeInternalGeometry(PyObject* args) { int GeoId; if (!PyArg_ParseTuple(args, "i", &GeoId)) return nullptr; - if (this->getSketchObjectPtr()->exposeInternalGeometry(GeoId)==-1) { + if (this->getSketchObjectPtr()->exposeInternalGeometry(GeoId) == -1) { std::stringstream str; str << "Object does not support internal geometry: " << GeoId; PyErr_SetString(PyExc_ValueError, str.str().c_str()); @@ -1455,15 +1506,15 @@ PyObject* SketchObjectPy::ExposeInternalGeometry(PyObject *args) Py_Return; } -//Deprecated -PyObject* SketchObjectPy::DeleteUnusedInternalGeometry(PyObject *args) +// Deprecated +PyObject* SketchObjectPy::DeleteUnusedInternalGeometry(PyObject* args) { int GeoId; if (!PyArg_ParseTuple(args, "i", &GeoId)) return nullptr; - if (this->getSketchObjectPtr()->deleteUnusedInternalGeometry(GeoId)==-1) { + if (this->getSketchObjectPtr()->deleteUnusedInternalGeometry(GeoId) == -1) { std::stringstream str; str << "Object does not support internal geometry: " << GeoId; PyErr_SetString(PyExc_ValueError, str.str().c_str()); @@ -1473,14 +1524,14 @@ PyObject* SketchObjectPy::DeleteUnusedInternalGeometry(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::exposeInternalGeometry(PyObject *args) +PyObject* SketchObjectPy::exposeInternalGeometry(PyObject* args) { int GeoId; if (!PyArg_ParseTuple(args, "i", &GeoId)) return nullptr; - if (this->getSketchObjectPtr()->exposeInternalGeometry(GeoId)==-1) { + if (this->getSketchObjectPtr()->exposeInternalGeometry(GeoId) == -1) { std::stringstream str; str << "Object does not support internal geometry: " << GeoId; PyErr_SetString(PyExc_ValueError, str.str().c_str()); @@ -1490,14 +1541,14 @@ PyObject* SketchObjectPy::exposeInternalGeometry(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::deleteUnusedInternalGeometry(PyObject *args) +PyObject* SketchObjectPy::deleteUnusedInternalGeometry(PyObject* args) { int GeoId; if (!PyArg_ParseTuple(args, "i", &GeoId)) return nullptr; - if (this->getSketchObjectPtr()->deleteUnusedInternalGeometry(GeoId)==-1) { + if (this->getSketchObjectPtr()->deleteUnusedInternalGeometry(GeoId) == -1) { std::stringstream str; str << "Object does not support internal geometry: " << GeoId; PyErr_SetString(PyExc_ValueError, str.str().c_str()); @@ -1507,7 +1558,7 @@ PyObject* SketchObjectPy::deleteUnusedInternalGeometry(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::convertToNURBS(PyObject *args) +PyObject* SketchObjectPy::convertToNURBS(PyObject* args) { int GeoId; @@ -1524,7 +1575,7 @@ PyObject* SketchObjectPy::convertToNURBS(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::increaseBSplineDegree(PyObject *args) +PyObject* SketchObjectPy::increaseBSplineDegree(PyObject* args) { int GeoId; int incr = 1; @@ -1542,7 +1593,7 @@ PyObject* SketchObjectPy::increaseBSplineDegree(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::decreaseBSplineDegree(PyObject *args) +PyObject* SketchObjectPy::decreaseBSplineDegree(PyObject* args) { int GeoId; int decr = 1; @@ -1554,7 +1605,7 @@ PyObject* SketchObjectPy::decreaseBSplineDegree(PyObject *args) return Py_BuildValue("O", (ok ? Py_True : Py_False)); } -PyObject* SketchObjectPy::modifyBSplineKnotMultiplicity(PyObject *args) +PyObject* SketchObjectPy::modifyBSplineKnotMultiplicity(PyObject* args) { int GeoId; int knotIndex; @@ -1563,7 +1614,8 @@ PyObject* SketchObjectPy::modifyBSplineKnotMultiplicity(PyObject *args) if (!PyArg_ParseTuple(args, "ii|i", &GeoId, &knotIndex, &multiplicity)) return nullptr; - if (!this->getSketchObjectPtr()->modifyBSplineKnotMultiplicity(GeoId, knotIndex, multiplicity)) { + if (!this->getSketchObjectPtr()->modifyBSplineKnotMultiplicity( + GeoId, knotIndex, multiplicity)) { std::stringstream str; str << "Multiplicity modification failed for: " << GeoId; PyErr_SetString(PyExc_ValueError, str.str().c_str()); @@ -1573,7 +1625,7 @@ PyObject* SketchObjectPy::modifyBSplineKnotMultiplicity(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::insertBSplineKnot(PyObject *args) +PyObject* SketchObjectPy::insertBSplineKnot(PyObject* args) { int GeoId; double knotParam; @@ -1592,17 +1644,19 @@ PyObject* SketchObjectPy::insertBSplineKnot(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::autoconstraint(PyObject *args) +PyObject* SketchObjectPy::autoconstraint(PyObject* args) { double precision = Precision::Confusion() * 1000; - double angleprecision = M_PI/8; + double angleprecision = M_PI / 8; PyObject* includeconstruction = Py_True; - if (!PyArg_ParseTuple(args, "|ddO!", &precision, &angleprecision, &PyBool_Type, &includeconstruction)) + if (!PyArg_ParseTuple( + args, "|ddO!", &precision, &angleprecision, &PyBool_Type, &includeconstruction)) return nullptr; - if (this->getSketchObjectPtr()->autoConstraint(precision, angleprecision, Base::asBoolean(includeconstruction))) { + if (this->getSketchObjectPtr()->autoConstraint( + precision, angleprecision, Base::asBoolean(includeconstruction))) { std::stringstream str; str << "Unable to autoconstraint"; PyErr_SetString(PyExc_ValueError, str.str().c_str()); @@ -1612,7 +1666,7 @@ PyObject* SketchObjectPy::autoconstraint(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::detectMissingPointOnPointConstraints(PyObject *args) +PyObject* SketchObjectPy::detectMissingPointOnPointConstraints(PyObject* args) { double precision = Precision::Confusion() * 1000; PyObject* includeconstruction = Py_True; @@ -1620,32 +1674,36 @@ PyObject* SketchObjectPy::detectMissingPointOnPointConstraints(PyObject *args) if (!PyArg_ParseTuple(args, "|dO!", &precision, &PyBool_Type, &includeconstruction)) return nullptr; - return Py::new_reference_to(Py::Long(this->getSketchObjectPtr()->detectMissingPointOnPointConstraints(precision, Base::asBoolean(includeconstruction)))); + return Py::new_reference_to( + Py::Long(this->getSketchObjectPtr()->detectMissingPointOnPointConstraints( + precision, Base::asBoolean(includeconstruction)))); } -PyObject* SketchObjectPy::detectMissingVerticalHorizontalConstraints(PyObject *args) +PyObject* SketchObjectPy::detectMissingVerticalHorizontalConstraints(PyObject* args) { - double angleprecision = M_PI/8; + double angleprecision = M_PI / 8; if (!PyArg_ParseTuple(args, "|d", &angleprecision)) return nullptr; - return Py::new_reference_to(Py::Long(this->getSketchObjectPtr()->detectMissingVerticalHorizontalConstraints(angleprecision))); + return Py::new_reference_to(Py::Long( + this->getSketchObjectPtr()->detectMissingVerticalHorizontalConstraints(angleprecision))); } -PyObject* SketchObjectPy::detectMissingEqualityConstraints(PyObject *args) +PyObject* SketchObjectPy::detectMissingEqualityConstraints(PyObject* args) { double precision = Precision::Confusion() * 1000; if (!PyArg_ParseTuple(args, "|d", &precision)) return nullptr; - return Py::new_reference_to(Py::Long(this->getSketchObjectPtr()->detectMissingEqualityConstraints(precision))); + return Py::new_reference_to( + Py::Long(this->getSketchObjectPtr()->detectMissingEqualityConstraints(precision))); } -PyObject* SketchObjectPy::analyseMissingPointOnPointCoincident(PyObject *args) +PyObject* SketchObjectPy::analyseMissingPointOnPointCoincident(PyObject* args) { - double angleprecision = M_PI/8; + double angleprecision = M_PI / 8; if (!PyArg_ParseTuple(args, "|d", &angleprecision)) return nullptr; @@ -1655,7 +1713,7 @@ PyObject* SketchObjectPy::analyseMissingPointOnPointCoincident(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::makeMissingPointOnPointCoincident(PyObject *args) +PyObject* SketchObjectPy::makeMissingPointOnPointCoincident(PyObject* args) { PyObject* onebyone = Py_False; @@ -1668,7 +1726,7 @@ PyObject* SketchObjectPy::makeMissingPointOnPointCoincident(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::makeMissingVerticalHorizontal(PyObject *args) +PyObject* SketchObjectPy::makeMissingVerticalHorizontal(PyObject* args) { PyObject* onebyone = Py_False; @@ -1680,7 +1738,7 @@ PyObject* SketchObjectPy::makeMissingVerticalHorizontal(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::makeMissingEquality(PyObject *args) +PyObject* SketchObjectPy::makeMissingEquality(PyObject* args) { PyObject* onebyone = Py_True; @@ -1692,7 +1750,7 @@ PyObject* SketchObjectPy::makeMissingEquality(PyObject *args) Py_Return; } -PyObject* SketchObjectPy::autoRemoveRedundants(PyObject *args) +PyObject* SketchObjectPy::autoRemoveRedundants(PyObject* args) { PyObject* updategeo = Py_True; @@ -1706,15 +1764,24 @@ PyObject* SketchObjectPy::autoRemoveRedundants(PyObject *args) Py::List SketchObjectPy::getMissingPointOnPointConstraints() const { - std::vector constraints = this->getSketchObjectPtr()->getMissingPointOnPointConstraints(); + std::vector constraints = + this->getSketchObjectPtr()->getMissingPointOnPointConstraints(); Py::List list; for (auto c : constraints) { Py::Tuple t(5); t.setItem(0, Py::Long(c.First)); - t.setItem(1, Py::Long(((c.FirstPos == Sketcher::PointPos::none)?0:(c.FirstPos == Sketcher::PointPos::start)?1:(c.FirstPos == Sketcher::PointPos::end)?2:3))); + t.setItem(1, + Py::Long(((c.FirstPos == Sketcher::PointPos::none) ? 0 + : (c.FirstPos == Sketcher::PointPos::start) ? 1 + : (c.FirstPos == Sketcher::PointPos::end) ? 2 + : 3))); t.setItem(2, Py::Long(c.Second)); - t.setItem(3, Py::Long(((c.SecondPos == Sketcher::PointPos::none)?0:(c.SecondPos == Sketcher::PointPos::start)?1:(c.SecondPos == Sketcher::PointPos::end)?2:3))); + t.setItem(3, + Py::Long(((c.SecondPos == Sketcher::PointPos::none) ? 0 + : (c.SecondPos == Sketcher::PointPos::start) ? 1 + : (c.SecondPos == Sketcher::PointPos::end) ? 2 + : 3))); t.setItem(4, Py::Long(c.Type)); list.append(t); } @@ -1725,18 +1792,24 @@ void SketchObjectPy::setMissingPointOnPointConstraints(Py::List arg) { std::vector constraints; - auto checkpos = [](Py::Tuple &t,int i) { - auto checkitem = [](Py::Tuple &t,int i, int val) {return long(Py::Long(t.getItem(i)))==val;}; - return (checkitem(t,i,0)?Sketcher::PointPos::none:(checkitem(t,i,1)?Sketcher::PointPos::start:(checkitem(t,i,2)?Sketcher::PointPos::end:Sketcher::PointPos::mid))); + auto checkpos = [](Py::Tuple& t, int i) { + auto checkitem = [](Py::Tuple& t, int i, int val) { + return long(Py::Long(t.getItem(i))) == val; + }; + return (checkitem(t, i, 0) + ? Sketcher::PointPos::none + : (checkitem(t, i, 1) ? Sketcher::PointPos::start + : (checkitem(t, i, 2) ? Sketcher::PointPos::end + : Sketcher::PointPos::mid))); }; for (const auto& ti : arg) { Py::Tuple t(ti); ConstraintIds c; c.First = static_cast(Py::Long(t.getItem(0))); - c.FirstPos = checkpos(t,1); + c.FirstPos = checkpos(t, 1); c.Second = static_cast(Py::Long(t.getItem(2))); - c.SecondPos = checkpos(t,3); + c.SecondPos = checkpos(t, 3); c.Type = static_cast(static_cast(Py::Long(t.getItem(4)))); constraints.push_back(c); @@ -1747,15 +1820,24 @@ void SketchObjectPy::setMissingPointOnPointConstraints(Py::List arg) Py::List SketchObjectPy::getMissingVerticalHorizontalConstraints() const { - std::vector constraints = this->getSketchObjectPtr()->getMissingVerticalHorizontalConstraints(); + std::vector constraints = + this->getSketchObjectPtr()->getMissingVerticalHorizontalConstraints(); Py::List list; for (auto c : constraints) { Py::Tuple t(5); t.setItem(0, Py::Long(c.First)); - t.setItem(1, Py::Long(((c.FirstPos == Sketcher::PointPos::none)?0:(c.FirstPos == Sketcher::PointPos::start)?1:(c.FirstPos == Sketcher::PointPos::end)?2:3))); + t.setItem(1, + Py::Long(((c.FirstPos == Sketcher::PointPos::none) ? 0 + : (c.FirstPos == Sketcher::PointPos::start) ? 1 + : (c.FirstPos == Sketcher::PointPos::end) ? 2 + : 3))); t.setItem(2, Py::Long(c.Second)); - t.setItem(3, Py::Long(((c.SecondPos == Sketcher::PointPos::none)?0:(c.SecondPos == Sketcher::PointPos::start)?1:(c.SecondPos == Sketcher::PointPos::end)?2:3))); + t.setItem(3, + Py::Long(((c.SecondPos == Sketcher::PointPos::none) ? 0 + : (c.SecondPos == Sketcher::PointPos::start) ? 1 + : (c.SecondPos == Sketcher::PointPos::end) ? 2 + : 3))); t.setItem(4, Py::Long(c.Type)); list.append(t); } @@ -1766,18 +1848,24 @@ void SketchObjectPy::setMissingVerticalHorizontalConstraints(Py::List arg) { std::vector constraints; - auto checkpos = [](Py::Tuple &t,int i) { - auto checkitem = [](Py::Tuple &t,int i, int val) {return long(Py::Long(t.getItem(i)))==val;}; - return (checkitem(t,i,0)?Sketcher::PointPos::none:(checkitem(t,i,1)?Sketcher::PointPos::start:(checkitem(t,i,2)?Sketcher::PointPos::end:Sketcher::PointPos::mid))); + auto checkpos = [](Py::Tuple& t, int i) { + auto checkitem = [](Py::Tuple& t, int i, int val) { + return long(Py::Long(t.getItem(i))) == val; + }; + return (checkitem(t, i, 0) + ? Sketcher::PointPos::none + : (checkitem(t, i, 1) ? Sketcher::PointPos::start + : (checkitem(t, i, 2) ? Sketcher::PointPos::end + : Sketcher::PointPos::mid))); }; for (const auto& ti : arg) { Py::Tuple t(ti); ConstraintIds c; c.First = static_cast(Py::Long(t.getItem(0))); - c.FirstPos = checkpos(t,1); + c.FirstPos = checkpos(t, 1); c.Second = static_cast(Py::Long(t.getItem(2))); - c.SecondPos = checkpos(t,3); + c.SecondPos = checkpos(t, 3); c.Type = static_cast(static_cast(Py::Long(t.getItem(4)))); constraints.push_back(c); @@ -1788,15 +1876,24 @@ void SketchObjectPy::setMissingVerticalHorizontalConstraints(Py::List arg) Py::List SketchObjectPy::getMissingLineEqualityConstraints() const { - std::vector constraints = this->getSketchObjectPtr()->getMissingLineEqualityConstraints(); + std::vector constraints = + this->getSketchObjectPtr()->getMissingLineEqualityConstraints(); Py::List list; for (auto c : constraints) { Py::Tuple t(4); t.setItem(0, Py::Long(c.First)); - t.setItem(1, Py::Long(((c.FirstPos == Sketcher::PointPos::none)?0:(c.FirstPos == Sketcher::PointPos::start)?1:(c.FirstPos == Sketcher::PointPos::end)?2:3))); + t.setItem(1, + Py::Long(((c.FirstPos == Sketcher::PointPos::none) ? 0 + : (c.FirstPos == Sketcher::PointPos::start) ? 1 + : (c.FirstPos == Sketcher::PointPos::end) ? 2 + : 3))); t.setItem(2, Py::Long(c.Second)); - t.setItem(3, Py::Long(((c.SecondPos == Sketcher::PointPos::none)?0:(c.SecondPos == Sketcher::PointPos::start)?1:(c.SecondPos == Sketcher::PointPos::end)?2:3))); + t.setItem(3, + Py::Long(((c.SecondPos == Sketcher::PointPos::none) ? 0 + : (c.SecondPos == Sketcher::PointPos::start) ? 1 + : (c.SecondPos == Sketcher::PointPos::end) ? 2 + : 3))); list.append(t); } return list; @@ -1806,18 +1903,24 @@ void SketchObjectPy::setMissingLineEqualityConstraints(Py::List arg) { std::vector constraints; - auto checkpos = [](Py::Tuple &t,int i) { - auto checkitem = [](Py::Tuple &t,int i, int val) {return long(Py::Long(t.getItem(i)))==val;}; - return (checkitem(t,i,0)?Sketcher::PointPos::none:(checkitem(t,i,1)?Sketcher::PointPos::start:(checkitem(t,i,2)?Sketcher::PointPos::end:Sketcher::PointPos::mid))); + auto checkpos = [](Py::Tuple& t, int i) { + auto checkitem = [](Py::Tuple& t, int i, int val) { + return long(Py::Long(t.getItem(i))) == val; + }; + return (checkitem(t, i, 0) + ? Sketcher::PointPos::none + : (checkitem(t, i, 1) ? Sketcher::PointPos::start + : (checkitem(t, i, 2) ? Sketcher::PointPos::end + : Sketcher::PointPos::mid))); }; for (const auto& ti : arg) { Py::Tuple t(ti); ConstraintIds c; c.First = (long)Py::Long(t.getItem(0)); - c.FirstPos = checkpos(t,1); + c.FirstPos = checkpos(t, 1); c.Second = (long)Py::Long(t.getItem(2)); - c.SecondPos = checkpos(t,3); + c.SecondPos = checkpos(t, 3); c.Type = Sketcher::Equal; constraints.push_back(c); @@ -1828,15 +1931,24 @@ void SketchObjectPy::setMissingLineEqualityConstraints(Py::List arg) Py::List SketchObjectPy::getMissingRadiusConstraints() const { - std::vector constraints = this->getSketchObjectPtr()->getMissingRadiusConstraints(); + std::vector constraints = + this->getSketchObjectPtr()->getMissingRadiusConstraints(); Py::List list; for (auto c : constraints) { Py::Tuple t(4); t.setItem(0, Py::Long(c.First)); - t.setItem(1, Py::Long(((c.FirstPos == Sketcher::PointPos::none)?0:(c.FirstPos == Sketcher::PointPos::start)?1:(c.FirstPos == Sketcher::PointPos::end)?2:3))); + t.setItem(1, + Py::Long(((c.FirstPos == Sketcher::PointPos::none) ? 0 + : (c.FirstPos == Sketcher::PointPos::start) ? 1 + : (c.FirstPos == Sketcher::PointPos::end) ? 2 + : 3))); t.setItem(2, Py::Long(c.Second)); - t.setItem(3, Py::Long(((c.SecondPos == Sketcher::PointPos::none)?0:(c.SecondPos == Sketcher::PointPos::start)?1:(c.SecondPos == Sketcher::PointPos::end)?2:3))); + t.setItem(3, + Py::Long(((c.SecondPos == Sketcher::PointPos::none) ? 0 + : (c.SecondPos == Sketcher::PointPos::start) ? 1 + : (c.SecondPos == Sketcher::PointPos::end) ? 2 + : 3))); list.append(t); } return list; @@ -1846,18 +1958,24 @@ void SketchObjectPy::setMissingRadiusConstraints(Py::List arg) { std::vector constraints; - auto checkpos = [](Py::Tuple &t,int i) { - auto checkitem = [](Py::Tuple &t,int i, int val) {return long(Py::Long(t.getItem(i)))==val;}; - return (checkitem(t,i,0)?Sketcher::PointPos::none:(checkitem(t,i,1)?Sketcher::PointPos::start:(checkitem(t,i,2)?Sketcher::PointPos::end:Sketcher::PointPos::mid))); + auto checkpos = [](Py::Tuple& t, int i) { + auto checkitem = [](Py::Tuple& t, int i, int val) { + return long(Py::Long(t.getItem(i))) == val; + }; + return (checkitem(t, i, 0) + ? Sketcher::PointPos::none + : (checkitem(t, i, 1) ? Sketcher::PointPos::start + : (checkitem(t, i, 2) ? Sketcher::PointPos::end + : Sketcher::PointPos::mid))); }; for (const auto& ti : arg) { Py::Tuple t(ti); ConstraintIds c; c.First = (long)Py::Long(t.getItem(0)); - c.FirstPos = checkpos(t,1); + c.FirstPos = checkpos(t, 1); c.Second = (long)Py::Long(t.getItem(2)); - c.SecondPos = checkpos(t,3); + c.SecondPos = checkpos(t, 3); c.Type = Sketcher::Equal; constraints.push_back(c); @@ -1866,12 +1984,12 @@ void SketchObjectPy::setMissingRadiusConstraints(Py::List arg) this->getSketchObjectPtr()->setMissingRadiusConstraints(constraints); } -PyObject* SketchObjectPy::getGeometryWithDependentParameters(PyObject *args) +PyObject* SketchObjectPy::getGeometryWithDependentParameters(PyObject* args) { if (!PyArg_ParseTuple(args, "")) return nullptr; - std::vector> geometrymap; + std::vector> geometrymap; this->getSketchObjectPtr()->getGeometryWithDependentParameters(geometrymap); @@ -1879,7 +1997,11 @@ PyObject* SketchObjectPy::getGeometryWithDependentParameters(PyObject *args) for (auto pair : geometrymap) { Py::Tuple t(2); t.setItem(0, Py::Long(pair.first)); - t.setItem(1, Py::Long(((pair.second == Sketcher::PointPos::none)?0:(pair.second == Sketcher::PointPos::start)?1:(pair.second == Sketcher::PointPos::end)?2:3))); + t.setItem(1, + Py::Long(((pair.second == Sketcher::PointPos::none) ? 0 + : (pair.second == Sketcher::PointPos::start) ? 1 + : (pair.second == Sketcher::PointPos::end) ? 2 + : 3))); list.append(t); } return Py::new_reference_to(list); @@ -1923,10 +2045,11 @@ Py::List SketchObjectPy::getGeometryFacadeList() const for (int i = 0; i < getSketchObjectPtr()->Geometry.getSize(); i++) { // we create a python copy and add it to the list - std::unique_ptr geofacade = GeometryFacade::getFacade(getSketchObjectPtr()->Geometry[i]->clone()); + std::unique_ptr geofacade = + GeometryFacade::getFacade(getSketchObjectPtr()->Geometry[i]->clone()); geofacade->setOwner(true); - Py::Object gfp = Py::Object(new GeometryFacadePy(geofacade.release()),true); + Py::Object gfp = Py::Object(new GeometryFacadePy(geofacade.release()), true); list.append(gfp); } @@ -1935,17 +2058,17 @@ Py::List SketchObjectPy::getGeometryFacadeList() const void SketchObjectPy::setGeometryFacadeList(Py::List value) { - std::vector list; + std::vector list; list.reserve(value.size()); - for (const auto & ti : value) { + for (const auto& ti : value) { if (PyObject_TypeCheck(ti.ptr(), &(GeometryFacadePy::Type))) { - GeometryFacadePy * gfp = static_cast(ti.ptr()); + GeometryFacadePy* gfp = static_cast(ti.ptr()); - GeometryFacade * gf = gfp->getGeometryFacadePtr(); + GeometryFacade* gf = gfp->getGeometryFacadePtr(); - Part::Geometry * geo = gf->getGeometry()->clone(); + Part::Geometry* geo = gf->getGeometry()->clone(); list.push_back(geo); } @@ -1954,7 +2077,7 @@ void SketchObjectPy::setGeometryFacadeList(Py::List value) getSketchObjectPtr()->Geometry.setValues(std::move(list)); } -PyObject* SketchObjectPy::getGeometryId(PyObject *args) +PyObject* SketchObjectPy::getGeometryId(PyObject* args) { int Index; if (!PyArg_ParseTuple(args, "i", &Index)) @@ -1969,10 +2092,10 @@ PyObject* SketchObjectPy::getGeometryId(PyObject *args) Py_Return; } - return Py::new_reference_to(Py::Long(Id)); + return Py::new_reference_to(Py::Long(Id)); } -PyObject* SketchObjectPy::setGeometryId(PyObject *args) +PyObject* SketchObjectPy::setGeometryId(PyObject* args) { int Index; long Id; @@ -1990,9 +2113,7 @@ PyObject* SketchObjectPy::setGeometryId(PyObject *args) } - - -PyObject *SketchObjectPy::getCustomAttributes(const char* /*attr*/) const +PyObject* SketchObjectPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -2000,10 +2121,10 @@ PyObject *SketchObjectPy::getCustomAttributes(const char* /*attr*/) const int SketchObjectPy::setCustomAttributes(const char* attr, PyObject* obj) { // search in PropertyList - App::Property *prop = getSketchObjectPtr()->getPropertyByName(attr); + App::Property* prop = getSketchObjectPtr()->getPropertyByName(attr); if (prop) { // Read-only attributes must not be set over its Python interface - short Type = getSketchObjectPtr()->getPropertyType(prop); + short Type = getSketchObjectPtr()->getPropertyType(prop); if (Type & App::Prop_ReadOnly) { std::stringstream s; s << "Object attribute '" << attr << "' is read-only"; @@ -2012,7 +2133,7 @@ int SketchObjectPy::setCustomAttributes(const char* attr, PyObject* obj) prop->setPyObject(obj); - if (strcmp(attr,"Geometry") == 0) + if (strcmp(attr, "Geometry") == 0) getSketchObjectPtr()->rebuildVertexIndex(); return 1; diff --git a/src/Mod/Sketcher/App/SketchObjectSF.cpp b/src/Mod/Sketcher/App/SketchObjectSF.cpp index e353c67079..7a76de4c01 100644 --- a/src/Mod/Sketcher/App/SketchObjectSF.cpp +++ b/src/Mod/Sketcher/App/SketchObjectSF.cpp @@ -33,8 +33,11 @@ PROPERTY_SOURCE(Sketcher::SketchObjectSF, Part::Part2DObject) SketchObjectSF::SketchObjectSF() { - ADD_PROPERTY_TYPE(SketchFlatFile,(nullptr),"",(App::PropertyType)(App::Prop_None), - "SketchFlat file (*.skf) which defines this sketch"); + ADD_PROPERTY_TYPE(SketchFlatFile, + (nullptr), + "", + (App::PropertyType)(App::Prop_None), + "SketchFlat file (*.skf) which defines this sketch"); } short SketchObjectSF::mustExecute() const @@ -44,9 +47,11 @@ short SketchObjectSF::mustExecute() const return 0; } -App::DocumentObjectExecReturn *SketchObjectSF::execute() +App::DocumentObjectExecReturn* SketchObjectSF::execute() { - Base::Console().Warning("%s: This feature is deprecated and won't be longer supported in future FreeCAD versions\n",this->getNameInDocument()); - // do nothing + Base::Console().Warning( + "%s: This feature is deprecated and won't be longer supported in future FreeCAD versions\n", + this->getNameInDocument()); + // do nothing return App::DocumentObject::StdReturn; } diff --git a/src/Mod/Sketcher/App/SketchObjectSF.h b/src/Mod/Sketcher/App/SketchObjectSF.h index a9d60cd601..06f12f2e0c 100644 --- a/src/Mod/Sketcher/App/SketchObjectSF.h +++ b/src/Mod/Sketcher/App/SketchObjectSF.h @@ -31,7 +31,7 @@ namespace Sketcher { -class SketchObjectSF :public Part::Part2DObject +class SketchObjectSF: public Part::Part2DObject { PROPERTY_HEADER_WITH_OVERRIDE(Sketcher::SketchObjectSF); @@ -44,21 +44,19 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// Uses the standard ViewProvider - //const char* getViewProviderName(void) const { - // return "SketcherGui::ViewProviderSketchSF"; - //} + // const char* getViewProviderName(void) const { + // return "SketcherGui::ViewProviderSketchSF"; + // } //@} bool save(const char* FileName); bool load(const char* FileName); - - }; -} //namespace Part +}// namespace Sketcher -#endif // SKETCH_SKETCHOBJECTSF_H +#endif// SKETCH_SKETCHOBJECTSF_H diff --git a/src/Mod/Sketcher/App/SketchObjectSFPyImp.cpp b/src/Mod/Sketcher/App/SketchObjectSFPyImp.cpp index ac695a9814..592c2ccef0 100644 --- a/src/Mod/Sketcher/App/SketchObjectSFPyImp.cpp +++ b/src/Mod/Sketcher/App/SketchObjectSFPyImp.cpp @@ -24,8 +24,8 @@ // inclusion of the generated files (generated out of SketchObjectSFPy.xml) #include "SketchObjectSFPy.h" -#include "SketchObjectSFPy.cpp" +#include "SketchObjectSFPy.cpp" using namespace Sketcher; @@ -35,12 +35,12 @@ std::string SketchObjectSFPy::representation() const return ""; } -PyObject *SketchObjectSFPy::getCustomAttributes(const char* /*attr*/) const +PyObject* SketchObjectSFPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } int SketchObjectSFPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) { - return 0; + return 0; } diff --git a/src/Mod/Sketcher/App/SketchPyImp.cpp b/src/Mod/Sketcher/App/SketchPyImp.cpp index cf089498e3..4949eca6d4 100644 --- a/src/Mod/Sketcher/App/SketchPyImp.cpp +++ b/src/Mod/Sketcher/App/SketchPyImp.cpp @@ -28,9 +28,10 @@ // inclusion of the generated files (generated out of SketchPy.xml) #include "SketchPy.h" -#include "SketchPy.cpp" -#include "ConstraintPy.h" +#include "SketchPy.cpp" + +#include "ConstraintPy.h" using namespace Sketcher; using namespace Part; @@ -41,7 +42,7 @@ std::string SketchPy::representation() const return std::string(""); } -PyObject *SketchPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* SketchPy::PyMake(struct _typeobject*, PyObject*, PyObject*)// Python wrapper { // create a new instance of SketchPy and the Twin object return new SketchPy(new Sketch()); @@ -55,7 +56,7 @@ int SketchPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) // +++ methods implementer ++++++++++++++++++++++++++++++++++++++++++++++++ -PyObject* SketchPy::solve(PyObject *args) +PyObject* SketchPy::solve(PyObject* args) { if (!PyArg_ParseTuple(args, "")) return nullptr; @@ -63,23 +64,23 @@ PyObject* SketchPy::solve(PyObject *args) return Py::new_reference_to(Py::Long(getSketchPtr()->solve())); } -PyObject* SketchPy::addGeometry(PyObject *args) +PyObject* SketchPy::addGeometry(PyObject* args) { - PyObject *pcObj; + PyObject* pcObj; if (!PyArg_ParseTuple(args, "O", &pcObj)) return nullptr; if (PyObject_TypeCheck(pcObj, &(Part::GeometryPy::Type))) { - Part::Geometry *geo = static_cast(pcObj)->getGeometryPtr(); + Part::Geometry* geo = static_cast(pcObj)->getGeometryPtr(); return Py::new_reference_to(Py::Long(this->getSketchPtr()->addGeometry(geo))); } - else if (PyObject_TypeCheck(pcObj, &(PyList_Type)) || - PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { - std::vector geoList; + else if (PyObject_TypeCheck(pcObj, &(PyList_Type)) + || PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { + std::vector geoList; Py::Sequence list(pcObj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(Part::GeometryPy::Type))) { - Part::Geometry *geo = static_cast((*it).ptr())->getGeometryPtr(); + Part::Geometry* geo = static_cast((*it).ptr())->getGeometryPtr(); geoList.push_back(geo); } } @@ -87,7 +88,7 @@ PyObject* SketchPy::addGeometry(PyObject *args) int ret = this->getSketchPtr()->addGeometry(geoList) + 1; std::size_t numGeo = geoList.size(); Py::Tuple tuple(numGeo); - for (std::size_t i=0; i((*it).ptr())->getConstraintPtr(); + Constraint* con = static_cast((*it).ptr())->getConstraintPtr(); values.push_back(con); } } @@ -118,14 +119,14 @@ PyObject* SketchPy::addConstraint(PyObject *args) int ret = getSketchPtr()->addConstraints(values) + 1; std::size_t numCon = values.size(); Py::Tuple tuple(numCon); - for (std::size_t i=0; i(pcObj); + else if (PyObject_TypeCheck(pcObj, &(ConstraintPy::Type))) { + ConstraintPy* pcObject = static_cast(pcObj); int ret = getSketchPtr()->addConstraint(pcObject->getConstraintPtr()); return Py::new_reference_to(Py::Long(ret)); } @@ -136,7 +137,7 @@ PyObject* SketchPy::addConstraint(PyObject *args) } } -PyObject* SketchPy::clear(PyObject *args) +PyObject* SketchPy::clear(PyObject* args) { if (!PyArg_ParseTuple(args, "")) return nullptr; @@ -146,23 +147,25 @@ PyObject* SketchPy::clear(PyObject *args) Py_RETURN_NONE; } -PyObject* SketchPy::movePoint(PyObject *args) +PyObject* SketchPy::movePoint(PyObject* args) { - int index1,index2; - PyObject *pcObj; - int relative=0; - if (!PyArg_ParseTuple(args, "iiO!|i", &index1,&index2,&(Base::VectorPy::Type),&pcObj,&relative)) + int index1, index2; + PyObject* pcObj; + int relative = 0; + if (!PyArg_ParseTuple( + args, "iiO!|i", &index1, &index2, &(Base::VectorPy::Type), &pcObj, &relative)) return nullptr; Base::Vector3d* toPoint = static_cast(pcObj)->getVectorPtr(); - return Py::new_reference_to(Py::Long(getSketchPtr()->movePoint(index1,static_cast(index2),*toPoint,(relative>0)))); + return Py::new_reference_to(Py::Long(getSketchPtr()->movePoint( + index1, static_cast(index2), *toPoint, (relative > 0)))); } // +++ attributes implementer ++++++++++++++++++++++++++++++++++++++++++++++++ Py::Long SketchPy::getConstraint() const { - //return Py::Int(); + // return Py::Int(); throw Py::AttributeError("Not yet implemented"); } @@ -170,7 +173,7 @@ Py::Tuple SketchPy::getConflicts() const { std::vector c = getSketchPtr()->getConflicting(); Py::Tuple t(c.size()); - for (std::size_t i=0; i c = getSketchPtr()->getRedundant(); Py::Tuple t(c.size()); - for (std::size_t i=0; i(cpy)->Edge = this->Edge; - static_cast(cpy)->Start = this->Start; - static_cast(cpy)->End = this->End; - static_cast(cpy)->Mid = this->Mid; + static_cast(cpy)->Edge = this->Edge; + static_cast(cpy)->Start = this->Start; + static_cast(cpy)->End = this->End; + static_cast(cpy)->Mid = this->Mid; } std::unique_ptr SolverGeometryExtension::copy() const @@ -56,33 +54,35 @@ std::unique_ptr SolverGeometryExtension::copy() const copyAttributes(cpy.get()); -#if defined (__GNUC__) && (__GNUC__ <=4) +#if defined(__GNUC__) && (__GNUC__ <= 4) return std::move(cpy); #else return cpy; #endif } -PyObject * SolverGeometryExtension::getPyObject() +PyObject* SolverGeometryExtension::getPyObject() { THROWM(Base::NotImplementedError, "SolverGeometryExtension does not have a Python counterpart"); } -SolverGeometryExtension::PointParameterStatus SolverGeometryExtension::getPoint(Sketcher::PointPos pos) const { - if(pos==Sketcher::PointPos::start) +SolverGeometryExtension::PointParameterStatus +SolverGeometryExtension::getPoint(Sketcher::PointPos pos) const +{ + if (pos == Sketcher::PointPos::start) return getStartPoint(); - if(pos==Sketcher::PointPos::end) + if (pos == Sketcher::PointPos::end) return getEndPoint(); - if(pos==Sketcher::PointPos::mid) + if (pos == Sketcher::PointPos::mid) return getMidPoint(); THROWM(Base::ValueError, "SolverGeometryExtension - getPoint: Edge is not a point"); } -void SolverGeometryExtension::notifyAttachment(Part::Geometry * geo) +void SolverGeometryExtension::notifyAttachment(Part::Geometry* geo) { // maps type to number of solver parameters taken by the edge - static std::map edgeParamMap = { + static std::map edgeParamMap = { {Part::GeomPoint::getClassTypeId(), 0}, {Part::GeomLineSegment::getClassTypeId(), 0}, {Part::GeomArcOfCircle::getClassTypeId(), 3}, @@ -91,78 +91,80 @@ void SolverGeometryExtension::notifyAttachment(Part::Geometry * geo) {Part::GeomEllipse::getClassTypeId(), 3}, {Part::GeomArcOfHyperbola::getClassTypeId(), 5}, {Part::GeomArcOfParabola::getClassTypeId(), 4}, - {Part::GeomBSplineCurve::getClassTypeId(), 0} // is dynamic + {Part::GeomBSplineCurve::getClassTypeId(), 0}// is dynamic }; GeometryType = geo->getTypeId(); auto result = edgeParamMap.find(GeometryType); - if( result == edgeParamMap.end() ) - THROWM(Base::TypeError, "SolverGeometryExtension - notifyAttachment - Geometry not supported!!"); + if (result == edgeParamMap.end()) + THROWM(Base::TypeError, + "SolverGeometryExtension - notifyAttachment - Geometry not supported!!"); auto nedgeparams = (*result).second; - if(nedgeparams>0) + if (nedgeparams > 0) Edge.init(nedgeparams); } -void SolverGeometryExtension::ensureType(const Base::Type & type) +void SolverGeometryExtension::ensureType(const Base::Type& type) { - if(GeometryType != type) - THROWM(Base::TypeError, "SolverGeometryExtension - requested edge parameters do not match underlying type!"); + if (GeometryType != type) + THROWM(Base::TypeError, + "SolverGeometryExtension - requested edge parameters do not match underlying type!"); } -SolverGeometryExtension::Point & SolverGeometryExtension::getPoint() +SolverGeometryExtension::Point& SolverGeometryExtension::getPoint() { ensureType(Part::GeomPoint::getClassTypeId()); - return static_cast(Edge); + return static_cast(Edge); } -SolverGeometryExtension::Line & SolverGeometryExtension::getLine() +SolverGeometryExtension::Line& SolverGeometryExtension::getLine() { ensureType(Part::GeomLineSegment::getClassTypeId()); - return static_cast(Edge); + return static_cast(Edge); } -SolverGeometryExtension::Arc & SolverGeometryExtension::getArc() +SolverGeometryExtension::Arc& SolverGeometryExtension::getArc() { ensureType(Part::GeomArcOfCircle::getClassTypeId()); - return static_cast(Edge); + return static_cast(Edge); } -SolverGeometryExtension::Circle & SolverGeometryExtension::getCircle() +SolverGeometryExtension::Circle& SolverGeometryExtension::getCircle() { ensureType(Part::GeomCircle::getClassTypeId()); - return static_cast(Edge); + return static_cast(Edge); } -SolverGeometryExtension::ArcOfEllipse & SolverGeometryExtension::getArcOfEllipse() +SolverGeometryExtension::ArcOfEllipse& SolverGeometryExtension::getArcOfEllipse() { ensureType(Part::GeomArcOfEllipse::getClassTypeId()); - return static_cast(Edge); + return static_cast(Edge); } -SolverGeometryExtension::Ellipse & SolverGeometryExtension::getEllipse() +SolverGeometryExtension::Ellipse& SolverGeometryExtension::getEllipse() { ensureType(Part::GeomEllipse::getClassTypeId()); - return static_cast(Edge); + return static_cast(Edge); } -SolverGeometryExtension::ArcOfHyperbola & SolverGeometryExtension::getArcOfHyperbola() +SolverGeometryExtension::ArcOfHyperbola& SolverGeometryExtension::getArcOfHyperbola() { ensureType(Part::GeomArcOfHyperbola::getClassTypeId()); - return static_cast(Edge); + return static_cast(Edge); } -SolverGeometryExtension::ArcOfParabola & SolverGeometryExtension::getArcOfParabola() +SolverGeometryExtension::ArcOfParabola& SolverGeometryExtension::getArcOfParabola() { ensureType(Part::GeomArcOfParabola::getClassTypeId()); - return static_cast(Edge); + return static_cast(Edge); } -SolverGeometryExtension::BSpline & SolverGeometryExtension::getBSpline() +SolverGeometryExtension::BSpline& SolverGeometryExtension::getBSpline() { ensureType(Part::GeomBSplineCurve::getClassTypeId()); - return static_cast(Edge); + return static_cast(Edge); } diff --git a/src/Mod/Sketcher/App/SolverGeometryExtension.h b/src/Mod/Sketcher/App/SolverGeometryExtension.h index e2bc799df7..790076a8f9 100644 --- a/src/Mod/Sketcher/App/SolverGeometryExtension.h +++ b/src/Mod/Sketcher/App/SolverGeometryExtension.h @@ -33,55 +33,95 @@ namespace Sketcher { -class SketcherExport SolverGeometryExtension : public Part::GeometryExtension +class SketcherExport SolverGeometryExtension: public Part::GeometryExtension { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: - enum SolverStatus { + enum SolverStatus + { FullyConstraint = 0, NotFullyConstraint = 1, NumSolverStatus }; - enum ParameterStatus { + enum ParameterStatus + { Dependent = 0, Independent = 1, NumParameterStatus }; - class PointParameterStatus { + class PointParameterStatus + { public: - explicit PointParameterStatus(ParameterStatus status) {setStatus(status);} - PointParameterStatus(ParameterStatus statusx, ParameterStatus statusy) {setStatus(statusx, statusy);} + explicit PointParameterStatus(ParameterStatus status) + { + setStatus(status); + } + PointParameterStatus(ParameterStatus statusx, ParameterStatus statusy) + { + setStatus(statusx, statusy); + } - PointParameterStatus(const PointParameterStatus &) = default; - PointParameterStatus & operator=(const PointParameterStatus &) = default; - PointParameterStatus(PointParameterStatus &&) = default; - PointParameterStatus & operator=(PointParameterStatus &&) = default; + PointParameterStatus(const PointParameterStatus&) = default; + PointParameterStatus& operator=(const PointParameterStatus&) = default; + PointParameterStatus(PointParameterStatus&&) = default; + PointParameterStatus& operator=(PointParameterStatus&&) = default; - ParameterStatus getStatus() const { return (xstatus == Independent && ystatus == Independent)?Independent:Dependent;} - ParameterStatus getStatusx() const { return xstatus;} - ParameterStatus getStatusy() const { return ystatus;} + ParameterStatus getStatus() const + { + return (xstatus == Independent && ystatus == Independent) ? Independent : Dependent; + } + ParameterStatus getStatusx() const + { + return xstatus; + } + ParameterStatus getStatusy() const + { + return ystatus; + } - bool isXDoF() {return xstatus == Dependent;} - bool isYDoF() {return ystatus == Dependent;} + bool isXDoF() + { + return xstatus == Dependent; + } + bool isYDoF() + { + return ystatus == Dependent; + } - int getDoFs() { + int getDoFs() + { bool xfree = isXDoF(); bool yfree = isYDoF(); - if(xfree && yfree) + if (xfree && yfree) return 2; - else if(xfree || yfree) + else if (xfree || yfree) return 1; else return 0; } - void setStatus(ParameterStatus status) {xstatus=status; ystatus=status;} - void setStatus(ParameterStatus statusx, ParameterStatus statusy) {xstatus=statusx; ystatus=statusy;} - void setStatusx(ParameterStatus statusx) {xstatus=statusx;} - void setStatusy(ParameterStatus statusy) {ystatus=statusy;} + void setStatus(ParameterStatus status) + { + xstatus = status; + ystatus = status; + } + void setStatus(ParameterStatus statusx, ParameterStatus statusy) + { + xstatus = statusx; + ystatus = statusy; + } + void setStatusx(ParameterStatus statusx) + { + xstatus = statusx; + } + void setStatusy(ParameterStatus statusy) + { + ystatus = statusy; + } private: ParameterStatus xstatus; @@ -93,108 +133,192 @@ public: public: EdgeParameterStatus() = default; - void init(int nparams) { pstatus.resize(nparams, ParameterStatus::Dependent);} - - ParameterStatus getStatus() const { - return std::all_of(pstatus.begin(), pstatus.end(), [](const auto & v){ return v == Independent;})?Independent:Dependent; + void init(int nparams) + { + pstatus.resize(nparams, ParameterStatus::Dependent); } - void setStatus(ParameterStatus status) { std::fill(pstatus.begin(), pstatus.end(), status);} + ParameterStatus getStatus() const + { + return std::all_of(pstatus.begin(), + pstatus.end(), + [](const auto& v) { + return v == Independent; + }) + ? Independent + : Dependent; + } - void setStatus(int index, ParameterStatus status) { - if(index >= int(pstatus.size())) - pstatus.resize(index+1,ParameterStatus::Dependent); + void setStatus(ParameterStatus status) + { + std::fill(pstatus.begin(), pstatus.end(), status); + } + + void setStatus(int index, ParameterStatus status) + { + if (index >= int(pstatus.size())) + pstatus.resize(index + 1, ParameterStatus::Dependent); pstatus.at(index) = status; - }; protected: std::vector pstatus; - }; - class Point : public EdgeParameterStatus + class Point: public EdgeParameterStatus { public: Point() = default; }; - class Line : public EdgeParameterStatus + class Line: public EdgeParameterStatus { public: Line() = default; }; - class Arc : public EdgeParameterStatus + class Arc: public EdgeParameterStatus { public: Arc() = default; - ParameterStatus getRadiusStatus() const {return pstatus[0];} - ParameterStatus getStartParameter() const {return pstatus[1];} - ParameterStatus getEndParameter() const {return pstatus[2];} + ParameterStatus getRadiusStatus() const + { + return pstatus[0]; + } + ParameterStatus getStartParameter() const + { + return pstatus[1]; + } + ParameterStatus getEndParameter() const + { + return pstatus[2]; + } }; - class Circle : public EdgeParameterStatus + class Circle: public EdgeParameterStatus { public: Circle() = default; - ParameterStatus getRadiusStatus() const {return pstatus[0];} - bool isRadiusDoF() const {return pstatus[0] == Dependent;} + ParameterStatus getRadiusStatus() const + { + return pstatus[0]; + } + bool isRadiusDoF() const + { + return pstatus[0] == Dependent; + } }; - class ArcOfEllipse : public EdgeParameterStatus + class ArcOfEllipse: public EdgeParameterStatus { public: ArcOfEllipse() = default; - ParameterStatus getFocusXStatus() const {return pstatus[0];} - ParameterStatus getFocusYStatus() const {return pstatus[1];} - ParameterStatus getFocusMinorRadiusStatus() const {return pstatus[2];} - ParameterStatus getStartParameter() const {return pstatus[3];} - ParameterStatus getEndParameter() const {return pstatus[4];} + ParameterStatus getFocusXStatus() const + { + return pstatus[0]; + } + ParameterStatus getFocusYStatus() const + { + return pstatus[1]; + } + ParameterStatus getFocusMinorRadiusStatus() const + { + return pstatus[2]; + } + ParameterStatus getStartParameter() const + { + return pstatus[3]; + } + ParameterStatus getEndParameter() const + { + return pstatus[4]; + } - bool isFocusDoF() const {return pstatus[0] == Dependent || pstatus[1] == Dependent;} - bool isMinorRadiusDoF() const {return (pstatus[2] == Dependent);} + bool isFocusDoF() const + { + return pstatus[0] == Dependent || pstatus[1] == Dependent; + } + bool isMinorRadiusDoF() const + { + return (pstatus[2] == Dependent); + } }; - class Ellipse : public EdgeParameterStatus + class Ellipse: public EdgeParameterStatus { public: Ellipse() = default; - ParameterStatus getFocusXStatus() const {return pstatus[0];} - ParameterStatus getFocusYStatus() const {return pstatus[1];} - ParameterStatus getFocusMinorRadiusStatus() const {return pstatus[2];} + ParameterStatus getFocusXStatus() const + { + return pstatus[0]; + } + ParameterStatus getFocusYStatus() const + { + return pstatus[1]; + } + ParameterStatus getFocusMinorRadiusStatus() const + { + return pstatus[2]; + } - bool isFocusDoF() const {return pstatus[0] == Dependent || pstatus[1] == Dependent;} - bool isMinorRadiusDoF() const {return (pstatus[2] == Dependent);} + bool isFocusDoF() const + { + return pstatus[0] == Dependent || pstatus[1] == Dependent; + } + bool isMinorRadiusDoF() const + { + return (pstatus[2] == Dependent); + } }; - class ArcOfHyperbola : public EdgeParameterStatus + class ArcOfHyperbola: public EdgeParameterStatus { public: ArcOfHyperbola() = default; - ParameterStatus getFocusXStatus() const {return pstatus[0];} - ParameterStatus getFocusYStatus() const {return pstatus[1];} - ParameterStatus getFocusMinorRadiusStatus() const {return pstatus[2];} - ParameterStatus getStartParameter() const {return pstatus[3];} - ParameterStatus getEndParameter() const {return pstatus[4];} + ParameterStatus getFocusXStatus() const + { + return pstatus[0]; + } + ParameterStatus getFocusYStatus() const + { + return pstatus[1]; + } + ParameterStatus getFocusMinorRadiusStatus() const + { + return pstatus[2]; + } + ParameterStatus getStartParameter() const + { + return pstatus[3]; + } + ParameterStatus getEndParameter() const + { + return pstatus[4]; + } }; - class ArcOfParabola : public EdgeParameterStatus + class ArcOfParabola: public EdgeParameterStatus { public: ArcOfParabola() = default; - ParameterStatus getFocusXStatus() const {return pstatus[0];} - ParameterStatus getFocusYStatus() const {return pstatus[1];} + ParameterStatus getFocusXStatus() const + { + return pstatus[0]; + } + ParameterStatus getFocusYStatus() const + { + return pstatus[1]; + } }; - class BSpline : public EdgeParameterStatus + class BSpline: public EdgeParameterStatus { public: BSpline() = default; @@ -203,30 +327,28 @@ public: { int npoles = pstatus.size() / 3; - if(poleindex < npoles) - return pstatus[poleindex*2]; + if (poleindex < npoles) + return pstatus[poleindex * 2]; THROWM(Base::IndexError, "Pole index out of range") - } ParameterStatus getPoleYStatus(int poleindex) const { int npoles = pstatus.size() / 3; - if(poleindex < npoles) - return pstatus[poleindex*2+1]; + if (poleindex < npoles) + return pstatus[poleindex * 2 + 1]; THROWM(Base::IndexError, "Pole index out of range") - } ParameterStatus getWeightStatus(int weightindex) const { int nweights = pstatus.size() / 3; - if(weightindex < nweights) - return pstatus[nweights*2 + weightindex]; + if (weightindex < nweights) + return pstatus[nweights * 2 + weightindex]; THROWM(Base::IndexError, "Weight index out of range") } @@ -238,51 +360,112 @@ public: std::unique_ptr copy() const override; - PyObject *getPyObject() override; + PyObject* getPyObject() override; - void notifyAttachment(Part::Geometry * geo) override; + void notifyAttachment(Part::Geometry* geo) override; - SolverStatus getGeometry() const {return ( Edge.getStatus() == Independent && - Start.getStatus() == Independent && - End.getStatus() == Independent && - Mid.getStatus() == Independent) ? FullyConstraint : NotFullyConstraint;} + SolverStatus getGeometry() const + { + return (Edge.getStatus() == Independent && Start.getStatus() == Independent + && End.getStatus() == Independent && Mid.getStatus() == Independent) + ? FullyConstraint + : NotFullyConstraint; + } - ParameterStatus getEdge() const {return Edge.getStatus();} - Point & getPoint(); - Line & getLine(); - Arc & getArc(); - Circle & getCircle(); - ArcOfEllipse & getArcOfEllipse(); - Ellipse & getEllipse(); - ArcOfHyperbola & getArcOfHyperbola(); - ArcOfParabola & getArcOfParabola(); - BSpline & getBSpline(); - EdgeParameterStatus getEdgeParameters() {return Edge;} - void setEdge(ParameterStatus status) {Edge.setStatus(status);} - void setEdge(int paramindex, ParameterStatus status) {Edge.setStatus(paramindex,status);} + ParameterStatus getEdge() const + { + return Edge.getStatus(); + } + Point& getPoint(); + Line& getLine(); + Arc& getArc(); + Circle& getCircle(); + ArcOfEllipse& getArcOfEllipse(); + Ellipse& getEllipse(); + ArcOfHyperbola& getArcOfHyperbola(); + ArcOfParabola& getArcOfParabola(); + BSpline& getBSpline(); + EdgeParameterStatus getEdgeParameters() + { + return Edge; + } + void setEdge(ParameterStatus status) + { + Edge.setStatus(status); + } + void setEdge(int paramindex, ParameterStatus status) + { + Edge.setStatus(paramindex, status); + } - ParameterStatus getStart() const {return Start.getStatus();} - PointParameterStatus getStartPoint() const {return Start;} - void setStart(ParameterStatus xstatus, ParameterStatus ystatus) {Start.setStatus(xstatus,ystatus);} - void setStartx(ParameterStatus xstatus) {Start.setStatusx(xstatus);} - void setStarty(ParameterStatus ystatus) {Start.setStatusy(ystatus);} + ParameterStatus getStart() const + { + return Start.getStatus(); + } + PointParameterStatus getStartPoint() const + { + return Start; + } + void setStart(ParameterStatus xstatus, ParameterStatus ystatus) + { + Start.setStatus(xstatus, ystatus); + } + void setStartx(ParameterStatus xstatus) + { + Start.setStatusx(xstatus); + } + void setStarty(ParameterStatus ystatus) + { + Start.setStatusy(ystatus); + } - ParameterStatus getMid() const {return Mid.getStatus();} - PointParameterStatus getMidPoint() const {return Mid;} - void setMid(ParameterStatus xstatus, ParameterStatus ystatus) {Mid.setStatus(xstatus,ystatus);} - void setMidx(ParameterStatus xstatus) {Mid.setStatusx(xstatus);} - void setMidy(ParameterStatus ystatus) {Mid.setStatusy(ystatus);} + ParameterStatus getMid() const + { + return Mid.getStatus(); + } + PointParameterStatus getMidPoint() const + { + return Mid; + } + void setMid(ParameterStatus xstatus, ParameterStatus ystatus) + { + Mid.setStatus(xstatus, ystatus); + } + void setMidx(ParameterStatus xstatus) + { + Mid.setStatusx(xstatus); + } + void setMidy(ParameterStatus ystatus) + { + Mid.setStatusy(ystatus); + } - ParameterStatus getEnd() const {return End.getStatus();} - PointParameterStatus getEndPoint() const {return End;} + ParameterStatus getEnd() const + { + return End.getStatus(); + } + PointParameterStatus getEndPoint() const + { + return End; + } - void setEnd(ParameterStatus xstatus, ParameterStatus ystatus) {End.setStatus(xstatus,ystatus);} - void setEndx(ParameterStatus xstatus) {End.setStatusx(xstatus);} - void setEndy(ParameterStatus ystatus) {End.setStatusy(ystatus);} + void setEnd(ParameterStatus xstatus, ParameterStatus ystatus) + { + End.setStatus(xstatus, ystatus); + } + void setEndx(ParameterStatus xstatus) + { + End.setStatusx(xstatus); + } + void setEndy(ParameterStatus ystatus) + { + End.setStatusy(ystatus); + } PointParameterStatus getPoint(Sketcher::PointPos pos) const; - void init(ParameterStatus status) { + void init(ParameterStatus status) + { Edge.setStatus(status); Start.setStatus(status); Mid.setStatus(status); @@ -290,24 +473,24 @@ public: } protected: - void copyAttributes(Part::GeometryExtension * cpy) const override; + void copyAttributes(Part::GeometryExtension* cpy) const override; private: SolverGeometryExtension(const SolverGeometryExtension&) = default; - void ensureType(const Base::Type & type); + void ensureType(const Base::Type& type); private: - EdgeParameterStatus Edge; + EdgeParameterStatus Edge; - PointParameterStatus Start; - PointParameterStatus Mid; - PointParameterStatus End; + PointParameterStatus Start; + PointParameterStatus Mid; + PointParameterStatus End; - Base::Type GeometryType; + Base::Type GeometryType; }; -} //namespace Sketcher +}// namespace Sketcher -#endif // SKETCHER_SOLVERGEOMETRYEXTENSION_H +#endif// SKETCHER_SOLVERGEOMETRYEXTENSION_H