/*Copyright (C) 2010-2012 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_GlyphSlot data)
{
    //Metrics
    m_advance.x = data->advance.x;
    m_advance.y = data->advance.y;
    
    m_topLeft.x = data->bitmap_left;
    m_topLeft.y = data->bitmap_top;
    
    //Texture
    FT_Bitmap &bitmap = data->bitmap;
    
    int width = Texture::nextPow2(bitmap.width);
    int height = Texture::nextPow2(bitmap.rows);
    
    GLubyte* pixels = new GLubyte[2 * width * height];
    
    for (int j = 0; j < height; j++)
    {
        for (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;
}

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;
}

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

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