//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Device/Mask/Ellipse.cpp
//! @brief     Implements class Ellipse.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "Device/Mask/Ellipse.h"
#include "Base/Axis/Bin.h"
#include <cmath>

//! @param xcenter x-coordinate of Ellipse's center
//! @param ycenter y-coordinate of Ellipse's center
//! @param xradius Radius along x-axis
//! @param yradius Radius along y-axis
//! @param theta Angle of Ellipse rotation in radians
Ellipse::Ellipse(double xcenter, double ycenter, double xradius, double yradius, double theta)
    : IShape2D("Ellipse")
    , m_xc(xcenter)
    , m_yc(ycenter)
    , m_xr(xradius)
    , m_yr(yradius)
    , m_theta(theta)
{
    if (xradius < 0.0 || yradius < 0.0)
        throw std::runtime_error(
            "Ellipse::Ellipse(double xcenter, double ycenter, double xradius, double yradius) "
            "-> Error. Radius cannot be negative\n");
}

bool Ellipse::contains(double x, double y) const
{
    double u = std::cos(m_theta) * (x - m_xc) - std::sin(m_theta) * (y - m_yc);
    double v = std::sin(m_theta) * (x - m_xc) + std::cos(m_theta) * (y - m_yc);
    double d = (u / m_xr) * (u / m_xr) + (v / m_yr) * (v / m_yr);
    return d <= 1;
}

bool Ellipse::contains(const Bin1D& binx, const Bin1D& biny) const
{
    // The overlap of an ellipse and a rectangle, in full generality, requires quite
    // a complicated algorithm. We therefore content ourselves with a check for n*n points.
    const int n = 7;
    for (int ix = 0; ix < n; ++ix)
        for (int iy = 0; iy < n; ++iy)
            if (contains(binx.atFraction(ix / (n - 1.)), biny.atFraction(iy / (n - 1.))))
                return true;
    return false;
}

void Ellipse::print(std::ostream& ostr) const
{
    ostr << "Ellipse at " << m_xc << ", " << m_yc << " radii " << m_xr << ", " << m_yr << " theta "
         << m_theta;
}
