#include <cstdio>
#include "Material.h"

#define MODULE_NAME "AVM_CarMaterial"
#define AVM_DEBUG_SWITCH    0
#include "Avm_log.h"

using namespace std;


void CTgaTex::InitTex(UChar * textureAddr)
{
    m_byData = textureAddr + 8;
    m_width  = *((int *)(textureAddr));
    m_height = *((int *)(textureAddr + 4));

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    if (0 == m_uTexName)
    {
        glGenTextures(1, &m_uTexName);
    }
    glBindTexture(GL_TEXTURE_2D, m_uTexName);
    glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, m_width, m_height,
            0, GL_RGB, GL_UNSIGNED_BYTE, m_byData);
    glGenerateMipmap(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, 0);
    AVM_DEBUG("Tga InitTex: m_width=%d, m_height=%d, m_uTexName=%d\n", m_width, m_height, m_uTexName);
}


void CTgaTex::SetTexture()
{
    if ((m_uTexName != 0) && (m_byData != NULL))
    {
        glBindTexture(GL_TEXTURE_2D, m_uTexName);
        AVM_DEBUG("m_uTexName=%d\n", m_uTexName);
    }
}


void CMaterial::InitTex(UChar * modelAddr)
{
    UChar * texAddr = modelAddr + m_filemtl.texoffset;
    AVM_DEBUG("start CMaterial::INitTex, texAddr=%p\n", texAddr);
    m_tgaTex.InitTex(texAddr);
}


void CMaterial::Set()
{
    m_tgaTex.SetTexture();
}

