unit TextureRectangle;

interface

uses Windows, SysUtils, GL, GLu, GLext, WGLext, GLtools, Images, Textures;

type
  TTextureRectangle = class(TTexture)
  protected
    procedure SetImage(img: TImage); override;
    function GetImage: TImage; override;
  public
    constructor Create; reintroduce;
  end;

implementation

constructor TTextureRectangle.Create;
begin
  if not glext_ExtensionSupported('GL_ARB_texture_rectangle') and
     not glext_ExtensionSupported('GL_EXT_texture_rectangle') and
     not glext_ExtensionSupported('GL_NV_texture_rectangle') then
       raise Exception.Create(
         'GL_ARB_texture_rectangle or equivalent required!');

  inherited Create(GL_TEXTURE_RECTANGLE_ARB);
end;

procedure TTextureRectangle.SetImage;
var
  fmt: cardinal;
begin
  Bind;
  case img.BytesPerPel of
    1: fmt := GL_RED;
    2: fmt := GL_LUMINANCE_ALPHA;
    3: fmt := GL_BGR;
    4: fmt := GL_BGRA;
    else raise Exception.Create('TTextureRectangle.SetImage: Invalid bytes per pel');
  end;
  glTexImage2D(FTarget, 0, FInternalFormat,
               img.Width, img.Height, 0, fmt, GL_UNSIGNED_BYTE, img.Data);
end;

function TTextureRectangle.GetImage;
var
  fmt: cardinal;
begin
  Bind;
  result := TImage.Create(Width, Height, BytesPerPel * 8);
  case BytesPerPel of
    1: fmt := GL_RED;
    2: fmt := GL_LUMINANCE_ALPHA;
    3: fmt := GL_BGR;
    4: fmt := GL_BGRA;
    else raise Exception.Create('TTextureRectangle.GetImage: Invalid bytes per pel');
  end;
  glGetTexImage(FTarget, 0, fmt, GL_UNSIGNED_BYTE, result.Data);
end;

end.
