module "/pliant/language/context.pli"
module "/pliant/math/functions.pli"
module "/pliant/SDL/SDL.pli"

gvar Pointer:SDL_Surface tile
gvar Pointer:SDL_Surface screen

function rotate dest src angle scale
 arg Pointer:SDL_Surface dest src
 arg Float angle scale
 var Int u v du dv x y sx sy mv mu
 var uInt umask := src:w - 1
 var uInt vmask := src:h - 1
 var Address texture image
 var Float temp

 texture := src:pixels
 image := dest:pixels

 sx := 0; sy := 0

 du := cast (scale * (cos angle) * 4096.0) Int
 dv := cast (scale * (sin angle) * 4096.0) Int

 for  y 0 (dest:h - 1)
   u := sx
   v := sy

   for x 0 (dest:w - 1)
    mv := (v \ 2^12 ) .and. vmask
    mu := (u \ 2^12 ) .and. umask

    (image map uInt8) := (texture map uInt8 (mv * src:w + mu ))
    image := (image translate uInt8 1)
    u += du
    v += dv

   sx -= dv
   sy += du

 return

function init -> b
 arg Bool b

 b := true


 if (SDL_Init SDL_INIT_VIDEO) < 0
  console "Could not initialize SDL!" eol
  SDL_QUIT
  b := false
  return

 screen :> (SDL_SetVideoMode 640 480 8 SDL_SWSURFACE)

 if not (exists screen)
  console "Could not init video!" eol
  SDL_QUIT
  b := false
  return

 tile :> SDL_LoadBMP "astroids.bmp"
 SDL_SetColors screen tile:format:palette:colors 0 tile:format:palette:ncolors


function main
 var SDL_Event event
 var Float angle := 0.0
 if not (init)
  console "Init failed..." eol
  return

 var CBool done := false

 while not done
  while SDL_PollEvent:event > 0
   if event:type = SDL_QUIT
     done := true
   eif event:type = SDL_KEYDOWN
     done := true

  rotate screen tile angle (sin angle)
  SDL_UpdateRect screen 0 0 0 0
  angle += 0.005

 SDL_FreeSurface tile

 SDL_QUIT
 return

main