2 * sdl-scrolling - Example program for scrolling images in SDL
4 * Copyright (C) 2013 Antonio Ospite <ospite@studenti.unina.it>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include <SDL_image.h>
29 static int mod(int a, int b)
32 return (c < 0) ? c + b : c;
35 static SDL_Surface *load_image(const char *filename)
37 SDL_Surface *image = NULL;
38 SDL_Surface *optimized_image = NULL;
40 image = IMG_Load(filename);
42 fprintf(stderr, "IMG_Load: %s\n", IMG_GetError());
46 optimized_image = SDL_DisplayFormat(image);
47 if (!optimized_image) {
48 fprintf(stderr, "erro whan calling SDL_DisplayFormat().\n");
51 SDL_FreeSurface(image);
53 return optimized_image;
56 int main(int argc, char *argv[])
59 SDL_Surface* screen = NULL;
60 SDL_Surface* map = NULL;
61 SDL_Rect viewport = {0 , 0, WIDTH, HEIGHT};
63 SDL_Joystick *joystick = NULL;
69 Sint16 lastframe_limit;
74 fprintf(stderr, "usage: %s <image>\n", argv[0]);
78 SDL_Init(SDL_INIT_TIMER | SDL_INIT_JOYSTICK);
80 screen = SDL_SetVideoMode(WIDTH, HEIGHT, 32, SDL_HWSURFACE);
82 fprintf(stderr, "Cannot set video mode\n");
87 map = load_image(argv[1]);
93 lastframe_limit = (map->h - HEIGHT);
95 if (SDL_NumJoysticks() > 0)
96 joystick = SDL_JoystickOpen(0);
98 SDL_JoystickEventState(SDL_ENABLE);
99 SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
102 time_start = SDL_GetTicks();
104 while(SDL_PollEvent(&event)) {
111 switch(event.key.keysym.sym) {
126 printf("key: '%s' keysym: %d\n",
127 SDL_GetKeyName(event.key.keysym.sym),
128 event.key.keysym.sym);
133 case SDL_JOYAXISMOTION:
134 fprintf(stderr, "Joystick which: %d, axis: %d, value: %d\n",
135 event.jaxis.which, event.jaxis.axis, event.jaxis.value);
136 if (event.jaxis.which == 0) {
137 if (event.jaxis.axis == 0)
138 /* TODO: improve scaling here */
139 y_offset = event.jaxis.value;
145 y = mod(y, lastframe_limit);
148 SDL_BlitSurface(map, &viewport, screen, NULL);
151 time_end = SDL_GetTicks();
152 if (time_end - time_start < 1000 / FPS)
153 SDL_Delay((1000 / FPS) - (time_end - time_start));
158 if (SDL_JoystickOpened(0))
159 SDL_JoystickClose(joystick);
161 SDL_FreeSurface(map);