unit uGmSprite;

interface

uses
  zglHeader;

type
  TSprFrame = record
    Frame     : zglTRect;
    Xoffset   : integer;
    Yoffset   : integer;
    W, H      : integer;
  end;

type
  PSprite = ^TSprite;
  TSprite = record
    Tex       : zglPTexture;
    Frames    : array of TSprFrame;
    FramesCnt : integer;
  end;

procedure Sprite_Load( Spr : PSprite; FileName : string );
procedure Sprite_Draw( Spr : PSprite; X, Y : Single; FrameN : Word; FlipX : boolean = False; alpha: byte = 255 );

implementation

//==============================================================================
procedure Sprite_Load( Spr : PSprite; FileName : string );
var
  F     : TextFile;
  str   : string;
  str2  : string;
  i, p, k ,len : integer;
begin
  AssignFile( F, FileName );
  FileMode := $0000;
  Reset( F );

  ReadLn( F, str );
  Spr.Tex := tex_LoadFromFile( file_GetDirectory( FileName ) + str );

  while not EOF( F ) do
  begin
    ReadLn( F, str );
    INC( Spr.FramesCnt );
    SetLength( Spr.Frames, Spr.FramesCnt );

    len   := Length( str );
    p     := 0;
    k     := Spr.FramesCnt - 1;
    str2  := '';

    for i := 1 to len do
    begin
      if str[ i ] <> ' ' then str2 := str2 + str[ i ];
      if str[ i ] = ' 'then
      begin
        INC( p );
        if p = 1 then Spr.Frames[ k ].Frame.X := u_StrToInt( str2 );
        if p = 2 then Spr.Frames[ k ].Frame.Y := u_StrToInt( str2 );
        if p = 3 then Spr.Frames[ k ].Frame.W := u_StrToInt( str2 );
        if p = 4 then Spr.Frames[ k ].Frame.H := u_StrToInt( str2 );
        if p = 5 then Spr.Frames[ k ].Xoffset := u_StrToInt( str2 );
        if p = 6 then Spr.Frames[ k ].Yoffset := u_StrToInt( str2 );
        if p = 7 then Spr.Frames[ k ].W       := u_StrToInt( str2 );
        if p = 8 then Spr.Frames[ k ].H       := u_StrToInt( str2 );
        str2 := '';
      end;
    end;
  end;

  CloseFile( F );
end;

//==============================================================================
procedure Sprite_Draw( Spr : PSprite; X, Y : Single; FrameN : Word; FlipX : boolean = False; alpha: byte = 255 );
var
  N : Word;
  W, H, CX, CY : single;
begin
  N := FrameN;
  if N > Spr.FramesCnt - 1 then N := Spr.FramesCnt - 1;

  W := Spr.Frames[ N ].Frame.W;
  H := Spr.Frames[ N ].Frame.H;
  if FlipX = False then
  begin
    CX := X - Spr.Frames[ N ].W / 2 + Spr.Frames[ N ].Xoffset;
    CY := Y - Spr.Frames[ N ].H / 2 + Spr.Frames[ N ].Yoffset;
    csprite2d_Draw( Spr.Tex, CX, CY, W, H, 0, Spr.Frames[ N ].Frame, alpha, FX_BLEND );
  end else
  begin
    CX := X + Spr.Frames[ N ].W / 2 - W - Spr.Frames[ N ].Xoffset;
    CY := Y - Spr.Frames[ N ].H / 2 + Spr.Frames[ N ].Yoffset;
    csprite2d_Draw( Spr.Tex, CX, CY, W, H, 0, Spr.Frames[ N ].Frame, alpha, FX_BLEND or FX2D_FLIPX );
  end;
end;

end.
