doc.txt

Allegro Graphics Library

_Allegro Graphics_ Library
===============

By Jon Rafkind (jon at rafkind dot com)

Keywords: _graphics_

Introduction
============

This library is a set of bindings to the Allegro graphics library.
Allegro is typically thought of as a game library, implementing all the
useful features a game is composed of: graphics, sound, and keyboard/mouse input.
The underlying Allegro library comes with this package so there is no need to
install Allegro by hand. On Unix systems Allegro is built from source, so that
phase could potentially fail if you do not have the proper libraries installed.

For more on Allegro, see the following websites:
http://alleg.sf.net
http://www.allegro.cc/manual/

For immediate gratification see the examples chapter at the end.

Each "feature" is split into its own module:
Graphics:
   (require (planet "image.ss" ("kazzmir" "allegro.plt" 1 1)))

Keyboard:
   (require (planet "keyboard.ss" ("kazzmir" "allegro.plt" 1 1)))

Mouse:
   (require (planet "mouse.ss" ("kazzmir" "allegro.plt" 1 1)))

Sound:
   (require (planet "sound.ss" ("kazzmir" "allegro.plt" 1 1)))

Utilities:
   (require (planet "util.ss" ("kazzmir" "allegro.plt" 1 1)))

Most of these modules export common function names so its usually best to
import them with a prefix, i.e:

   (require (prefix keyboard- (planet "keyboard.ss" ("kazzmir" "allegro.plt" 1
   1))))

Using any of the Allegro subsystems require that Allegro be set up properly.
The utilities module is just for that purpose.

_Utilies_
=========

> (easy-init width height depth [mode]) -> void

Set up the Allegro system. This function creates a graphics context, installs
the keyboard, the mouse, and sound.

  width - Width of the graphics window
  height - Height of the graphics window
  depth - Bits per pixel, otherwise known as color depth
  mode - Optional argument that defines whether to use fullscreen or windowed.
  The default is windowed mode.

  Typical width/height pairs are:
  320 240
  640 480
  800 600
  1024 768
  1280 960

  Typical color depths are:
  8
  15
  16
  24
  32

  Possible modes are:
  'TEXT - Destroys the graphics window if it exists
  'AUTO - Let Allegro choose the proper graphics mode
  'FULLSCREEN - Fullscreen mode
  'WINDOWED - Windowed mode
  'SAFE - Allegro will choose a graphics mode. This mode may ignore the
  width, height and color depths but will almost always set some graphics
  mode.

  A typical use of this function is:
  (easy-init 640 480 16)

> (easy-exit) -> void

Shuts down the Allegro system. Call this method at the end of your program.

> (game-loop logic-func draw-func delay) -> void

This method implements the de-facto game loop. In short the logic-func will
update the environment after `delay' amount of time has passed. After the
logic-func is run, the draw-func is run which will display the environment
onto the graphics context.

  logic-func :: (lambda () body)
  If logic-func returns #f, game-loop will exit.

  draw-func :: (lambda (buffer) body)
  buffer is an image, as defined in image.ss, and is used as a double buffer
  to make drawing graphics look smooth. Buffer is not the screen, but rather a
  section of memory that you are free to do as you wish with. The game-loop
  will copy buffer to the screen immediately following this function.
  *WARNING* If you use game-loop you *must* draw to the buffer and not to the
  screen. If you draw to the screen in the draw-func your image will flicker.

  delay :: int
  Amount of time to wait in between logic updates. If there is enough time,
  sleep will be called so that cpu cycles are not wasted. You can play with
  this number until you feel comfortable or you can use frames-per-second to
  calculate a reasonable time.

Example:

;; keep drawing a red circle at 50,50 until ESC is pressed
(game-loop
  (lambda ()
    (keypressed? 'ESC))
  (lambda (buffer)
    (circle buffer 50 50 5 (color 255 0 0))))

> (frames-per-second frames) -> int

Calculate an amount of time to delay between logic cycles in game-loop. This
function does exactly what it sounds like: (frames-per-second 30) will run 30
logic/draw cycles per second.

> (blend-palette start-color end-color num-colors) -> list of color

Returns a list of colors that can be used as pixel values. The colors are
calculated by interpolating the individual pixel components( red, green, blue
) from start color to end color. This is an easy way to make a color gradient.
Example:
(blend-palette (color 0 0 0) (color 255 255 255) 10)

Would be a list of colors starting with black and progressivly lighter shades
of grey until the last color white.

Blenders. All parameters( such as red, green, blue ) to all blenders are in
the range [0,255]. Most of the blender documentation was copy/pasted out of
the allegro manual so anything that looks strange probably is.

> (set-trans-blender! red green blue alpha) -> void

Enables a linear interpolator blender mode for combining translucent or lit truecolor pixels.

> (set-alpha-blender!)

Enables the special alpha-channel blending mode, which is used for drawing
32-bit RGBA sprites. After calling this function, you can use
draw_trans_sprite() or draw_trans_rle_sprite() to draw a 32-bit source image
onto any hicolor or truecolor destination. The alpha values will be taken
directly from the source graphic, so you can vary the solidity of each part
of the image. You can't use any of the normal translucency functions while
this mode is active, though, so you should reset to one of the normal blender
modes (eg. set_trans_blender()) before drawing anything other than 32-bit
RGBA sprites.

> (set-write-alpha-blender!)

Enables the special alpha-channel editing mode, which is used for drawing alpha
channels over the top of an existing 32-bit RGB sprite, to turn it into an RGBA 
format image. After calling this function, you can set the drawing mode to
DRAW_MODE_TRANS and then write draw color values (0-255) onto a 32-bit image.
This will leave the color values unchanged, but alter the alpha to whatever
values you are writing. After enabling this mode you can also use
draw_trans_sprite() to superimpose an 8-bit alpha mask over the top of an
existing 32-bit sprite.

> (set-add-blender! red green blue alpha)

Enables an additive blender mode for combining translucent or lit truecolor pixels.

> (set-burn-blender! red green blue alpha)

Enables a burn blender mode for combining translucent or lit truecolor pixels.
Here the lightness values of the colours of the source image reduce the
lightness of the destination image, darkening the image.

> (set-color-blender! red geen blue alpha)

Enables a color blender mode for combining translucent or lit truecolor pixels.
Applies only the hue and saturation of the source image to the destination
image. The luminance of the destination image is not affected.

> (set-difference-blender! red green blue alpha)

Enables a difference blender mode for combining translucent or lit truecolor
pixels. This makes an image which has colours calculated by the difference
between the source and destination colours.

> (set-dissolve-blender! red green blue alpha)

Enables a dissolve blender mode for combining translucent or lit truecolor
pixels. Randomly replaces the colours of some pixels in the destination image
with those of the source image. The number of pixels replaced depends on the
alpha value (higher value, more pixels replaced; you get the idea :).

> (set-dodge-blender! red green blue alpha)

Enables a dodge blender mode for combining translucent or lit truecolor pixels.
The lightness of colours in the source lighten the colours of the destination.
White has the most effect; black has none.

> (set-hue-blender! red green blue alpha)

Enables a hue blender mode for combining translucent or lit truecolor pixels.
This applies the hue of the source to the destination.

> (set-invert-blender! red green blue alpha)

Enables an invert blender mode for combining translucent or lit truecolor
pixels. Blends the inverse (or negative) colour of the source with the
destination.

> (set-luminance-blender! red green blue alpha)

Enables a luminance blender mode for combining translucent or lit truecolor
pixels. Applies the luminance of the source to the destination.  The colour
of the destination is not affected.

> (set-multiply-blender! red green blue alpha)

Enables a multiply blender mode for combining translucent or lit truecolor
pixels. Combines the source and destination images, multiplying the colours to
produce a darker colour. If a colour is multiplied by white it remains
unchanged; when multiplied by black it also becomes black.

> (set-saturation-blender red green blue alpha)

Enables a saturation blender mode for combining translucent or lit truecolor
pixels. Applies the saturation of the source to the destination image.

> (set-screen-blender red green blue alpha)

Enables a screen blender mode for combining translucent or lit truecolor
pixels. This blender mode lightens the colour of the destination image by
multiplying the inverse of the source and destination colours. Sort of like
the opposite of the multiply blender mode.

> (allegro-init) -> int

Initializes the Allegro system. Most of the time you can just call
(easy-init).

> (allegro-exit) -> void

Shuts down Allegro. Call this at the end of your program. Most of the time you
can just call (easy-exit).

_Graphics_
==========

> (screen) -> image

Predefined image that represents the graphics context currently open. All the
functions defined below also have a corresponding -screen function which
operates directly on this variable. For example:

(line (screen) 5 5 10 10 (color 64 0 0)) ;; Draws on the screen
(line-screen 5 5 10 10 (color 64 0 0)) ;; Does the same thing

(copy (screen) my-image) ;; Copy a buffer onto the screen
(copy-screen my-image) ;; Same thing

> (create width height [depth]) -> image

Create a graphics buffer in memory with the dimensions provided.
  width - Width of buffer. Should be > 0
  height - Height of buffer. Should be > 0
  depth - Optional color depth. Defaults to the current color depth of the
  screen. Possible depths:
  8
  15
  16
  24
  32

If there is not enough available memory width/height #f will be returned.

> (create-from-file filename) -> image

Load `filename' and copy it into a graphics buffer. This buffer is safe to
draw on. Allegro will guess at the filetype and can be one of the following:
  .bmp
  .pcx
  .lbm
  .tga
  .png

Extensions to support .jpg exist for Allegro and will be added to
this module at some point.

> (color red green blue) -> int

Creates a color that can be used with all Allegro functions. The
representation of the color will vary depending on the current color depth.
  0 <= red <= 255
  0 <= green <= 255
  0 <= blue <= 255

In all truecolor modes( 15, 16, 24, 32 ) the following hold:
(color 0 0 0) = black
(color 255 255 255) = white
(color 255 0 255) = magic pink, the masking color

> (mask-color) -> int

The masking color for the current color depth. This is equivalent to (color
255 0 255) but is provided for your convienence.

> (line image x1 y1 x2 y2 color) -> void

Draw a line from x1,y1 to x2,y2 on image using `color'. Pixels outside the
image will not be drawn so its safe to give coordinates outside the
dimensions of the image.

> (fastline image x1 y1 x2 y2 color) -> void

Like (line) except the line is clipped to fit the image before its drawn.
For lines that have coordinates outside the image boundaries this is extremely
fast but be warned that the clipping from (fastline) will not be the same as
the clipping that results from a normal (line); the starting pixel may differ
by a single pixel position occasionally.

> (arc image x y angle1 angle2 radius color) -> void

Draw an arc around x y from angle1 to angle2 with radius. Angles should be in
the range of 0 - 255. 0 = 0 degrees and 255 = 360 degrees.

> (circle image x y radius color) -> void

Draw a hollow circle onto image at x,y with radius

> (circle-fill image x y radius color) -> void

Draw a filled circle onto image at x,y with radius

> (ellipse image x y radius-x radius-y color) -> void

Draw a hollow ellipse at x,y with an x radius of radius-x and a y radius of radius-y
in the specified color.

> (ellipse-fill image x y radius-x radius-y color) -> void

Same as ellipse but the shape will be filled.

> (rectangle image x1 y1 x2 y2 color) -> void

Draw a hollow rectangle onto image from x1, y1 to x2, y2. x1,y1 should be the
opposite corner from x2,y2 but there is no restriction on which pair of points
is which corner.

> (rectangle-fill image x1 y1 x2 y2 color) -> void

Same as rectangle but the shape will be filled.

> (putpixel image x y color) -> void

Draw a single pixel onto image at x,y

> (getpixel image x y) -> color :: int

Read a pixel from an image. The value returned can be used in all situations
that (color) can be used.

(putpixel image 5 5 (color 64 0 0))
(eq? (color 64 0 0) (getpixel image 5 5))

Would be #t

> (print image x y color background-color message) -> void

Print some text onto image starting at x, y. color is the foreground color
while background-color is for the background. If background-color is -1 the
message will be printed without obscuring the background its printed on.

> (clear image [color]) -> void

Set every pixel in the image to a color. color defaults to black, (color 0 0
0).

> (copy image1 image2 [x y] [width height] [dest-x dest-y])

Copy every pixel from image2 onto image1. x,y specify the upper left corner of
image2 to copy to and both default to 0. width, height is the width and height
of the source image and defaults to the width and height of image2. dest-x and
dest-y is the upper left corner of image1 to copy to and defaults to 0,0.


> (copy-masked image1 image2 [x y] [width height] [dest-x dest-y])

Exactly like (copy) except masked pixels are skipped.

> (copy-stretch image1 image2 source-x source-y source-width source-height dest-x dest-y dest-width dest-height)

Like (copy) except image2 is stretched onto image1. The rectangle from image2
spanning from the upper left corner (source-x,source-y) to the lower right
corner (source-x + source-width, source-y + source-height) is copied and
stretched onto image1 at (dest-x,dest-y) with dimensions dest-width and
dest-height.

> (copy-masked-stretch image1 image2 source-x source-y source-width source-height dest-x dest-y dest-width dest-height)

Like (copy-stretch) except masked pixels are skipped.

> (draw image1 image2 x y)

Draw image2( the sprite ) onto image1. This is almost the same as (copy)
except masking pixels will be not be copied leaving whatever was on image1 in
place at the location of the masking pixel. The masking pixel is "magic pink"
and is always equivalent to (color 255 0 255). All draw-* methods work in
adhere to this functionality in addition to whatever else they are supposed to
do.


> (draw-gouraud image1 image2 x y color1 color2 color3 color4)

Draws image2 onto image1 with colored corners. color1 = upper left corner.
color2 = upper right. color3 = lower left. color4 = lower right.

> (draw-character image1 image2 x y color background)

Draws image2 onto image1 at the specified position, drawing transparent pixels in the background color (or skipping them if the background color is -1) and setting all other pixels to the specified color. Transparent pixels are marked by a zero in 256-color modes or bright pink for truecolor data (maximum red and blue, zero green). The sprite must be an 8-bit image, even if the destination is a truecolor bitmap. Example:

;; draw the logo as a red silhouette
(draw-character (screen) logo 50 50 (color 255 0 0) -1)

> (draw-lit image1 image2 x y alpha)

Draw image2 onto image1 at x,y with a lighting level of alpha. The lighting
colors need to be preset with (set-trans-blender!).

> (draw-trans image1 image2 x y alpha)

Draw image2 onto image1 at x, y with a translucency level of alpha. The
translucency colors need to be preset with (set-trans-blender!)

> (draw-horizontal-flip image1 image2 x y)

Like draw but flips the image over the vertical axis between x0 and x1 where
x0 is the left side of the image and x1 is the right side.

> (draw-vertical-flip image1 image2 x y)

Like draw but flips the image over the horizontal axis bewteen y0 and y1 where
y0 is the upper side of the image and y1 is the lower side.

> (draw-vertical-horizontal-flip image1 image2 x y)

draw-horizontal-flip and draw-vertical-flip simeltaneously

> (draw-pivot image1 image2 x y center-x center-y angle)

Draws image2 onto image1 at x,y rotated around center-x and center-y. x,y
correspond to coordinates on image1 whereas center-x, center-y correspond to
coordinates on image2. Angle defines how much to rotate the sprite. Angle
should be between 0 and 255 where 0 = 0 degrees and 255 = 360 degrees.

Here is a full listing of all functions provided by image.ss:

arc
circle
circle-fill
clear
collide-equad?
color
copy
copy-masked
copy-masked-screen
copy-masked-stretch
copy-screen
copy-stretch
create
create-from-file
create-sub
destroy
display-ebox
draw
draw-character
draw-gouraud
draw-horizontal-flip
draw-lit
draw-pivot
draw-pivot-scaled
draw-pivot-scaled-vertical-flip
draw-pivot-vertical-flip
draw-rotate
draw-rotate-scaled
draw-rotate-scaled-vertical-flip
draw-rotate-vertical-flip
draw-stretched
draw-trans
draw-vertical-flip
draw-vertical-horizontal-flip
ebox-collide?
ellipse
ellipse-fill
fastline
floodfill
get-rgb
getpixel
line
make-ebox-from-image
make-v3d
mask-color
polygon
polygon3d
print-center
putpixel
quad3d
rectangle
rectangle-fill
save
screen
spline
triangle
triangle3d
unwrite-line
write-line

_Keyboard_
==========

> (keypressed? key) -> boolean

Returns true if the key is being pressed on the keyboard. Available keys are:
    'A 'B 'C 'D 'E 'F 'G 'H 'I 'J 'K
    'L 'M 'N 'O 'P 'Q 'R 'S 'T 'U
    'V 'W 'X 'Y 'Z 'NUM-0 'NUM-1 'NUM-2 'NUM-3 'NUM-4
    'NUM-5 'NUM-6 'NUM-7 'NUM-8 'NUM-9 'PAD-0 'PAD-1 'PAD-2
    'PAD-3 'PAD-4 'PAD-5 'PAD-6 'PAD-7 'PAD-8
    'PAD-9 'F1 'F2 'F3 'F4 'F5 'F6 'F7
    'F8 'F9 'F10 'F11 'F12 'ESC 'TILDE
    'MINUS 'EQUALS 'BACKSPACE 'TAB 'OPENBRACE
    'CLOSEBRACE 'ENTER 'COLON 'QUOTE 'BACKSLASH
    'BACKSLASH2 'COMMA 'STOP 'SLASH 'SPACE 'INSERT
    'DEL 'HOME 'END 'PGUP 'PGDN 'LEFT 'RIGHT
    'UP 'DOWN 'SLASH_PAD 'ASTERISK 'MINUS_PAD
    'PLUS_PAD 'DEL_PAD 'ENTER_PAD 'PRTSCR 'PAUSE
    'ABNT_C1 'YEN 'KANA 'CONVERT 'NOCONVERT 'AT
    'CIRCUMFLEX 'COLON2 'KANJI
    'EQUALS_PAD  ;; MacOS X
    'BACKQUOTE  ;; MacOS X
    'SEMICOLON  ;; MacOS X
    'COMMAND  ;; MacOS X
    'UNKNOWN1
    'UNKNOWN2
    'UNKNOWN3
    'UNKNOWN4
    'UNKNOWN5
    'UNKNOWN6
    'UNKNOWN7
    'UNKNOWN8
    'MODIFIERS
    'LSHIFT
    'RSHIFT
    'LCONTROL
    'RCONTROL
    'ALT
    'ALTGR
    'LWIN
    'RWIN
    'MENU
    'SCRLOCK
    'NUMLOCK
    'CAPSLOCK

> (readkey) -> symbol

Waits for a key to be pressed and when one is returns one of the above
symbols.

> (key-modifiers) -> list of symbol

Returns a list of the currently pressed modifiers:
   'shift
   'ctrl    
   'alt     
   'lwin    
   'rwin    
   'menu    
   'command 
   'scrolock
   'numlock 
   'capslock
   'inaltseq
   'accent1 
   'accent2 
   'accent3 
   'accent4

> (simulate-keypress) -> void

Puts a key into the key event buffer so that the next call to (readkey) will
return this value. i.e:

(simulate-keypress 'T)
(eq? 'T (readkey))

Would be #t.

> (any-keypressed?) -> boolean

Returns #t if any key on the keyboard is pressed and #f if not.

> (clear-keyboard) -> void

Clears all keys from the keyboard buffer so that (readkey) would wait for a
keypress.

_Mouse_
=======

> (left-click?) -> boolean

Returns #t if the left button on the mouse was clicked, false otherwise.

> (right-click?) -> boolean

Returns #t if the right button on the mouse was clicked, false otherwise.

> (x) -> int

Returns the current x position of the mouse on the graphics context.

> (y) -> int

Returns the current y position of the mouse on the graphics context.

> (get-mickeys) -> (values x y)

Returns pair of values, x/y, that represent how far the mouse has just moved.

_Sound_
=======

> (load-sound filename) -> sound

Create a sound object from a filename. Available extensions for filenames are
  .wav
  .voc

> (play-sound sound [volume] [pan] [frequency]) -> void

Plays a sound.
  sound - sound object
  volume - 0 <= volume <= 255
  pan - 0 <= pan <= 255. Pan determines which speaker the sound will come out
  of. 0 is left, 255 is right. 128 is in the middle.
  frequency - What speed to play the sound at. 1000 is normal, less is slower,
  and more is faster.

> (play-sound-looped sound [volume] [pan] [frequency]) -> void

Exactly like play-sound except the sound will play forever.

> (stop-sound sound) -> void

Stop playing a sound. No effect if the sound is not already playing.

_Examples_
==========

Some examples that demonstrate some of what Allegro can do are listed below.
All examples export a single 'run' method that you can invoke.

;; Demo of sound and using the mouse
(require (planet "piano.ss" ("kazzmir" "allegro.plt" 1 2) "examples"))

;; Show Allegros ability to blend images together
(require (planet "exblend.ss" ("kazzmir" "allegro.plt" 1 2) "examples"))

;; Hello world
(require (planet "exhello.ss" ("kazzmir" "allegro.plt" 1 2) "examples"))

;; 3d bouncing boxes in various rendering modes
(require (planet "ex3d.ss" ("kazzmir" "allegro.plt" 1 2) "examples"))

;; 3d simulation of flying through a wormhole, non-interactive 
(require (planet "wormhole.ss" ("kazzmir" "allegro.plt" 1 2) "examples"))

;; A game wherein you must collect the white diamonds and escape through the
;; red portal. Left click to shoot
(require (planet "xquest.ss" ("kazzmir" "allegro.plt" 1 2) "examples/xquest"))

After requiring any of the above, invoke:
(run)

_Step by step_
==============

The following is a short tutorial on using Allegro. At each step I will add
some code and explain what it does.

1. Set up Allegro and quit. Pretty self explanatory.

;; this require will be used throughout
(require (planet "util.ss" ("kazzmir" "allegro.plt" 1 1)))
(require (planet "keyboard.ss" ("kazzmir" "allegro.plt" 1 1)))
(require (prefix image- (planet "image.ss" ("kazzmir" "allegro.plt" 1 1))))
(require (prefix mouse- (planet "mouse.ss" ("kazzmir" "allegro.plt" 1 1))))

(define (run)
  (easy-init 640 480 16) ;; set up Allegro. Use 640x480 for window demensions
  and 16 bits per pixel
  (easy-exit)) ;; Just quit Allegro

2. Print hello world to the screen and quit when ESC is pressed.

(define (run)
  (easy-init 640 480 16)
  (game-loop
     (lambda ()
        (keypressed? 'ESC))
     (lambda (buffer)
        (image-print buffer 50 50 (image-color 255 255 255) -1 "Hello world"))
     (frames-per-second 30))
  (easy-exit))

3. Print hello world wherever the mouse is.

(define (run)
  (easy-init 640 480 16)
  (game-loop
     (lambda ()
        (keypressed? 'ESC))
     (lambda (buffer)
        (let ((x (mouse-x))
	      (y (mouse-y)))
	 (image-print buffer x y (image-color 255 255 255) -1 "Hello world")))
     (frames-per-second 30))
  (easy-exit))

4. Load a bitmap and show it where the mouse is.

(define (run)
  (easy-init 640 480 16)
  (let ((my-image (image-create-from-file "myimage.bmp")))
    (game-loop
      (lambda ()
        (keypressed? 'ESC))
      (lambda (buffer)
        (let ((x (mouse-x))
	      (y (mouse-y)))
	 (image-copy buffer my-image x y)))
     (frames-per-second 30))
  (easy-exit))

_FAQ_
=====

Q. Where and how do I get the Allegro library itself to install?
A. You dont need to install Allegro, it comes with the planet package.

Q. Where is the OSX support?
Allegro needs to run in the main thread on OSX so if you start mzscheme and
load Allegro later things dont work. At this point I dont have a solution, any
advice is appreciated.

_ChangeLog_
===========

1.3 - 7/31/2006

* Added blender routines
* Added more keyboard support: simulate-keypress and readkey.
* Documented more functions

1.2 - 7/16/2006

* Added png support

1.1 - 7/8/2006

* When the window loses focus in Windows, run the program in the background
* Provided more drawing functions

1.0 - 6/26/2006

* Initial release. Some functionality provided, drawing, keyboard, mouse.