//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Img3D/View/Shader.cpp
//! @brief     Implements class Shader.
//!
//! @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 "Img3D/View/Shader.h"
#include "Base/Util/Assert.h"
#include "Img3D/View/Camera.h"

// The macro call has to be in the global namespace
inline void InitShaderResources()
{
    Q_INIT_RESOURCE(shaders);
}

static constexpr float AMBIENT = 0.4f;

namespace Img3D {

Shader::Shader()
{
    InitShaderResources(); // so that Qt will find our shaders resource files
    needsInit();
}

void Shader::needsInit()
{
    doInit = true;
}

void Shader::init()
{
    if (!doInit)
        return;
    doInit = false;

    bool ok = addShaderFromSourceFile(QOpenGLShader::Vertex, ":/shaders/vertex_shader.vert");
    ASSERT(ok);

    ok = addShaderFromSourceFile(QOpenGLShader::Fragment, ":/shaders/fragment_shader.frag");
    ASSERT(ok);

    bindAttributeLocation("vertex", 0);
    bindAttributeLocation("normal", 1);
    bindAttributeLocation("axiscolor", 2);

    link();

    bind();
    locMatProj = uniformLocation("matProj");
    locMatModel = uniformLocation("matModel");
    locMatObject = uniformLocation("matObject");
    locLightPos1 = uniformLocation("lightPos1");
    locColor = uniformLocation("color");
    ambient = uniformLocation("ambient");
    eye = uniformLocation("eye");
    locAxis = uniformLocation("axis");
    release();
}

void Shader::setCamera(Camera const& camera)
{
    setUniformValue(ambient, AMBIENT);
    setUniformValue(locMatProj, camera.matProj());
    setUniformValue(locMatModel, camera.matModel());
    setUniformValue(locLightPos1, camera.lightPosRotated());
    setUniformValue(eye, camera.getPos().eye);
}

void Shader::setColor(QColor const& color)
{
    setUniformValue(locColor, color);
}

void Shader::setMatObject(QMatrix4x4 const& mat)
{
    setUniformValue(locMatObject, mat);
}

void Shader::setMatModel(QMatrix4x4 const& mat)
{
    setUniformValue(locMatModel, mat);
}

void Shader::setAxis(bool const& axis_)
{
    setUniformValue(locAxis, axis_);
}

} // namespace Img3D
