unit Occlusion;

interface

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

type
  TOcclusionQuery = class
  protected
    FQuery              : GLuint;
  public
    constructor Create; virtual;
    destructor Destroy; override;
    procedure BeginQuery; virtual;
    procedure EndQuery; virtual;
    function ResultAvail: boolean; virtual;
    function SamplesPassed: cardinal; virtual;
    function Visible: boolean; virtual;
    property Query: GLuint read FQuery;
  end;

implementation

constructor TOcclusionQuery.Create;
begin
  if not Load_GL_ARB_occlusion_query then
    raise Exception.Create('GL_ARB_occlusion_query required!');

  inherited Create;

  glGenQueriesARB(1, @FQuery);
end;

destructor TOcclusionQuery.Destroy;
begin
  glDeleteQueriesARB(1, @FQuery);

  inherited Destroy;
end;

procedure TOcclusionQuery.BeginQuery;
begin
  glBeginQueryARB(GL_SAMPLES_PASSED_ARB, FQuery);
end;

procedure TOcclusionQuery.EndQuery;
begin
  glEndQueryARB(GL_SAMPLES_PASSED_ARB);
end;

function TOcclusionQuery.ResultAvail;
var
  avail: GLint;
begin
  glGetQueryObjectivARB(FQuery, GL_QUERY_RESULT_AVAILABLE_ARB, @avail);
  result := (avail = GL_TRUE);
end;

function TOcclusionQuery.SamplesPassed;
begin
  glGetQueryObjectuivARB(FQuery, GL_QUERY_RESULT_ARB, @result);
end;

function TOcclusionQuery.Visible;
var
  samples: GLuint;
begin
  glGetQueryObjectuivARB(FQuery, GL_QUERY_RESULT_ARB, @samples);
  result := (samples > 0);
end;

end.
