/*Copyright (C) 2010-2020 Duncan Deveaux

This file is part of Hikou no mizu.

Hikou no mizu 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.

Hikou no mizu 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 Hikou no mizu.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "Glyph.hpp"

Glyph::Glyph() : m_width(0), m_height(0)
{
    
}

void Glyph::load(const FT_BitmapGlyph &data, const Vector &advance)
{
    //Texture
    FT_Bitmap &bitmap = data->bitmap;
    
    unsigned int width = Texture::nextPow2(bitmap.width);
    unsigned int height = Texture::nextPow2(bitmap.rows);
    
    GLubyte* pixels = new GLubyte[2 * width * height];
    
    for (unsigned int j = 0; j < height; j++)
    {
        for (unsigned int i = 0; i < width; i++)
        {
            pixels[2 * (i + j * width)] = 255;
            pixels[2 * (i + j * width) + 1] = (i >= bitmap.width || j >= bitmap.rows) ? 0 : bitmap.buffer[i + bitmap.width * j];
        }
    }
    
    m_texture.loadFromMemory(pixels, GL_RGBA, GL_LUMINANCE_ALPHA, width, height);
    delete[] pixels;
    
    m_width = bitmap.width;
    m_height = bitmap.rows;
    
    m_topLeft = Vector(data->left, data->top);
    m_advance = advance;
}

void Glyph::draw() const
{
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    
    float x2 = (m_texture.getWidth() > 0) ? static_cast<float>(m_width) / m_texture.getWidth() : 1;
    float y2 = (m_texture.getHeight() > 0) ? static_cast<float>(m_height) / m_texture.getHeight() : 1;
    
    glTranslatef(m_topLeft.x, -m_topLeft.y, 0);
    m_texture.draw(0, 0, x2, y2);
    
    glPopMatrix();
}

const Vector &Glyph::getAdvance() const
{
    return m_advance;
}

const Vector &Glyph::getTopLeft() const
{
    return m_topLeft;
}

unsigned int Glyph::getWidth() const
{
    return m_width;
}

unsigned int Glyph::getHeight() const
{
    return m_height;
}
