//
//    File: texture.cc
//
//    (C) 2000-2008 Helmut Cantzler
//
//    Licensed under the terms of the Lesser General Public License.
//

#include "texture.h"

Texture::Texture()
{
  GLint proxyComponents;

  image = new Image();

  // check which texture sizes are supported
  maxSize=4096*2;
  do
    {
      maxSize/=2;
      glTexImage2D(GL_PROXY_TEXTURE_2D, 0, GL_RGB, maxSize, maxSize, 0,
                   GL_RGB, GL_UNSIGNED_BYTE, NULL);
      glGetTexLevelParameteriv(GL_PROXY_TEXTURE_2D, 0, 
                               GL_TEXTURE_INTERNAL_FORMAT, &proxyComponents);
    }
  while (proxyComponents != GL_RGB && proxyComponents != GL_RGB8);

  //printf("Max texture size is: %dx%d\n", maxSize, maxSize);
}

Texture::~Texture()
{
  delete image;
}

int Texture::read(const char *filename)
{
  int width, height;

  delete image;
  image = new Image();

  // Read the image
  if (image->read(filename) != 0)
    return 1;

  //  printf(" Read texture: %s\n", filename);

  //textureFormat=GL_LUMINANCE;
  textureFormat=GL_RGB;

  // Find texture size
  width=maxSize;
  height=maxSize;

  while (image->width() / width < 0.8)
    width/=2;
  while (image->height() / height < 0.8)
    height/=2;

  //  printf(" Scale from %dx%d to %dx%d\n", imageHeight, imageWidth,
  //	 textureHeight, textureWidth);

  // Scale image to texture size
  image->scale(height, width);

  return 0;
}

int Texture::height(void) const
{
  return image->height();
}

int Texture::width(void) const
{
  return image->width();
}

int Texture::colorComponents(void) const
{
  return 3;
}

GLenum Texture::format(void) const
{
  return textureFormat;
}

const unsigned char* Texture::data(void) const
{
  return image->data();
}
