/*
 *  <Short Description>
 *  Copyright (C) 2023  Brett Terpstra
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
#include <blt/gfx/state.h>
#include <blt/logging/logging.h>
#include "blt/std/assert.h"

void blt::gfx::matrix_state_manager::update()
{
    pvm = perspective * view;
    blt::mat4x4 scaled;
    scaled.scale(scale_2d);
    ovm = scaled * ortho * view_2d;
    BLT_ASSERT(global_matrix_ubo != nullptr && "You forgot to call create_internals(). Make sure you call cleanup() as well!");
    global_matrix_ubo->upload((void*)perspective.ptr(), sizeof(blt::mat4x4), 0);
    global_matrix_ubo->upload((void*)ortho.ptr(), sizeof(blt::mat4x4), sizeof(blt::mat4x4));
    global_matrix_ubo->upload((void*)view.ptr(), sizeof(blt::mat4x4), sizeof(blt::mat4x4) * 2);
    global_matrix_ubo->upload((void*)pvm.ptr(), sizeof(blt::mat4x4), sizeof(blt::mat4x4) * 3);
    global_matrix_ubo->upload((void*)ovm.ptr(), sizeof(blt::mat4x4), sizeof(blt::mat4x4) * 4);
}

void blt::gfx::matrix_state_manager::update_perspectives(std::int32_t width, std::int32_t height, float fov, float near, float far, float ortho_near,
                                                         float ortho_far)
{
    if (width != last_width || height != last_height)
    {
        last_width = width;
        last_height = height;
        
        perspective = blt::perspective(fov, (float)width / (float)height, near, far);
        ortho = blt::ortho(0, (float)width, (float)height, 0, ortho_near, ortho_far);
    }
}

const blt::mat4x4& blt::gfx::matrix_state_manager::getView() const
{
    return view;
}

const blt::mat4x4& blt::gfx::matrix_state_manager::getOrtho() const
{
    return ortho;
}

const blt::mat4x4& blt::gfx::matrix_state_manager::getPerspective() const
{
    return perspective;
}

const blt::mat4x4& blt::gfx::matrix_state_manager::getPvm() const
{
    return pvm;
}

const blt::mat4x4& blt::gfx::matrix_state_manager::getOvm() const
{
    return ovm;
}

const blt::mat4x4& blt::gfx::matrix_state_manager::getView2D() const
{
    return view_2d;
}

const blt::vec3& blt::gfx::matrix_state_manager::getScale2D() const
{
    return scale_2d;
}
