Debian Codegraph @

engine/video/sdl.cpp

raw
1 // ____ _ __
2 // / __ )____ _____ | | / /___ ___________
3 // / __ / __ \/ ___/ | | /| / / __ `/ ___/ ___/
4 // / /_/ / /_/ (__ ) | |/ |/ / /_/ / / (__ )
5 // /_____/\____/____/ |__/|__/\__,_/_/ /____/
6 //
7 // A futuristic real-time strategy game.
8 // This file is part of Bos Wars.
9 //
10 /**@name sdl.cpp - SDL video support. */
11 //
12 // (c) Copyright 1999-2010 by Lutz Sammer, Jimmy Salmon, Nehal Mistry
13 //
14 // This program is free software; you can redistribute it and/or modify
15 // it under the terms of the GNU General Public License as published by
16 // the Free Software Foundation; only version 2 of the License.
17 //
18 // This program is distributed in the hope that it will be useful,
19 // but WITHOUT ANY WARRANTY; without even the implied warranty of
20 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 // GNU General Public License for more details.
22 //
23 // You should have received a copy of the GNU General Public License
24 // along with this program; if not, write to the Free Software
25 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
26 // 02111-1307, USA.
27 //
28
29 //@{
30
31 /*----------------------------------------------------------------------------
32 -- Includes
33 ----------------------------------------------------------------------------*/
34
35 #include "stratagus.h"
36
37 #ifdef DEBUG
38 #include <signal.h>
39 #endif
40
41 #include <map>
42 #include <string>
43
44 #include <stdlib.h>
45 #include <string.h>
46
47 #include <limits.h>
48 #ifndef _MSC_VER
49 #include <sys/time.h>
50 #include <sys/types.h>
51 #include <unistd.h>
52 #endif
53
54 #ifdef USE_WIN32
55 #include "net_lowlevel.h"
56 #endif
57
58 #include "video.h"
59 #include "font.h"
60 #include "interface.h"
61 #include "network.h"
62 #include "ui.h"
63 #include "sound_server.h"
64 #include "sound.h"
65 #include "interface.h"
66 #include "minimap.h"
67 #include "widgets.h"
68 #include "editor.h"
69
70 /*----------------------------------------------------------------------------
71 -- Declarations
72 ----------------------------------------------------------------------------*/
73
74 /*----------------------------------------------------------------------------
75 -- Variables
76 ----------------------------------------------------------------------------*/
77
78 SDL_Surface *TheScreen; /// Internal screen
79
80 static SDL_Rect Rects[100];
81 static int NumRects;
82 GLint GLMaxTextureSize; /// Max texture size supported on the video card
83 GLint GLMaxTextureSizeOverride; /// User-specified limit for ::GLMaxTextureSize
84 bool GLTextureCompressionSupported; /// Is OpenGL texture compression supported
85 bool UseGLTextureCompression; /// Use OpenGL texture compression
86
87 static std::map<int, std::string> Key2Str;
88 static std::map<std::string, int> Str2Key;
89
90 static int FrameTicks; /// Frame length in ms
91 static int FrameRemainder; /// Frame remainder 0.1 ms
92 static int FrameFraction; /// Frame fractional term
93
94 const EventCallback *Callbacks;
95
96 #ifdef DEBUG
97 bool DumpAllSdlEvents; /// Show all events received from SDL
98 #endif
99
100 /*----------------------------------------------------------------------------
101 -- Functions
102 ----------------------------------------------------------------------------*/
103
104 // ARB_texture_compression
105 PFNGLCOMPRESSEDTEXIMAGE3DARBPROC glCompressedTexImage3DARB;
106 PFNGLCOMPRESSEDTEXIMAGE2DARBPROC glCompressedTexImage2DARB;
107 PFNGLCOMPRESSEDTEXIMAGE1DARBPROC glCompressedTexImage1DARB;
108 PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC glCompressedTexSubImage3DARB;
109 PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC glCompressedTexSubImage2DARB;
110 PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC glCompressedTexSubImage1DARB;
111 PFNGLGETCOMPRESSEDTEXIMAGEARBPROC glGetCompressedTexImageARB;
112
113 /*----------------------------------------------------------------------------
114 -- Sync
115 ----------------------------------------------------------------------------*/
116
117 /**
118 ** Initialise video sync.
119 ** Calculate the length of video frame and any simulation skips.
120 **
121 ** @see VideoSyncSpeed @see SkipFrames @see FrameTicks @see FrameRemainder
122 */
123 void SetVideoSync(void)
124 {
125 int ms;
126
127 if (VideoSyncSpeed) {
128 ms = (1000 * 1000 / CYCLES_PER_SECOND) / VideoSyncSpeed;
129 } else {
130 ms = INT_MAX;
131 }
132 SkipFrames = ms / 400;
133 while (SkipFrames && ms / SkipFrames < 200) {
134 --SkipFrames;
135 }
136 ms /= SkipFrames + 1;
137
138 FrameTicks = ms / 10;
139 FrameRemainder = ms % 10;
140 DebugPrint("frames %d - %d.%dms\n" _C_ SkipFrames _C_ ms / 10 _C_ ms % 10);
141 }
142
143 /*----------------------------------------------------------------------------
144 -- Video
145 ----------------------------------------------------------------------------*/
146
147 /**
148 ** Check if an extension is supported
149 */
150 static bool IsExtensionSupported(const char *extension)
151 {
152 const GLubyte *extensions = NULL;
153 const GLubyte *start;
154 GLubyte *ptr, *terminator;
155 int len;
156
157 // Extension names should not have spaces.
158 ptr = (GLubyte *)strchr(extension, ' ');
159 if (ptr || *extension == '\0') {
160 return false;
161 }
162
163 extensions = glGetString(GL_EXTENSIONS);
164 len = strlen(extension);
165 start = extensions;
166 while (true) {
167 ptr = (GLubyte *)strstr((const char *)start, extension);
168 if (!ptr) {
169 break;
170 }
171
172 terminator = ptr + len;
173 if (ptr == start || *(ptr - 1) == ' ') {
174 if (*terminator == ' ' || *terminator == '\0') {
175 return true;
176 }
177 }
178 start = terminator;
179 }
180 return false;
181 }
182
183 /**
184 ** Initialize OpenGL extensions
185 */
186 static void InitOpenGLExtensions()
187 {
188 // ARB_texture_compression
189 if (IsExtensionSupported("GL_ARB_texture_compression"))
190 {
191 glCompressedTexImage3DARB =
192 (PFNGLCOMPRESSEDTEXIMAGE3DARBPROC)SDL_GL_GetProcAddress("glCompressedTexImage3DARB");
193 glCompressedTexImage2DARB =
194 (PFNGLCOMPRESSEDTEXIMAGE2DARBPROC)SDL_GL_GetProcAddress("glCompressedTexImage2DARB");
195 glCompressedTexImage1DARB =
196 (PFNGLCOMPRESSEDTEXIMAGE1DARBPROC)SDL_GL_GetProcAddress("glCompressedTexImage1DARB");
197 glCompressedTexSubImage3DARB =
198 (PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC)SDL_GL_GetProcAddress("glCompressedTexSubImage3DARB");
199 glCompressedTexSubImage2DARB =
200 (PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC)SDL_GL_GetProcAddress("glCompressedTexSubImage2DARB");
201 glCompressedTexSubImage1DARB =
202 (PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC)SDL_GL_GetProcAddress("glCompressedTexSubImage1DARB");
203 glGetCompressedTexImageARB =
204 (PFNGLGETCOMPRESSEDTEXIMAGEARBPROC)SDL_GL_GetProcAddress("glGetCompressedTexImageARB");
205
206 if (glCompressedTexImage3DARB && glCompressedTexImage2DARB &&
207 glCompressedTexImage1DARB && glCompressedTexSubImage3DARB &&
208 glCompressedTexSubImage2DARB && glCompressedTexSubImage1DARB &&
209 glGetCompressedTexImageARB)
210 {
211 GLTextureCompressionSupported = true;
212 }
213 else
214 {
215 GLTextureCompressionSupported = false;
216 }
217 }
218 }
219
220 /**
221 ** Initialize OpenGL
222 */
223 static void InitOpenGL(void)
224 {
225 InitOpenGLExtensions();
226
227 glViewport(0, 0, (GLsizei)Video.Width, (GLsizei)Video.Height);
228 glMatrixMode(GL_PROJECTION);
229 glLoadIdentity();
230 glOrtho(0, Video.Width, Video.Height, 0, -1, 1);
231 glMatrixMode(GL_MODELVIEW);
232 glLoadIdentity();
233 glTranslatef(0.375, 0.375, 0.);
234
235 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
236 glClearDepth(1.0f);
237 glShadeModel(GL_FLAT);
238 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
239 glEnable(GL_BLEND);
240 glEnable(GL_TEXTURE_2D);
241 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
242 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
243 glEnable(GL_LINE_SMOOTH);
244 glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
245
246 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &GLMaxTextureSize);
247 if (GLMaxTextureSize == 0) {
248 // FIXME: try to use GL_PROXY_TEXTURE_2D to get a valid size
249 #if 0
250 glTexImage2D(GL_PROXY_TEXTURE_2D, 0, GL_RGBA, size, size, 0,
251 GL_RGBA, GL_UNSIGNED_BYTE, NULL);
252 glGetTexLevelParameterfv(GL_PROXY_TEXTURE_2D, 0,
253 GL_TEXTURE_INTERNAL_FORMAT, &internalFormat);
254 #endif
255 fprintf(stderr, "GL_MAX_TEXTURE_SIZE is 0, using 256 by default\n");
256 GLMaxTextureSize = 256;
257 }
258 if (GLMaxTextureSize > GLMaxTextureSizeOverride
259 && GLMaxTextureSizeOverride > 0) {
260 GLMaxTextureSize = GLMaxTextureSizeOverride;
261 }
262 }
263
264 void ReloadOpenGL()
265 {
266 InitOpenGL();
267 ReloadGraphics();
268 ReloadFonts();
269 UI.Minimap.Reload();
270 }
271
272 #if defined(DEBUG) && !defined(USE_WIN32)
273 static void CleanExit(int signum)
274 {
275 // Clean SDL
276 SDL_Quit();
277 // Reestablish normal behaviour for next abort call
278 signal(SIGABRT, SIG_DFL);
279 // Generates a core dump
280 abort();
281 }
282 #endif
283
284 /**
285 ** Initialize SDLKey to string map
286 */
287 static void InitKey2Str()
288 {
289 Str2Key[_("esc")] = SDLK_ESCAPE;
290
291 if (!Key2Str.empty()) {
292 return;
293 }
294
295 int i;
296 char str[20];
297
298 Key2Str[SDLK_BACKSPACE] = "backspace";
299 Key2Str[SDLK_TAB] = "tab";
300 Key2Str[SDLK_CLEAR] = "clear";
301 Key2Str[SDLK_RETURN] = "return";
302 Key2Str[SDLK_PAUSE] = "pause";
303 Key2Str[SDLK_ESCAPE] = "escape";
304 Key2Str[SDLK_SPACE] = " ";
305 Key2Str[SDLK_EXCLAIM] = "!";
306 Key2Str[SDLK_QUOTEDBL] = "\"";
307 Key2Str[SDLK_HASH] = "#";
308 Key2Str[SDLK_DOLLAR] = "$";
309 Key2Str[SDLK_AMPERSAND] = "&";
310 Key2Str[SDLK_QUOTE] = "'";
311 Key2Str[SDLK_LEFTPAREN] = "(";
312 Key2Str[SDLK_RIGHTPAREN] = ")";
313 Key2Str[SDLK_ASTERISK] = "*";
314 Key2Str[SDLK_PLUS] = "+";
315 Key2Str[SDLK_COMMA] = ",";
316 Key2Str[SDLK_MINUS] = "-";
317 Key2Str[SDLK_PERIOD] = ".";
318 Key2Str[SDLK_SLASH] = "/";
319
320 str[1] = '\0';
321 for (i = SDLK_0; i <= SDLK_9; ++i) {
322 str[0] = i;
323 Key2Str[i] = str;
324 }
325
326 Key2Str[SDLK_COLON] = ":";
327 Key2Str[SDLK_SEMICOLON] = ";";
328 Key2Str[SDLK_LESS] = "<";
329 Key2Str[SDLK_EQUALS] = "=";
330 Key2Str[SDLK_GREATER] = ">";
331 Key2Str[SDLK_QUESTION] = "?";
332 Key2Str[SDLK_AT] = "@";
333 Key2Str[SDLK_LEFTBRACKET] = "[";
334 Key2Str[SDLK_BACKSLASH] = "\\";
335 Key2Str[SDLK_RIGHTBRACKET] = "]";
336 Key2Str[SDLK_BACKQUOTE] = "`";
337
338 str[1] = '\0';
339 for (i = SDLK_a; i <= SDLK_z; ++i) {
340 str[0] = i;
341 Key2Str[i] = str;
342 }
343
344 Key2Str[SDLK_DELETE] = "delete";
345
346 for (i = SDLK_KP0; i <= SDLK_KP9; ++i) {
347 sprintf_s(str, sizeof(str), "kp_%d", i - SDLK_KP0);
348 Key2Str[i] = str;
349 }
350
351 Key2Str[SDLK_KP_PERIOD] = "kp_period";
352 Key2Str[SDLK_KP_DIVIDE] = "kp_divide";
353 Key2Str[SDLK_KP_MULTIPLY] = "kp_multiply";
354 Key2Str[SDLK_KP_MINUS] = "kp_minus";
355 Key2Str[SDLK_KP_PLUS] = "kp_plus";
356 Key2Str[SDLK_KP_ENTER] = "kp_enter";
357 Key2Str[SDLK_KP_EQUALS] = "kp_equals";
358 Key2Str[SDLK_UP] = "up";
359 Key2Str[SDLK_DOWN] = "down";
360 Key2Str[SDLK_RIGHT] = "right";
361 Key2Str[SDLK_LEFT] = "left";
362 Key2Str[SDLK_INSERT] = "insert";
363 Key2Str[SDLK_HOME] = "home";
364 Key2Str[SDLK_END] = "end";
365 Key2Str[SDLK_PAGEUP] = "pageup";
366 Key2Str[SDLK_PAGEDOWN] = "pagedown";
367
368 for (i = SDLK_F1; i <= SDLK_F15; ++i) {
369 sprintf_s(str, sizeof(str), "f%d", i - SDLK_F1 + 1);
370 Key2Str[i] = str;
371 sprintf_s(str, sizeof(str), "F%d", i - SDLK_F1 + 1);
372 Str2Key[str] = i;
373 }
374
375 Key2Str[SDLK_HELP] = "help";
376 Key2Str[SDLK_PRINT] = "print";
377 Key2Str[SDLK_SYSREQ] = "sysreq";
378 Key2Str[SDLK_BREAK] = "break";
379 Key2Str[SDLK_MENU] = "menu";
380 Key2Str[SDLK_POWER] = "power";
381 Key2Str[SDLK_EURO] = "euro";
382 Key2Str[SDLK_UNDO] = "undo";
383 }
384
385 /**
386 ** Initialize the video part for SDL.
387 */
388 void InitVideoSdl(void)
389 {
390 Uint32 flags;
391
392 if (SDL_WasInit(SDL_INIT_VIDEO) == 0) {
393 #ifdef HAVE_X
394 // Fix tablet input in full-screen mode.
395 //
396 // By default, SDL 1.2 on X11 uses mouse relative mode
397 // if the mouse cursor is hidden and input is grabbed.
398 // In this mode, SDL attempts to report the direction
399 // in which the mouse is moving. SDL computes this
400 // from the mouse-cursor coordinates it gets from X.
401 // If the mouse cursor of X were to hit an edge of the
402 // screen, SDL would not know whether the user keeps
403 // moving the mouse in that direction. To prevent
404 // that, SDL warps the mouse cursor of X back to the
405 // center of the screen whenever it gets too far.
406 // SDL then compensates for this warping in its
407 // relative-motion computations, and uses the relative
408 // coordinates to maintain its own idea of the mouse
409 // cursor location, separately from what X thinks.
410 //
411 // All of the above works great with mice but fails
412 // horribly with tablet or touch-screen devices, where
413 // the coordinates reported by X depend only on the
414 // position of the stylus and not at all on where SDL
415 // previously warped the pointer. Because Bos Wars
416 // doesn't actually care about relative mouse motion,
417 // let's just disable that whole feature in SDL. The
418 // easiest way to do that is by setting an environment
419 // variable. Do this before SDL_Init in case that
420 // caches the value.
421 //
422 // SDL 1.2 documentation warns that environment
423 // variables are mostly for debugging and might not be
424 // supported in future SDL releases. In that event,
425 // Bos Wars can instead use the same trick as Barrage
426 // does: tell SDL to show the mouse cursor, but make
427 // all of its pixels transparent, so it's actually
428 // invisible. However, SDL 1.3 is apparently going to
429 // support tablet devices natively, so this might not
430 // be needed then.
431 static char mouseRelative0[] = "SDL_MOUSE_RELATIVE=0";
432 SDL_putenv(mouseRelative0); // doesn't want const
433 #endif
434
435 if (SDL_Init(
436 #ifdef DEBUG
437 SDL_INIT_NOPARACHUTE |
438 #endif
439 SDL_INIT_AUDIO | SDL_INIT_VIDEO |
440 SDL_INIT_TIMER) < 0 ) {
441 fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
442 exit(1);
443 }
444
445 // Clean up on exit
446
447 atexit(SDL_Quit);
448
449 // If debug is enabled, Stratagus disable SDL Parachute.
450 // So we need gracefully handle segfaults and aborts.
451 #if defined(DEBUG) && !defined(USE_WIN32)
452 signal(SIGSEGV, CleanExit);
453 signal(SIGABRT, CleanExit);
454 #endif
455 // Set WindowManager Title
456 SDL_WM_SetCaption("Bos Wars", "Bos Wars");
457 }
458
459 // Initialize the display
460
461 flags = 0;
462 // Sam said: better for windows.
463 /* SDL_HWSURFACE|SDL_HWPALETTE | */
464 if (Video.FullScreen) {
465 flags |= SDL_FULLSCREEN;
466 }
467 if (UseOpenGL) {
468 flags |= SDL_OPENGL;
469 }
470
471 if (!Video.Width || !Video.Height) {
472 Video.Width = 640;
473 Video.Height = 480;
474 }
475
476 TheScreen = SDL_SetVideoMode(Video.Width, Video.Height, Video.Depth, flags);
477 if (TheScreen && (TheScreen->format->BitsPerPixel != 16 &&
478 TheScreen->format->BitsPerPixel != 32)) {
479 // Only support 16 and 32 bpp, default to 16
480 TheScreen = SDL_SetVideoMode(Video.Width, Video.Height, 16, flags);
481 }
482 if (TheScreen == NULL) {
483 fprintf(stderr, "Couldn't set %dx%dx%d video mode: %s\n",
484 Video.Width, Video.Height, Video.Depth, SDL_GetError());
485 exit(1);
486 }
487
488 Video.FullScreen = (TheScreen->flags & SDL_FULLSCREEN) ? 1 : 0;
489 Video.Depth = TheScreen->format->BitsPerPixel;
490
491 // Turn cursor off, we use our own.
492 SDL_ShowCursor(0);
493
494 // Make default character translation easier
495 SDL_EnableUNICODE(1);
496
497 if (UseOpenGL) {
498 InitOpenGL();
499 }
500
501 InitKey2Str();
502
503 ColorBlack = Video.MapRGB(TheScreen->format, 0, 0, 0);
504 ColorDarkGreen = Video.MapRGB(TheScreen->format, 48, 100, 4);
505 ColorDarkBlue = Video.MapRGB(TheScreen->format, 0, 0, 96);
506 ColorBlue = Video.MapRGB(TheScreen->format, 0, 0, 252);
507 ColorCyan = Video.MapRGB(TheScreen->format, 0, 160, 208);
508 ColorOrange = Video.MapRGB(TheScreen->format, 248, 140, 20);
509 ColorWhite = Video.MapRGB(TheScreen->format, 252, 248, 240);
510 ColorGray = Video.MapRGB(TheScreen->format, 128, 128, 128);
511 ColorRed = Video.MapRGB(TheScreen->format, 252, 0, 0);
512 ColorGreen = Video.MapRGB(TheScreen->format, 0, 252, 0);
513 ColorYellow = Video.MapRGB(TheScreen->format, 252, 252, 0);
514
515 UI.MouseWarpX = UI.MouseWarpY = -1;
516 }
517
518 /**
519 ** Check if a resolution is valid
520 **
521 ** @param w Width
522 ** @param h Height
523 */
524 int VideoValidResolution(int w, int h)
525 {
526 return SDL_VideoModeOK(w, h, TheScreen->format->BitsPerPixel, TheScreen->flags);
527 }
528
529 /**
530 ** Invalidate some area
531 **
532 ** @param x screen pixel X position.
533 ** @param y screen pixel Y position.
534 ** @param w width of rectangle in pixels.
535 ** @param h height of rectangle in pixels.
536 */
537 void InvalidateArea(int x, int y, int w, int h)
538 {
539 if (!UseOpenGL) {
540 Assert(NumRects != sizeof(Rects) / sizeof(*Rects));
541 Assert(x >= 0 && y >= 0 && x + w <= Video.Width && y + h <= Video.Height);
542 Rects[NumRects].x = x;
543 Rects[NumRects].y = y;
544 Rects[NumRects].w = w;
545 Rects[NumRects].h = h;
546 ++NumRects;
547 }
548 }
549
550 /**
551 ** Invalidate whole window
552 */
553 void Invalidate(void)
554 {
555 if (!UseOpenGL) {
556 Rects[0].x = 0;
557 Rects[0].y = 0;
558 Rects[0].w = Video.Width;
559 Rects[0].h = Video.Height;
560 NumRects = 1;
561 }
562 }
563
564
565 #ifdef DEBUG
566
567 static void DumpSdlActiveEvent(const SDL_ActiveEvent &active, const char *type)
568 {
569 printf("SDL_ActiveEvent {"
570 " type=%s, gain=%d, state=%d }\n",
571 type,
572 static_cast<int>(active.gain),
573 static_cast<int>(active.state));
574 }
575
576 static void DumpSdlKeyboardEvent(const SDL_KeyboardEvent &key, const char *type)
577 {
578 printf("SDL_KeyboardEvent {"
579 " type=%s, which=%d, state=%d, keysym={"
580 " scancode=%d, sym=%d, mod=%d, unicode=%d }}\n",
581 type,
582 static_cast<int>(key.which),
583 static_cast<int>(key.state),
584 static_cast<int>(key.keysym.scancode),
585 static_cast<int>(key.keysym.sym),
586 static_cast<int>(key.keysym.mod),
587 static_cast<int>(key.keysym.unicode));
588 }
589
590 static void DumpSdlMouseMotionEvent(const SDL_MouseMotionEvent &motion, const char *type)
591 {
592 printf("SDL_MouseMotionEvent {"
593 " type=%s, which=%d, state=%d,"
594 " x=%d, y=%d, xrel=%d, yrel=%d }\n",
595 type,
596 static_cast<int>(motion.which),
597 static_cast<int>(motion.state),
598 static_cast<int>(motion.x),
599 static_cast<int>(motion.y),
600 static_cast<int>(motion.xrel),
601 static_cast<int>(motion.yrel));
602 }
603
604 static void DumpSdlMouseButtonEvent(const SDL_MouseButtonEvent &button, const char *type)
605 {
606 printf("SDL_MouseButtonEvent {"
607 " type=%s, which=%d, button=%d, state=%d, x=%d, y=%d }\n",
608 type,
609 static_cast<int>(button.which),
610 static_cast<int>(button.button),
611 static_cast<int>(button.state),
612 static_cast<int>(button.x),
613 static_cast<int>(button.y));
614 }
615
616 static void DumpSdlJoyAxisEvent(const SDL_JoyAxisEvent &jaxis, const char *type)
617 {
618 printf("SDL_JoyAxisEvent {"
619 " type=%s, which=%d, axis=%d, value=%d }\n",
620 type,
621 static_cast<int>(jaxis.which),
622 static_cast<int>(jaxis.axis),
623 static_cast<int>(jaxis.value));
624 }
625
626 static void DumpSdlJoyBallEvent(const SDL_JoyBallEvent &jball, const char *type)
627 {
628 printf("SDL_JoyBallEvent {"
629 " type=%s, which=%d, ball=%d, xrel=%d, yrel=%d }\n",
630 type,
631 static_cast<int>(jball.which),
632 static_cast<int>(jball.ball),
633 static_cast<int>(jball.xrel),
634 static_cast<int>(jball.yrel));
635 }
636
637 static void DumpSdlJoyHatEvent(const SDL_JoyHatEvent &jhat, const char *type)
638 {
639 printf("SDL_JoyHatEvent {"
640 " type=%s, which=%d, button=%d, state=%d }\n",
641 type,
642 static_cast<int>(jhat.which),
643 static_cast<int>(jhat.hat),
644 static_cast<int>(jhat.value));
645 }
646
647 static void DumpSdlJoyButtonEvent(const SDL_JoyButtonEvent &jbutton, const char *type)
648 {
649 printf("SDL_JoyButtonEvent {"
650 " type=%s, which=%d, button=%d, state=%d }\n",
651 type,
652 static_cast<int>(jbutton.which),
653 static_cast<int>(jbutton.button),
654 static_cast<int>(jbutton.state));
655 }
656
657 static void DumpSdlResizeEvent(const SDL_ResizeEvent &resize, const char *type)
658 {
659 printf("SDL_ResizeEvent {"
660 " type=%s, w=%d, h=%d }\n",
661 type,
662 static_cast<int>(resize.w),
663 static_cast<int>(resize.h));
664 }
665
666 static void DumpSdlExposeEvent(const SDL_ExposeEvent &, const char *type)
667 {
668 printf("SDL_ExposeEvent {"
669 " type=%s }\n",
670 type);
671 }
672
673 static void DumpSdlQuitEvent(const SDL_QuitEvent &, const char *type)
674 {
675 printf("SDL_QuitEvent {"
676 " type=%s }\n",
677 type);
678 }
679
680 static void DumpSdlEvent(const SDL_Event *event)
681 {
682 switch (event->type) {
683 case SDL_ACTIVEEVENT:
684 DumpSdlActiveEvent(event->active, "SDL_ACTIVEEVENT");
685 break;
686
687 case SDL_KEYDOWN:
688 DumpSdlKeyboardEvent(event->key, "SDL_KEYDOWN");
689 break;
690
691 case SDL_KEYUP:
692 DumpSdlKeyboardEvent(event->key, "SDL_KEYUP");
693 break;
694
695 case SDL_MOUSEMOTION:
696 DumpSdlMouseMotionEvent(event->motion, "SDL_MOUSEMOTION");
697 break;
698
699 case SDL_MOUSEBUTTONDOWN:
700 DumpSdlMouseButtonEvent(event->button, "SDL_MOUSEBUTTONDOWN");
701 break;
702
703 case SDL_MOUSEBUTTONUP:
704 DumpSdlMouseButtonEvent(event->button, "SDL_MOUSEBUTTONUP");
705 break;
706
707 case SDL_JOYAXISMOTION:
708 DumpSdlJoyAxisEvent(event->jaxis, "SDL_JOYAXISMOTION");
709 break;
710
711 case SDL_JOYBALLMOTION:
712 DumpSdlJoyBallEvent(event->jball, "SDL_JOYBALLMOTION");
713 break;
714
715 case SDL_JOYHATMOTION:
716 DumpSdlJoyHatEvent(event->jhat, "SDL_JOYHATMOTION");
717 break;
718
719 case SDL_JOYBUTTONDOWN:
720 DumpSdlJoyButtonEvent(event->jbutton, "SDL_JOYBUTTONDOWN");
721 break;
722
723 case SDL_JOYBUTTONUP:
724 DumpSdlJoyButtonEvent(event->jbutton, "SDL_JOYBUTTONUP");
725 break;
726
727 case SDL_VIDEORESIZE:
728 DumpSdlResizeEvent(event->resize, "SDL_VIDEORESIZE");
729 break;
730
731 case SDL_VIDEOEXPOSE:
732 DumpSdlExposeEvent(event->expose, "SDL_VIDEOEXPOSE");
733 break;
734
735 case SDL_QUIT:
736 DumpSdlQuitEvent(event->quit, "SDL_QUIT");
737 break;
738
739 default:
740 printf("SDL_Event { type=%d, ... }\n",
741 static_cast<int>(event->type));
742 break;
743
744 }
745 fflush(stdout);
746 }
747
748 #endif // DEBUG
749
750 /**
751 ** Handle interactive input event.
752 **
753 ** @param callbacks Callback structure for events.
754 ** @param event SDL event structure pointer.
755 */
756 static void SdlDoEvent(const EventCallback *callbacks, const SDL_Event *event)
757 {
758 #ifdef DEBUG
759 if (DumpAllSdlEvents) {
760 DumpSdlEvent(event);
761 }
762 #endif
763
764 switch (event->type) {
765 case SDL_MOUSEBUTTONDOWN:
766 InputMouseButtonPress(callbacks, SDL_GetTicks(),
767 event->button.button);
768 break;
769
770 case SDL_MOUSEBUTTONUP:
771 InputMouseButtonRelease(callbacks, SDL_GetTicks(),
772 event->button.button);
773 break;
774
775 // FIXME: check if this is only useful for the cursor
776 // FIXME: if this is the case we don't need this.
777 case SDL_MOUSEMOTION:
778 InputMouseMove(callbacks, SDL_GetTicks(),
779 event->motion.x, event->motion.y);
780 // FIXME: Same bug fix from X11
781 if ((UI.MouseWarpX != -1 || UI.MouseWarpY != -1) &&
782 (event->motion.x != UI.MouseWarpX ||
783 event->motion.y != UI.MouseWarpY)) {
784 int xw = UI.MouseWarpX;
785 int yw = UI.MouseWarpY;
786 UI.MouseWarpX = -1;
787 UI.MouseWarpY = -1;
788 SDL_WarpMouse(xw, yw);
789 }
790 break;
791
792 case SDL_ACTIVEEVENT:
793 if (event->active.state & SDL_APPMOUSEFOCUS) {
794 static bool InMainWindow = true;
795
796 if (InMainWindow && !event->active.gain) {
797 InputMouseExit(callbacks, SDL_GetTicks());
798 }
799 InMainWindow = (event->active.gain != 0);
800 }
801 if (event->active.state & SDL_APPACTIVE) {
802 static bool IsVisible = true;
803 static bool DoTogglePause = false;
804
805 if (IsVisible && !event->active.gain) {
806 IsVisible = false;
807 if (!GamePaused) {
808 DoTogglePause = true;
809 UiTogglePause();
810 }
811 } else if (!IsVisible && event->active.gain) {
812 IsVisible = true;
813 if (GamePaused && DoTogglePause) {
814 DoTogglePause = false;
815 UiTogglePause();
816 }
817 if (UseOpenGL) {
818 Video.ResizeScreen(Video.Width, Video.Height);
819 }
820 }
821 }
822 break;
823
824 case SDL_KEYDOWN:
825 InputKeyButtonPress(callbacks, SDL_GetTicks(),
826 event->key.keysym.sym, event->key.keysym.unicode);
827 break;
828
829 case SDL_KEYUP:
830 InputKeyButtonRelease(callbacks, SDL_GetTicks(),
831 event->key.keysym.sym, event->key.keysym.unicode);
832 break;
833
834 case SDL_QUIT:
835 Exit(0);
836 break;
837 }
838
839 if (callbacks == GetCallbacks()) {
840 handleInput(event);
841 }
842 }
843
844 /**
845 ** Set the current callbacks
846 */
847 void SetCallbacks(const EventCallback *callbacks)
848 {
849 Callbacks = callbacks;
850 }
851
852 /**
853 ** Get the current callbacks
854 */
855 const EventCallback *GetCallbacks()
856 {
857 return Callbacks;
858 }
859
860 /**
861 ** Wait for interactive input event for one frame.
862 **
863 ** Handles system events, joystick, keyboard, mouse.
864 ** Handles the network messages.
865 ** Handles the sound queue.
866 **
867 ** All events available are fetched. Sound and network only if available.
868 ** Returns if the time for one frame is over.
869 */
870 void WaitEventsOneFrame()
871 {
872 struct timeval tv;
873 fd_set rfds;
874 fd_set wfds;
875 Socket maxfd;
876 int i;
877 int s;
878 SDL_Event event[1];
879 Uint32 ticks;
880 int interrupts;
881
882 ++FrameCounter;
883
884 ticks = SDL_GetTicks();
885 if (ticks > NextFrameTicks) { // We are too slow :(
886 ++SlowFrameCounter;
887 }
888
889 InputMouseTimeout(GetCallbacks(), ticks);
890 InputKeyTimeout(GetCallbacks(), ticks);
891 CursorAnimate(ticks);
892
893 interrupts = 0;
894
895 for (;;) {
896 //
897 // Time of frame over? This makes the CPU happy. :(
898 //
899 ticks = SDL_GetTicks();
900 if (!interrupts && ticks < NextFrameTicks) {
901 SDL_Delay(NextFrameTicks - ticks);
902 ticks = SDL_GetTicks();
903 }
904 while (ticks >= NextFrameTicks) {
905 ++interrupts;
906 FrameFraction += FrameRemainder;
907 if (FrameFraction > 10) {
908 FrameFraction -= 10;
909 ++NextFrameTicks;
910 }
911 NextFrameTicks += FrameTicks;
912 }
913
914 //
915 // Prepare select
916 //
917 maxfd = 0;
918 tv.tv_sec = tv.tv_usec = 0;
919 FD_ZERO(&rfds);
920 FD_ZERO(&wfds);
921
922 //
923 // Network
924 //
925 if (IsNetworkGame()) {
926 if (NetworkFildes > maxfd) {
927 maxfd = NetworkFildes;
928 }
929 FD_SET(NetworkFildes, &rfds);
930 }
931
932 #if 0
933 s = select(maxfd + 1, &rfds, &wfds, NULL,
934 (i = SDL_PollEvent(event)) ? &tv : NULL);
935 #else
936 // QUICK HACK to fix the event/timer problem
937 // The timer code didn't interrupt the select call.
938 // Perhaps I could send a signal to the process
939 // Not very nice, but this is the problem if you use other libraries
940 // The event handling of SDL is wrong designed = polling only.
941 // There is hope on SDL 1.3 which will have this fixed.
942
943 s = select(maxfd + 1, &rfds, &wfds, NULL, &tv);
944 i = SDL_PollEvent(event);
945 #endif
946
947 if (i) { // Handle SDL event
948 SdlDoEvent(GetCallbacks(), event);
949 }
950
951 if (s > 0) {
952 //
953 // Network
954 //
955 if (IsNetworkGame() && FD_ISSET(NetworkFildes, &rfds) ) {
956 GetCallbacks()->NetworkEvent();
957 }
958 }
959
960 //
961 // No more input and time for frame over: return
962 //
963 if (!i && s <= 0 && interrupts) {
964 break;
965 }
966 }
967 handleInput(NULL);
968
969 if (!SkipGameCycle--) {
970 SkipGameCycle = SkipFrames;
971 }
972
973 if (!UseOpenGL && (GameRunning || Editor.Running || PatchEditorRunning)) {
974 Video.ClearScreen();
975 }
976 }
977
978 /**
979 ** Realize video memory.
980 */
981 void RealizeVideoMemory(void)
982 {
983 if (UseOpenGL) {
984 SDL_GL_SwapBuffers();
985 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
986 } else {
987 if (NumRects) {
988 SDL_UpdateRects(TheScreen, NumRects, Rects);
989 NumRects = 0;
990 }
991 }
992 HideCursor();
993 }
994
995 /**
996 ** Lock the screen for write access.
997 */
998 void SdlLockScreen(void)
999 {
1000 if (!UseOpenGL) {
1001 if (SDL_MUSTLOCK(TheScreen)) {
1002 SDL_LockSurface(TheScreen);
1003 }
1004 }
1005 }
1006
1007 /**
1008 ** Unlock the screen for write access.
1009 */
1010 void SdlUnlockScreen(void)
1011 {
1012 if (!UseOpenGL) {
1013 if (SDL_MUSTLOCK(TheScreen)) {
1014 SDL_UnlockSurface(TheScreen);
1015 }
1016 }
1017 }
1018
1019 /**
1020 ** Convert a SDLKey to a string
1021 */
1022 const char *SdlKey2Str(int key)
1023 {
1024 return Key2Str[key].c_str();
1025 }
1026
1027 /**
1028 ** Convert a string to SDLKey
1029 */
1030 int Str2SdlKey(const char *str)
1031 {
1032 InitKey2Str();
1033
1034 std::map<int, std::string>::iterator i;
1035 for (i = Key2Str.begin(); i != Key2Str.end(); ++i) {
1036 if (!strcasecmp(str, (*i).second.c_str())) {
1037 return (*i).first;
1038 }
1039 }
1040 std::map<std::string, int>::iterator i2;
1041 for (i2 = Str2Key.begin(); i2 != Str2Key.end(); ++i2) {
1042 if (!strcasecmp(str, (*i2).first.c_str())) {
1043 return (*i2).second;
1044 }
1045 }
1046 return 0;
1047 }
1048
1049 /**
1050 ** Check if the mouse is grabbed
1051 */
1052 bool SdlGetGrabMouse(void)
1053 {
1054 return SDL_WM_GrabInput(SDL_GRAB_QUERY) == SDL_GRAB_ON;
1055 }
1056
1057 /**
1058 ** Toggle grab mouse.
1059 **
1060 ** @param mode Wanted mode, 1 grab, -1 not grab, 0 toggle.
1061 */
1062 void ToggleGrabMouse(int mode)
1063 {
1064 bool grabbed = SdlGetGrabMouse();
1065
1066 if (mode <= 0 && grabbed) {
1067 SDL_WM_GrabInput(SDL_GRAB_OFF);
1068 } else if (mode >= 0 && !grabbed) {
1069 SDL_WM_GrabInput(SDL_GRAB_ON);
1070 }
1071 }
1072
1073 /**
1074 ** Toggle full screen mode.
1075 */
1076 void ToggleFullScreen(void)
1077 {
1078 #ifdef USE_WIN32
1079 long framesize;
1080 SDL_Rect clip;
1081 Uint32 flags;
1082 int w;
1083 int h;
1084 int bpp;
1085 unsigned char *pixels = NULL;
1086 SDL_Color *palette = NULL;
1087 int ncolors = 0;
1088
1089 if (!TheScreen) { // don't bother if there's no surface.
1090 return;
1091 }
1092
1093 flags = TheScreen->flags;
1094 w = TheScreen->w;
1095 h = TheScreen->h;
1096 bpp = TheScreen->format->BitsPerPixel;
1097
1098 if (!SDL_VideoModeOK(w, h, bpp, flags ^ SDL_FULLSCREEN)) {
1099 return;
1100 }
1101
1102 SDL_GetClipRect(TheScreen, &clip);
1103
1104 // save the contents of the screen.
1105 framesize = w * h * TheScreen->format->BytesPerPixel;
1106
1107 if (!UseOpenGL) {
1108 if (!(pixels = new unsigned char[framesize])) { // out of memory
1109 return;
1110 }
1111 SDL_LockSurface(TheScreen);
1112 memcpy(pixels, TheScreen->pixels, framesize);
1113
1114 if (TheScreen->format->palette) {
1115 ncolors = TheScreen->format->palette->ncolors;
1116 if (!(palette = new SDL_Color[ncolors])) {
1117 delete[] pixels;
1118 return;
1119 }
1120 memcpy(palette, TheScreen->format->palette->colors,
1121 ncolors * sizeof(SDL_Color));
1122 }
1123 SDL_UnlockSurface(TheScreen);
1124 }
1125
1126 TheScreen = SDL_SetVideoMode(w, h, bpp, flags ^ SDL_FULLSCREEN);
1127 if (!TheScreen) {
1128 TheScreen = SDL_SetVideoMode(w, h, bpp, flags);
1129 if (!TheScreen) { // completely screwed.
1130 if (!UseOpenGL) {
1131 delete[] pixels;
1132 delete[] palette;
1133 }
1134 fprintf(stderr, "Toggle to fullscreen, crashed all\n");
1135 Exit(-1);
1136 }
1137 }
1138
1139 // Windows shows the SDL cursor when starting in fullscreen mode
1140 // then switching to window mode. This hides the cursor again.
1141 SDL_ShowCursor(SDL_ENABLE);
1142 SDL_ShowCursor(SDL_DISABLE);
1143
1144 if (UseOpenGL) {
1145 ReloadOpenGL();
1146 } else {
1147 SDL_LockSurface(TheScreen);
1148 memcpy(TheScreen->pixels, pixels, framesize);
1149 delete[] pixels;
1150
1151 if (TheScreen->format->palette) {
1152 // !!! FIXME : No idea if that flags param is right.
1153 SDL_SetPalette(TheScreen, SDL_LOGPAL, palette, 0, ncolors);
1154 delete[] palette;
1155 }
1156 SDL_UnlockSurface(TheScreen);
1157 }
1158
1159 SDL_SetClipRect(TheScreen, &clip);
1160
1161 Invalidate(); // Update display
1162 #else // !USE_WIN32
1163 SDL_WM_ToggleFullScreen(TheScreen);
1164 #endif
1165
1166 Video.FullScreen = (TheScreen->flags & SDL_FULLSCREEN) ? 1 : 0;
1167 }
1168
1169 //@}