A stained glass effect in C
Save this code to your computer with an appropriate name (such as glass.c) and download the glass images to go with it. Compile it with something like:
gcc -o glass glass.c -lbr -lm
and enjoy!
#include <stdio.h>
#include <stdlib.h>
#include <SDL/SDL.h>
#include <SDL/SDL_mixer.h>
#include <SDL/SDL_image.h>
#include <brick.h>
/* Compile with: gcc -o glass glass.c -lm -lbr */
/*
* a few configuration options
*/
#define SCREEN_W 256
#define SCREEN_H 180
#define DISPL_W 80
#define DISPL_H 100
int main() {
int i,j;
/* layer vars */
int layer_id;
/* the sprite variables */
struct sprite *glass, *bear;
/* the buffer for loading pngs, and a color key for the bear sprite */
struct color key;
/* a buffer to hold the pixel displacement data for the pane of glass */
short displ[DISPL_H][DISPL_W][2];
/* the bear sprite's position */
int bx, by;
/* a struct to contain inputs */
struct input io;
/* initialize brick and create the layer */
init_brick();
layer_id = layer_add();
layer_set_sorting( layer_id, 1 );
/*
* now, we're going to create the stained glass effect by combining two sprites:
* a color-adjustment sprite to give the glass some color, and a displacement
* sprite to give it the fuzzy, mottled look. first we'll create a
* displacement map for the fuzzy effect, by making a list of small random
* pixel displacement values, which will comprise the displacement sprite.
*/
for( i=0; i < DISPL_H; i++ )
for( j=0; j < DISPL_W; j++ ) {
displ[i][j][0] = (random() & 7) - 3;
displ[i][j][1] = (random() & 7) - 3;
}
/* and load the pane of glass */
glass = sprite_create();
sprite_add_frame(glass, frame_convert( frame_from_disk("window.png", NULL), FRAME_LT, NULL));
sprite_add_subframe(glass, 0, frame_create(FRAME_DISPL, DISPL_W, DISPL_H, displ, NULL));
/* position the sprite and add it to the list */
sprite_set_position(glass, 100, 20);
sprite_set_z_hint(glass, 10);
list_add( layer_get_sprite_list(layer_id), glass);
/*
* and last, load the bear sprite, and set a color key to make
* sure that the magenta background is made transparent
*/
bear = sprite_create();
key.r = 255;
key.g = 0;
key.b = 255;
sprite_add_frame(bear, frame_copy(frame_from_disk("bear.png", &key)));
list_add( layer_get_sprite_list(layer_id), bear);
/* open the graphics display */
graphics_open(GRAPHICS_ACCEL, SCREEN_W, SCREEN_H, 0, 3);
/* initialize the sprite position and enter the main loop */
bx = 0;
by = 0;
for(;;) {
/* read the keyboard/joystick input */
io_fetch(0, &io);
/* update the sprite position */
bx += io.hat[0].horiz;
by += io.hat[0].vert;
sprite_set_position(bear, bx, by);
/* display the frame and run the delay loop */
render_display();
delay(50);
/* quit on escape keypress */
if( io.esc || io_has_quit() )
{
quit_brick();
exit(0);
}
}
}