Graphics Unit

unit GraphicsUnit;

interface

uses
  sdl,
  sdlutils;

// Loads Images As a Transparent Sprite!!!
function LoadImage(DataFile: String; Transparent: Boolean): PSDL_Surface;
// Unloads Images
procedure UnloadImage(Image: PSDL_Surface);
// Checks If X,Y is On Visible Screen
function onScreen(GameScreen: PSDL_Surface; X, Y, ScreenX, ScreenY: Integer): Boolean;
// Draws Tile onto GameScreen
procedure DrawTile(GameScreen: PSDL_Surface; X, Y, TileIndex, TileSize: Integer; TileSet: PSDL_Surface);
// Draws Background onto GameScreen
procedure DrawBackgound(GameScreen: PSDL_Surface; BGImage: PSDL_Surface);

implementation

// Loads Images As a Transparent Sprite!!!
function LoadImage(DataFile: String; Transparent: Boolean): PSDL_Surface;
var
  Image, Surface: PSDL_Surface;
begin
     Image := SDL_LoadBMP(PChar(DataFile));
     if (Image = nil) then
     begin
          Result := nil;
          Exit;
     end;

     if (Transparent) then
     begin
          // Assuming 32-bit BMP image
          SDL_SetColorKey(Image, (SDL_SRCCOLORKEY or SDL_RLEACCEL),
                          PUint32(Image.pixels)^);
     end;
     Surface := SDL_DisplayFormat(Image);
     SDL_FreeSurface(Image);
     Result := Surface;
end;

// Unloads Images
procedure UnloadImage(Image: PSDL_Surface);
begin
     SDL_FreeSurface(Image);
end;

function onScreen(GameScreen: PSDL_Surface; X, Y, ScreenX, ScreenY: Integer): Boolean;
begin
     Result := False;
     if ((X >= ScreenX) and (X < ScreenX + GameScreen.w)) or
        ((Y >= ScreenY) and (Y < ScreenY + GameScreen.h)) then
        Result := True;
end;

{Draw Tile}
procedure DrawTile(GameScreen: PSDL_Surface; X, Y, TileIndex, TileSize: Integer; TileSet: PSDL_Surface);
var
  SrcRect, DestRect: TSDL_Rect;
begin
     SrcRect  := SDLRect(TileIndex * TileSize, 0, TileSize, TileSize);
     DestRect := SDLRect(X, Y, TileSize, TileSize);
     if ((X < GameScreen.w) or (X > -TileSize)) and ((Y < GameScreen.h) or (Y > -TileSize)) then
        SDL_BlitSurface(TileSet, @SrcRect, GameScreen, @DestRect);
end;

{Draw Background}
procedure DrawBackgound(GameScreen: PSDL_Surface; BGImage: PSDL_Surface);
var
  SrcRect: TSDL_Rect;
begin
     SrcRect := SDLRect(0, 0, BGImage.w, BGImage.h);
     if (BGImage.w > 0) and (BGImage.h > 0) then
        SDL_BlitSurface(BGImage, @SrcRect, GameScreen, @SrcRect);
end;

end.
Programming - a skill for life!

Part 4 of republished guest tutorial by Jason McMillen