<commit_before>/***************************************************************************
 *   Copyright (c) 2013 <NAME>                                    *
 *                                   <<EMAIL>> *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/


#include "PreCompiled.h"

#ifndef _PreComp_
# include <math.h> //OvG: Required for log10
# include <TopoDS.hxx>
# include <BRepGProp_Face.hxx>
# include <gp_Vec.hxx>
# include <gp_Pnt.hxx>
# include <gp_Pln.hxx>
# include <gp_Cylinder.hxx>
# include <gp_Ax3.hxx>
# include <BRepAdaptor_Curve.hxx>
# include <GCPnts_AbscissaPoint.hxx>
# include <Adaptor3d_IsoCurve.hxx>
# include <Adaptor3d_HSurface.hxx>
# include <BRepAdaptor_HSurface.hxx>
# include <BRepAdaptor_Surface.hxx>
# include <GProp_GProps.hxx>
# include <BRepGProp.hxx>
# include <TopoDS_Vertex.hxx>
# include <BRepClass_FaceClassifier.hxx>
# include <BRep_Tool.hxx>
# include <BRepGProp_Face.hxx>
# include <ShapeAnalysis.hxx>
# include <GeomAPI_ProjectPointOnSurf.hxx>
# include <GeomAPI_IntCS.hxx>
# include <Geom_Plane.hxx>
# include <Geom_Line.hxx>
# include <Precision.hxx>
#endif

#include "FemConstraint.h"
#include "FemTools.h"

#include <App/DocumentObjectPy.h>
#include <App/FeaturePythonPyImp.h>

#include <Mod/Part/App/PartFeature.h>
#include <Base/Console.h>
#include <Base/Exception.h>


using namespace Fem;

// maybe in the c++ standard later, older compiler don't have round()
#if _MSC_VER <= 1700
double round(double r) {
    return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5);
}
#endif

PROPERTY_SOURCE(Fem::Constraint, App::DocumentObject)

Constraint::Constraint()
{
    ADD_PROPERTY_TYPE(References,(0,0),"Constraint",(App::PropertyType)(App::Prop_None),"Elements where the constraint is applied");
    ADD_PROPERTY_TYPE(NormalDirection,(Base::Vector3d(0,0,1)),"Constraint",App::PropertyType(App::Prop_ReadOnly|App::Prop_Output),"Normal direction pointing outside of solid");
    ADD_PROPERTY_TYPE(Scale,(1),"Base",App::PropertyType(App::Prop_Output),"Scale used for drawing constraints"); //OvG: Add scale parameter inherited by all derived constraints

    References.setScope(App::LinkScope::Global);
}

Constraint::~Constraint()
{
}

App::DocumentObjectExecReturn *Constraint::execute(void)
{
    References.touch();
    Scale.touch();
    return StdReturn;
}

//OvG: Provide the ability to determine how big to draw constraint arrows etc.
int Constraint::calcDrawScaleFactor(double lparam) const
{
    return ((int)round(log(lparam)*log(lparam)*log(lparam)/10)>1)?((int)round(log(lparam)*log(lparam)*log(lparam)/10)):1;
}

int Constraint::calcDrawScaleFactor(double lvparam, double luparam) const
{
    return calcDrawScaleFactor((lvparam+luparam)/2.0);
}

int Constraint::calcDrawScaleFactor() const
{
    return 1;
}
#define CONSTRAINTSTEPLIMIT 50

void Constraint::onChanged(const App::Property* prop)
{
    if (prop == &References) {
        // If References are changed, recalculate the normal direction. If no useful reference is found,
        // use z axis or previous value. If several faces are selected, only the first one is used
        std::vector<App::DocumentObject*> Objects = References.getValues();
        std::vector<std::string> SubElements = References.getSubValues();

        // Extract geometry from References
        TopoDS_Shape sh;

        for (std::size_t i = 0; i < Objects.size(); i++) {
            App::DocumentObject* obj = Objects[i];
            Part::Feature* feat = static_cast<Part::Feature*>(obj);
            const Part::TopoShape& toposhape = feat->Shape.getShape();
            if (!toposhape.getShape().IsNull()) {
                sh = toposhape.getSubShape(SubElements[i].c_str());

                if (sh.ShapeType() == TopAbs_FACE) {
                    // Get face normal in center point
                    TopoDS_Face face = TopoDS::Face(sh);
                    BRepGProp_Face props(face);
                    gp_Vec normal;
                    gp_Pnt center;
                    double u1,u2,v1,v2;
                    props.Bounds(u1,u2,v1,v2);
                    props.Normal((u1+u2)/2.0,(v1+v2)/2.0,center,normal);
                    normal.Normalize();
                    NormalDirection.setValue(normal.X(), normal.Y(), normal.Z());
                    // One face is enough...
                    App::DocumentObject::onChanged(prop);
                    return;
                }
            }
        }
    }

    App::DocumentObject::onChanged(prop);
}

void Constraint::onDocumentRestored()
{
    // This seems to be the only way to make the ViewProvider display the constraint
    References.touch();
    App::DocumentObject::onDocumentRestored();
}

bool Constraint::getPoints(std::vector<Base::Vector3d> &points, std::vector<Base::Vector3d> &normals, int * scale) const
{
    std::vector<App::DocumentObject*> Objects = References.getValues();
    std::vector<std::string> SubElements = References.getSubValues();

    // Extract geometry from References
    TopoDS_Shape sh;

    for (std::size_t i = 0; i < Objects.size(); i++) {
        App::DocumentObject* obj = Objects[i];
        Part::Feature* feat = static_cast<Part::Feature*>(obj);
        const Part::TopoShape& toposhape = feat->Shape.getShape();
        if (toposhape.isNull())
            return false;

        sh = toposhape.getSubShape(SubElements[i].c_str());

        if (sh.ShapeType() == TopAbs_VERTEX) {
            const TopoDS_Vertex& vertex = TopoDS::Vertex(sh);
            gp_Pnt p = BRep_Tool::Pnt(vertex);
            points.emplace_back(p.X(), p.Y(), p.Z());
            normals.push_back(NormalDirection.getValue());
            //OvG: Scale by whole object mass in case of a vertex
            GProp_GProps props;
            BRepGProp::VolumeProperties(toposhape.getShape(), props);
            double lx = props.Mass();
            *scale = this->calcDrawScaleFactor(sqrt(lx)*0.5); //OvG: setup draw scale for constraint
        }
        else if (sh.ShapeType() == TopAbs_EDGE) {
            BRepAdaptor_Curve curve(TopoDS::Edge(sh));
            double fp = curve.FirstParameter();
            double lp = curve.LastParameter();
            GProp_GProps props;
            BRepGProp::LinearProperties(TopoDS::Edge(sh), props);
            double l = props.Mass();
            // Create points with 10 units distance, but at least one at the beginning and end of the edge
            int steps;
            if (l >= 30) //OvG: Increase 10 units distance proportionately to l for larger objects.<commit_msg>Fem: [skip ci] handle exception in Fem Constraint in case referenced shape element doesn't exist<commit_after>/***************************************************************************
 *   Copyright (c) 2013 <NAME>                                    *
 *                                   <<EMAIL>> *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/


#include "PreCompiled.h"

#ifndef _PreComp_
# include <math.h> //OvG: Required for log10
# include <TopoDS.hxx>
# include <BRepGProp_Face.hxx>
# include <gp_Vec.hxx>
# include <gp_Pnt.hxx>
# include <gp_Pln.hxx>
# include <gp_Cylinder.hxx>
# include <gp_Ax3.hxx>
# include <BRepAdaptor_Curve.hxx>
# include <GCPnts_AbscissaPoint.hxx>
# include <Adaptor3d_IsoCurve.hxx>
# include <Adaptor3d_HSurface.hxx>
# include <BRepAdaptor_HSurface.hxx>
# include <BRepAdaptor_Surface.hxx>
# include <GProp_GProps.hxx>
# include <BRepGProp.hxx>
# include <TopoDS_Vertex.hxx>
# include <BRepClass_FaceClassifier.hxx>
# include <BRep_Tool.hxx>
# include <BRepGProp_Face.hxx>
# include <ShapeAnalysis.hxx>
# include <GeomAPI_ProjectPointOnSurf.hxx>
# include <GeomAPI_IntCS.hxx>
# include <Geom_Plane.hxx>
# include <Geom_Line.hxx>
# include <Precision.hxx>
#endif

#include "FemConstraint.h"
#include "FemTools.h"

#include <App/DocumentObjectPy.h>
#include <App/FeaturePythonPyImp.h>

#include <Mod/Part/App/PartFeature.h>
#include <Base/Console.h>
#include <Base/Exception.h>


using namespace Fem;

// maybe in the c++ standard later, older compiler don't have round()
#if _MSC_VER <= 1700
double round(double r) {
    return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5);
}
#endif

PROPERTY_SOURCE(Fem::Constraint, App::DocumentObject)

Constraint::Constraint()
{
    ADD_PROPERTY_TYPE(References,(0,0),"Constraint",(App::PropertyType)(App::Prop_None),"Elements where the constraint is applied");
    ADD_PROPERTY_TYPE(NormalDirection,(Base::Vector3d(0,0,1)),"Constraint",App::PropertyType(App::Prop_ReadOnly|App::Prop_Output),"Normal direction pointing outside of solid");
    ADD_PROPERTY_TYPE(Scale,(1),"Base",App::PropertyType(App::Prop_Output),"Scale used for drawing constraints"); //OvG: Add scale parameter inherited by all derived constraints

    References.setScope(App::LinkScope::Global);
}

Constraint::~Constraint()
{
}

App::DocumentObjectExecReturn *Constraint::execute(void)
{
    try {
        References.touch();
        Scale.touch();
        return StdReturn;
    }
    catch (const Standard_Failure& e) {
        return new App::DocumentObjectExecReturn(e.GetMessageString(), this);
    }
}

//OvG: Provide the ability to determine how big to draw constraint arrows etc.
int Constraint::calcDrawScaleFactor(double lparam) const
{
    return ((int)round(log(lparam)*log(lparam)*log(lparam)/10)>1)?((int)round(log(lparam)*log(lparam)*log(lparam)/10)):1;
}

int Constraint::calcDrawScaleFactor(double lvparam, double luparam) const
{
    return calcDrawScaleFactor((lvparam+luparam)/2.0);
}

int Constraint::calcDrawScaleFactor() const
{
    return 1;
}
#define CONSTRAINTSTEPLIMIT 50

void Constraint::onChanged(const App::Property* prop)
{
    if (prop == &References) {
        // If References are changed, recalculate the normal direction. If no useful reference is found,
        // use z axis or previous value. If several faces are selected, only the first one is used
        std::vector<App::DocumentObject*> Objects = References.getValues();
        std::vector<std::string> SubElements = References.getSubValues();

        // Extract geometry from References
        TopoDS_Shape sh;

        bool execute = this->isRecomputing();
        for (std::size_t i = 0; i < Objects.size(); i++) {
            App::DocumentObject* obj = Objects[i];
            Part::Feature* feat = static_cast<Part::Feature*>(obj);
            const Part::TopoShape& toposhape = feat->Shape.getShape();
            if (!toposhape.getShape().IsNull()) {
                sh = toposhape.getSubShape(SubElements[i].c_str(), !execute);

                if (!sh.IsNull() && sh.ShapeType() == TopAbs_FACE) {
                    // Get face normal in center point
                    TopoDS_Face face = TopoDS::Face(sh);
                    BRepGProp_Face props(face);
                    gp_Vec normal;
                    gp_Pnt center;
                    double u1,u2,v1,v2;
                    props.Bounds(u1,u2,v1,v2);
                    props.Normal((u1+u2)/2.0,(v1+v2)/2.0,center,normal);
                    normal.Normalize();
                    NormalDirection.setValue(normal.X(), normal.Y(), normal.Z());
                    // One face is enough...
                    break;
                }
            }
        }
    }

    App::DocumentObject::onChanged(prop);
}

void Constraint::onDocumentRestored()
{
    // This seems to be the only way to make the ViewProvider display the constraint
    References.touch();
    App::DocumentObject::onDocumentRestored();
}

bool Constraint::getPoints(std::vector<Base::Vector3d> &points, std::vector<Base::Vector3d> &normals, int * scale) const
{
    std::vector<App::DocumentObject*> Objects = References.getValues();
    std::vector<std::string> SubElements = References.getSubValues();

    // Extract geometry from References
    TopoDS_Shape sh;

    for (std::size_t i = 0; i < Objects.size(); i++) {
        App::DocumentObject* obj = Objects[i];
        Part::Feature* feat = static_cast<Part::Feature*>(obj);
        const Part::TopoShape& toposhape = feat->Shape.getShape();
        if (toposhape.isNull())
            return false;

        sh = toposhape.getSubShape(SubElements[i].c_str(), true);
        if (sh.IsNull())
            return false;

        if (sh.ShapeType() == TopAbs_VERTEX) {
            const TopoDS_Vertex& vertex = TopoDS::Vertex(sh);
            gp_Pnt p = BRep_Tool::Pnt(vertex);
            points.emplace_back(p.X(), p.Y(), p.Z());
            normals.push_back(NormalDirection.getValue());
            //OvG: Scale by whole object mass in case of a vertex
            GProp_GProps props;
            BRepGProp::VolumeProperties(toposhape.getShape(), props);
            double lx = props.Mass();
            *scale = this->calcDrawScaleFactor(sqrt(lx)*0.5); //OvG: setup draw scale for constraint
        }
        else if (sh.ShapeType() == TopAbs_EDGE) {
            BRepAdaptor_Curve curve(TopoDS::Edge(sh));
            double fp = curve.FirstParameter();
            double lp = curve.LastParameter();
            GProp_GProps props;
            BRepGProp::LinearProperties(TopoDS::Edge(sh), props);
            double l = props.Mass();
            // Create points with 10 units distance, but at least one at the beginning and end of the edge
            int steps;
            if (l >= 30) //OvG: Increase 10 units distance proportionately to l for larger objects.
{'fraction_non_alphanumeric': 0.1323101677083978, 'fraction_numerical': 0.009901602821956804, 'mean_word_length': 2.440493932297211, 'pattern_counts': {'":': 0, '<': 93, '<?xml version=': 0, '>': 100, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 36, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4803157', 'n_tokens_mistral': 4773, 'n_tokens_neox': 4571, 'n_words': 1169}