unit texture_loading;

interface

uses
  Windows, OpenGL, Graphics, JPEG, SysUtils, variables;

procedure LoadTexture(file_name: String; var texture: GLuint);

implementation

function gluBuild2DMipmaps(Target: GLenum; Components, Width, Height: GLint; Format, atype: GLenum; Data: Pointer): GLint; stdcall; external glu32;
procedure glGenTextures(n: GLsizei; var textures: GLuint); stdcall; external opengl32;
procedure glBindTexture(target: GLenum; texture: GLuint); stdcall; external opengl32;


function CreateTexture(Width, Height : Word; pData : Pointer) : Integer;
var
  Texture : GLuint;
begin
glGenTextures(1, Texture);
glBindTexture(GL_TEXTURE_2D, Texture);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
if filtered_textures then
  begin
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  end
else
  begin
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  end;
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, Width, Height, GL_RGBA, GL_UNSIGNED_BYTE, pData);
result :=Texture;
end;

procedure LoadTexture(file_name: String; var texture : GLuint);
var
data : array of LongWord;
w, width, h, height : Integer;
b : TBitmap;
j : TJPEGImage;
c : LongWord;
line : ^LongWord;
begin
j := TJPEGImage.Create;
j.LoadFromFile(file_name);

b := TBitmap.Create;
b.pixelformat := pf32bit;
b.width := j.width;
b.height := j.height;
b.canvas.draw(0, 0, j);

width := b.width;
height := b.height;
SetLength(Data, width*height);

for h := 0 to height - 1 do
  begin
    line := b.scanline[h];
    for w := 0 to width - 1 do
      begin
        c := Line^ and $FFFFFF;
        Data[w + (h * width)] :=(((c and $FF) shl 16)+
                                  (c shr 16)+(c and $FF00)) or $FF000000; 
        inc(Line);
      end;
  end;

b.free;
j.free;

texture := CreateTexture(width, height, addr(Data[0]));
end;


end.
