Add non-animated SSSE3 blitter
[openttd/fttd.git] / src / video / allegro_v.cpp
blobf844c6d0d0e3f654fdc3c2ff8fdba25346ad53e3
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /**
11 * @file allegro_v.cpp Implementation of the Allegro video driver.
12 * @note Implementing threaded pushing of data to the display is
13 * not faster (it's a few percent slower) in contrast to the
14 * results gained with threading it for SDL.
17 #ifdef WITH_ALLEGRO
19 #include "../stdafx.h"
20 #include "../openttd.h"
21 #include "../gfx_func.h"
22 #include "../rev.h"
23 #include "../blitter/factory.hpp"
24 #include "../network/network.h"
25 #include "../core/random_func.hpp"
26 #include "../core/math_func.hpp"
27 #include "allegro_v.h"
28 #include <allegro.h>
30 #ifdef _DEBUG
31 /* Allegro replaces SEGV/ABRT signals meaning that the debugger will never
32 * be triggered, so rereplace the signals and make the debugger useful. */
33 #include <signal.h>
34 #endif
36 static FVideoDriver_Allegro iFVideoDriver_Allegro;
38 static BITMAP *_allegro_screen;
40 #define MAX_DIRTY_RECTS 100
41 static PointDimension _dirty_rects[MAX_DIRTY_RECTS];
42 static int _num_dirty_rects;
44 void VideoDriver_Allegro::MakeDirty(int left, int top, int width, int height)
46 if (_num_dirty_rects < MAX_DIRTY_RECTS) {
47 _dirty_rects[_num_dirty_rects].x = left;
48 _dirty_rects[_num_dirty_rects].y = top;
49 _dirty_rects[_num_dirty_rects].width = width;
50 _dirty_rects[_num_dirty_rects].height = height;
52 _num_dirty_rects++;
55 static void DrawSurfaceToScreen()
57 int n = _num_dirty_rects;
58 if (n == 0) return;
60 _num_dirty_rects = 0;
61 if (n > MAX_DIRTY_RECTS) {
62 blit(_allegro_screen, screen, 0, 0, 0, 0, _allegro_screen->w, _allegro_screen->h);
63 return;
66 for (int i = 0; i < n; i++) {
67 blit(_allegro_screen, screen, _dirty_rects[i].x, _dirty_rects[i].y, _dirty_rects[i].x, _dirty_rects[i].y, _dirty_rects[i].width, _dirty_rects[i].height);
72 static void UpdatePalette(uint start, uint count)
74 static PALETTE pal;
76 uint end = start + count;
77 for (uint i = start; i != end; i++) {
78 pal[i].r = _cur_palette.palette[i].r / 4;
79 pal[i].g = _cur_palette.palette[i].g / 4;
80 pal[i].b = _cur_palette.palette[i].b / 4;
81 pal[i].filler = 0;
84 set_palette_range(pal, start, end - 1, 1);
87 static void InitPalette()
89 UpdatePalette(0, 256);
92 static void CheckPaletteAnim()
94 if (_cur_palette.count_dirty != 0) {
95 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
97 switch (blitter->UsePaletteAnimation()) {
98 case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
99 UpdatePalette(_cur_palette.first_dirty, _cur_palette.count_dirty);
100 break;
102 case Blitter::PALETTE_ANIMATION_BLITTER:
103 blitter->PaletteAnimate(_cur_palette);
104 break;
106 case Blitter::PALETTE_ANIMATION_NONE:
107 break;
109 default:
110 NOT_REACHED();
112 _cur_palette.count_dirty = 0;
116 static const Dimension default_resolutions[] = {
117 { 640, 480},
118 { 800, 600},
119 {1024, 768},
120 {1152, 864},
121 {1280, 800},
122 {1280, 960},
123 {1280, 1024},
124 {1400, 1050},
125 {1600, 1200},
126 {1680, 1050},
127 {1920, 1200}
130 static void GetVideoModes()
132 /* Need to set a gfx_mode as there is NO other way to autodetect for
133 * cards ourselves... and we need a card to get the modes. */
134 set_gfx_mode(_fullscreen ? GFX_AUTODETECT_FULLSCREEN : GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0);
136 GFX_MODE_LIST *mode_list = get_gfx_mode_list(gfx_driver->id);
137 if (mode_list == NULL) {
138 memcpy(_resolutions, default_resolutions, sizeof(default_resolutions));
139 _num_resolutions = lengthof(default_resolutions);
140 return;
143 GFX_MODE *modes = mode_list->mode;
145 int n = 0;
146 for (int i = 0; modes[i].bpp != 0; i++) {
147 uint w = modes[i].width;
148 uint h = modes[i].height;
149 if (w >= 640 && h >= 480) {
150 int j;
151 for (j = 0; j < n; j++) {
152 if (_resolutions[j].width == w && _resolutions[j].height == h) break;
155 if (j == n) {
156 _resolutions[j].width = w;
157 _resolutions[j].height = h;
158 if (++n == lengthof(_resolutions)) break;
162 _num_resolutions = n;
163 SortResolutions(_num_resolutions);
165 destroy_gfx_mode_list(mode_list);
168 static void GetAvailableVideoMode(uint *w, uint *h)
170 /* No video modes, so just try it and see where it ends */
171 if (_num_resolutions == 0) return;
173 /* is the wanted mode among the available modes? */
174 for (int i = 0; i != _num_resolutions; i++) {
175 if (*w == _resolutions[i].width && *h == _resolutions[i].height) return;
178 /* use the closest possible resolution */
179 int best = 0;
180 uint delta = Delta(_resolutions[0].width, *w) * Delta(_resolutions[0].height, *h);
181 for (int i = 1; i != _num_resolutions; ++i) {
182 uint newdelta = Delta(_resolutions[i].width, *w) * Delta(_resolutions[i].height, *h);
183 if (newdelta < delta) {
184 best = i;
185 delta = newdelta;
188 *w = _resolutions[best].width;
189 *h = _resolutions[best].height;
192 static bool CreateMainSurface(uint w, uint h)
194 int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
195 if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");
196 set_color_depth(bpp);
198 GetAvailableVideoMode(&w, &h);
199 if (set_gfx_mode(_fullscreen ? GFX_AUTODETECT_FULLSCREEN : GFX_AUTODETECT_WINDOWED, w, h, 0, 0) != 0) {
200 DEBUG(driver, 0, "Allegro: Couldn't allocate a window to draw on '%s'", allegro_error);
201 return false;
204 /* The size of the screen might be bigger than the part we can actually draw on!
205 * So calculate the size based on the top, bottom, left and right */
206 _allegro_screen = create_bitmap_ex(bpp, screen->cr - screen->cl, screen->cb - screen->ct);
207 _screen.width = _allegro_screen->w;
208 _screen.height = _allegro_screen->h;
209 _screen.pitch = ((byte*)screen->line[1] - (byte*)screen->line[0]) / (bpp / 8);
210 _screen.dst_ptr = _allegro_screen->line[0];
212 /* Initialise the screen so we don't blit garbage to the screen */
213 memset(_screen.dst_ptr, 0, _screen.height * _screen.pitch);
215 /* Set the mouse at the place where we expect it */
216 poll_mouse();
217 _cursor.pos.x = mouse_x;
218 _cursor.pos.y = mouse_y;
220 BlitterFactory::GetCurrentBlitter()->PostResize();
222 InitPalette();
224 char caption[32];
225 snprintf(caption, sizeof(caption), "OpenTTD %s", _openttd_revision);
226 set_window_title(caption);
228 enable_hardware_cursor();
229 select_mouse_cursor(MOUSE_CURSOR_ARROW);
230 show_mouse(_allegro_screen);
232 GameSizeChanged();
234 return true;
237 bool VideoDriver_Allegro::ClaimMousePointer()
239 select_mouse_cursor(MOUSE_CURSOR_NONE);
240 show_mouse(NULL);
241 disable_hardware_cursor();
242 return true;
245 struct VkMapping {
246 uint16 vk_from;
247 byte vk_count;
248 byte map_to;
251 #define AS(x, z) {x, 0, z}
252 #define AM(x, y, z, w) {x, y - x, z}
254 static const VkMapping _vk_mapping[] = {
255 /* Pageup stuff + up/down */
256 AM(KEY_PGUP, KEY_PGDN, WKC_PAGEUP, WKC_PAGEDOWN),
257 AS(KEY_UP, WKC_UP),
258 AS(KEY_DOWN, WKC_DOWN),
259 AS(KEY_LEFT, WKC_LEFT),
260 AS(KEY_RIGHT, WKC_RIGHT),
262 AS(KEY_HOME, WKC_HOME),
263 AS(KEY_END, WKC_END),
265 AS(KEY_INSERT, WKC_INSERT),
266 AS(KEY_DEL, WKC_DELETE),
268 /* Map letters & digits */
269 AM(KEY_A, KEY_Z, 'A', 'Z'),
270 AM(KEY_0, KEY_9, '0', '9'),
272 AS(KEY_ESC, WKC_ESC),
273 AS(KEY_PAUSE, WKC_PAUSE),
274 AS(KEY_BACKSPACE, WKC_BACKSPACE),
276 AS(KEY_SPACE, WKC_SPACE),
277 AS(KEY_ENTER, WKC_RETURN),
278 AS(KEY_TAB, WKC_TAB),
280 /* Function keys */
281 AM(KEY_F1, KEY_F12, WKC_F1, WKC_F12),
283 /* Numeric part. */
284 AM(KEY_0_PAD, KEY_9_PAD, '0', '9'),
285 AS(KEY_SLASH_PAD, WKC_NUM_DIV),
286 AS(KEY_ASTERISK, WKC_NUM_MUL),
287 AS(KEY_MINUS_PAD, WKC_NUM_MINUS),
288 AS(KEY_PLUS_PAD, WKC_NUM_PLUS),
289 AS(KEY_ENTER_PAD, WKC_NUM_ENTER),
290 AS(KEY_DEL_PAD, WKC_DELETE),
292 /* Other non-letter keys */
293 AS(KEY_SLASH, WKC_SLASH),
294 AS(KEY_SEMICOLON, WKC_SEMICOLON),
295 AS(KEY_EQUALS, WKC_EQUALS),
296 AS(KEY_OPENBRACE, WKC_L_BRACKET),
297 AS(KEY_BACKSLASH, WKC_BACKSLASH),
298 AS(KEY_CLOSEBRACE, WKC_R_BRACKET),
300 AS(KEY_QUOTE, WKC_SINGLEQUOTE),
301 AS(KEY_COMMA, WKC_COMMA),
302 AS(KEY_MINUS, WKC_MINUS),
303 AS(KEY_STOP, WKC_PERIOD),
304 AS(KEY_TILDE, WKC_BACKQUOTE),
307 static uint32 ConvertAllegroKeyIntoMy(WChar *character)
309 int scancode;
310 int unicode = ureadkey(&scancode);
312 const VkMapping *map;
313 uint key = 0;
315 for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
316 if ((uint)(scancode - map->vk_from) <= map->vk_count) {
317 key = scancode - map->vk_from + map->map_to;
318 break;
322 if (key_shifts & KB_SHIFT_FLAG) key |= WKC_SHIFT;
323 if (key_shifts & KB_CTRL_FLAG) key |= WKC_CTRL;
324 if (key_shifts & KB_ALT_FLAG) key |= WKC_ALT;
325 #if 0
326 DEBUG(driver, 0, "Scancode character pressed %u", scancode);
327 DEBUG(driver, 0, "Unicode character pressed %u", unicode);
328 #endif
330 *character = unicode;
331 return key;
334 static const uint LEFT_BUTTON = 0;
335 static const uint RIGHT_BUTTON = 1;
337 static void PollEvent()
339 poll_mouse();
341 bool mouse_action = false;
343 /* Mouse buttons */
344 static int prev_button_state;
345 if (prev_button_state != mouse_b) {
346 uint diff = prev_button_state ^ mouse_b;
347 while (diff != 0) {
348 uint button = FindFirstBit(diff);
349 ClrBit(diff, button);
350 if (HasBit(mouse_b, button)) {
351 /* Pressed mouse button */
352 if (_rightclick_emulate && (key_shifts & KB_CTRL_FLAG)) {
353 button = RIGHT_BUTTON;
354 ClrBit(diff, RIGHT_BUTTON);
356 switch (button) {
357 case LEFT_BUTTON:
358 _left_button_down = true;
359 break;
361 case RIGHT_BUTTON:
362 _right_button_down = true;
363 _right_button_clicked = true;
364 break;
366 default:
367 /* ignore rest */
368 break;
370 } else {
371 /* Released mouse button */
372 if (_rightclick_emulate) {
373 _right_button_down = false;
374 _left_button_down = false;
375 _left_button_clicked = false;
376 } else if (button == LEFT_BUTTON) {
377 _left_button_down = false;
378 _left_button_clicked = false;
379 } else if (button == RIGHT_BUTTON) {
380 _right_button_down = false;
384 prev_button_state = mouse_b;
385 mouse_action = true;
388 /* Mouse movement */
389 int dx = mouse_x - _cursor.pos.x;
390 int dy = mouse_y - _cursor.pos.y;
391 if (dx != 0 || dy != 0) {
392 if (_cursor.fix_at) {
393 _cursor.delta.x = dx;
394 _cursor.delta.y = dy;
395 position_mouse(_cursor.pos.x, _cursor.pos.y);
396 } else {
397 _cursor.delta.x = dx;
398 _cursor.delta.y = dy;
399 _cursor.pos.x = mouse_x;
400 _cursor.pos.y = mouse_y;
401 _cursor.dirty = true;
403 mouse_action = true;
406 static int prev_mouse_z = 0;
407 if (prev_mouse_z != mouse_z) {
408 _cursor.wheel = (prev_mouse_z - mouse_z) < 0 ? -1 : 1;
409 prev_mouse_z = mouse_z;
410 mouse_action = true;
413 if (mouse_action) HandleMouseEvents();
415 poll_keyboard();
416 if ((key_shifts & KB_ALT_FLAG) && (key[KEY_ENTER] || key[KEY_F])) {
417 ToggleFullScreen(!_fullscreen);
418 } else if (keypressed()) {
419 WChar character;
420 uint keycode = ConvertAllegroKeyIntoMy(&character);
421 HandleKeypress(keycode, character);
426 * There are multiple modules that might be using Allegro and
427 * Allegro can only be initiated once.
429 int _allegro_instance_count = 0;
431 const char *VideoDriver_Allegro::Start(const char * const *parm)
433 if (_allegro_instance_count == 0 && install_allegro(SYSTEM_AUTODETECT, &errno, NULL)) {
434 DEBUG(driver, 0, "allegro: install_allegro failed '%s'", allegro_error);
435 return "Failed to set up Allegro";
437 _allegro_instance_count++;
439 install_timer();
440 install_mouse();
441 install_keyboard();
443 #if defined _DEBUG
444 /* Allegro replaces SEGV/ABRT signals meaning that the debugger will never
445 * be triggered, so rereplace the signals and make the debugger useful. */
446 signal(SIGABRT, NULL);
447 signal(SIGSEGV, NULL);
448 #endif
450 #if defined(DOS)
451 /* Force DOS builds to ALWAYS use full screen as
452 * it can't do windowed. */
453 _fullscreen = true;
454 #endif
456 GetVideoModes();
457 if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height)) {
458 return "Failed to set up Allegro video";
460 MarkWholeScreenDirty();
461 set_close_button_callback(HandleExitGameRequest);
463 return NULL;
466 void VideoDriver_Allegro::Stop()
468 if (--_allegro_instance_count == 0) allegro_exit();
471 #if defined(UNIX) || defined(__OS2__) || defined(PSP) || defined(DOS)
472 # include <sys/time.h> /* gettimeofday */
474 static uint32 GetTime()
476 struct timeval tim;
478 gettimeofday(&tim, NULL);
479 return tim.tv_usec / 1000 + tim.tv_sec * 1000;
481 #else
482 static uint32 GetTime()
484 return GetTickCount();
486 #endif
489 void VideoDriver_Allegro::MainLoop()
491 uint32 cur_ticks = GetTime();
492 uint32 last_cur_ticks = cur_ticks;
493 uint32 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
495 CheckPaletteAnim();
497 for (;;) {
498 uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
499 InteractiveRandom(); // randomness
501 PollEvent();
502 if (_exit_game) return;
504 #if defined(_DEBUG)
505 if (_shift_pressed)
506 #else
507 /* Speedup when pressing tab, except when using ALT+TAB
508 * to switch to another application */
509 if (key[KEY_TAB] && (key_shifts & KB_ALT_FLAG) == 0)
510 #endif
512 if (!_networking && _game_mode != GM_MENU) _fast_forward |= 2;
513 } else if (_fast_forward & 2) {
514 _fast_forward = 0;
517 cur_ticks = GetTime();
518 if (cur_ticks >= next_tick || (_fast_forward && !_pause_mode) || cur_ticks < prev_cur_ticks) {
519 _realtime_tick += cur_ticks - last_cur_ticks;
520 last_cur_ticks = cur_ticks;
521 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
523 bool old_ctrl_pressed = _ctrl_pressed;
525 _ctrl_pressed = !!(key_shifts & KB_CTRL_FLAG);
526 _shift_pressed = !!(key_shifts & KB_SHIFT_FLAG);
528 /* determine which directional keys are down */
529 _dirkeys =
530 (key[KEY_LEFT] ? 1 : 0) |
531 (key[KEY_UP] ? 2 : 0) |
532 (key[KEY_RIGHT] ? 4 : 0) |
533 (key[KEY_DOWN] ? 8 : 0);
535 if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
537 GameLoop();
539 UpdateWindows();
540 CheckPaletteAnim();
541 DrawSurfaceToScreen();
542 } else {
543 CSleep(1);
544 NetworkDrawChatMessage();
545 DrawMouseCursor();
546 DrawSurfaceToScreen();
551 bool VideoDriver_Allegro::ChangeResolution(int w, int h)
553 return CreateMainSurface(w, h);
556 bool VideoDriver_Allegro::ToggleFullscreen(bool fullscreen)
558 #ifdef DOS
559 return false;
560 #else
561 _fullscreen = fullscreen;
562 GetVideoModes(); // get the list of available video modes
563 if (_num_resolutions == 0 || !this->ChangeResolution(_cur_resolution.width, _cur_resolution.height)) {
564 /* switching resolution failed, put back full_screen to original status */
565 _fullscreen ^= true;
566 return false;
568 return true;
569 #endif
572 bool VideoDriver_Allegro::AfterBlitterChange()
574 return CreateMainSurface(_screen.width, _screen.height);
577 #endif /* WITH_ALLEGRO */