]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_sdl.c
Merge PR 'Use the text from modinfo.txt as the mod menu entry'
[xonotic/darkplaces.git] / vid_sdl.c
1 /*
2 Copyright (C) 2003  T. Joseph Carter
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18 */
19 #undef WIN32_LEAN_AND_MEAN  //hush a warning, SDL.h redefines this
20 #include <SDL.h>
21 #include <stdio.h>
22
23 #include "quakedef.h"
24 #include "image.h"
25 #include "utf8lib.h"
26
27 #ifndef __IPHONEOS__
28 #ifdef MACOSX
29 #include <Carbon/Carbon.h>
30 #include <IOKit/hidsystem/IOHIDLib.h>
31 #include <IOKit/hidsystem/IOHIDParameter.h>
32 #include <IOKit/hidsystem/event_status_driver.h>
33 #if (MAC_OS_X_VERSION_MIN_REQUIRED < 120000)
34         #define IOMainPort IOMasterPort
35 #endif
36 static cvar_t apple_mouse_noaccel = {CF_CLIENT | CF_ARCHIVE, "apple_mouse_noaccel", "1", "disables mouse acceleration while DarkPlaces is active"};
37 static qbool vid_usingnoaccel;
38 static double originalMouseSpeed = -1.0;
39 static io_connect_t IN_GetIOHandle(void)
40 {
41         io_connect_t iohandle = MACH_PORT_NULL;
42         kern_return_t status;
43         io_service_t iohidsystem = MACH_PORT_NULL;
44         mach_port_t masterport;
45
46         status = IOMainPort(MACH_PORT_NULL, &masterport);
47         if(status != KERN_SUCCESS)
48                 return 0;
49
50         iohidsystem = IORegistryEntryFromPath(masterport, kIOServicePlane ":/IOResources/IOHIDSystem");
51         if(!iohidsystem)
52                 return 0;
53
54         status = IOServiceOpen(iohidsystem, mach_task_self(), kIOHIDParamConnectType, &iohandle);
55         IOObjectRelease(iohidsystem);
56
57         return iohandle;
58 }
59 #endif
60 #endif
61
62 #ifdef WIN32
63 #define SDL_R_RESTART
64 #endif
65
66 // Tell startup code that we have a client
67 int cl_available = true;
68
69 qbool vid_supportrefreshrate = false;
70
71 static qbool vid_usingmouse = false;
72 static qbool vid_usingmouse_relativeworks = false; // SDL2 workaround for unimplemented RelativeMouse mode
73 static qbool vid_usinghidecursor = false;
74 static qbool vid_hasfocus = false;
75 static qbool vid_isfullscreen;
76 static qbool vid_usingvsync = false;
77 static SDL_Joystick *vid_sdljoystick = NULL;
78 static SDL_GameController *vid_sdlgamecontroller = NULL;
79 static cvar_t joy_sdl2_trigger_deadzone = {CF_ARCHIVE | CF_CLIENT, "joy_sdl2_trigger_deadzone", "0.5", "deadzone for triggers to be registered as key presses"};
80 // GAME_STEELSTORM specific
81 static cvar_t *steelstorm_showing_map = NULL; // detect but do not create the cvar
82 static cvar_t *steelstorm_showing_mousecursor = NULL; // detect but do not create the cvar
83
84 static int win_half_width = 50;
85 static int win_half_height = 50;
86 static int video_bpp;
87
88 static SDL_GLContext context;
89 static SDL_Window *window;
90 static int window_flags;
91 static vid_mode_t desktop_mode;
92
93 // Input handling
94
95 #ifndef SDLK_PERCENT
96 #define SDLK_PERCENT '%'
97 #endif
98
99 static int MapKey( unsigned int sdlkey )
100 {
101         switch(sdlkey)
102         {
103         default: return 0;
104 //      case SDLK_UNKNOWN:            return K_UNKNOWN;
105         case SDLK_RETURN:             return K_ENTER;
106         case SDLK_ESCAPE:             return K_ESCAPE;
107         case SDLK_BACKSPACE:          return K_BACKSPACE;
108         case SDLK_TAB:                return K_TAB;
109         case SDLK_SPACE:              return K_SPACE;
110         case SDLK_EXCLAIM:            return '!';
111         case SDLK_QUOTEDBL:           return '"';
112         case SDLK_HASH:               return '#';
113         case SDLK_PERCENT:            return '%';
114         case SDLK_DOLLAR:             return '$';
115         case SDLK_AMPERSAND:          return '&';
116         case SDLK_QUOTE:              return '\'';
117         case SDLK_LEFTPAREN:          return '(';
118         case SDLK_RIGHTPAREN:         return ')';
119         case SDLK_ASTERISK:           return '*';
120         case SDLK_PLUS:               return '+';
121         case SDLK_COMMA:              return ',';
122         case SDLK_MINUS:              return '-';
123         case SDLK_PERIOD:             return '.';
124         case SDLK_SLASH:              return '/';
125         case SDLK_0:                  return '0';
126         case SDLK_1:                  return '1';
127         case SDLK_2:                  return '2';
128         case SDLK_3:                  return '3';
129         case SDLK_4:                  return '4';
130         case SDLK_5:                  return '5';
131         case SDLK_6:                  return '6';
132         case SDLK_7:                  return '7';
133         case SDLK_8:                  return '8';
134         case SDLK_9:                  return '9';
135         case SDLK_COLON:              return ':';
136         case SDLK_SEMICOLON:          return ';';
137         case SDLK_LESS:               return '<';
138         case SDLK_EQUALS:             return '=';
139         case SDLK_GREATER:            return '>';
140         case SDLK_QUESTION:           return '?';
141         case SDLK_AT:                 return '@';
142         case SDLK_LEFTBRACKET:        return '[';
143         case SDLK_BACKSLASH:          return '\\';
144         case SDLK_RIGHTBRACKET:       return ']';
145         case SDLK_CARET:              return '^';
146         case SDLK_UNDERSCORE:         return '_';
147         case SDLK_BACKQUOTE:          return '`';
148         case SDLK_a:                  return 'a';
149         case SDLK_b:                  return 'b';
150         case SDLK_c:                  return 'c';
151         case SDLK_d:                  return 'd';
152         case SDLK_e:                  return 'e';
153         case SDLK_f:                  return 'f';
154         case SDLK_g:                  return 'g';
155         case SDLK_h:                  return 'h';
156         case SDLK_i:                  return 'i';
157         case SDLK_j:                  return 'j';
158         case SDLK_k:                  return 'k';
159         case SDLK_l:                  return 'l';
160         case SDLK_m:                  return 'm';
161         case SDLK_n:                  return 'n';
162         case SDLK_o:                  return 'o';
163         case SDLK_p:                  return 'p';
164         case SDLK_q:                  return 'q';
165         case SDLK_r:                  return 'r';
166         case SDLK_s:                  return 's';
167         case SDLK_t:                  return 't';
168         case SDLK_u:                  return 'u';
169         case SDLK_v:                  return 'v';
170         case SDLK_w:                  return 'w';
171         case SDLK_x:                  return 'x';
172         case SDLK_y:                  return 'y';
173         case SDLK_z:                  return 'z';
174         case SDLK_CAPSLOCK:           return K_CAPSLOCK;
175         case SDLK_F1:                 return K_F1;
176         case SDLK_F2:                 return K_F2;
177         case SDLK_F3:                 return K_F3;
178         case SDLK_F4:                 return K_F4;
179         case SDLK_F5:                 return K_F5;
180         case SDLK_F6:                 return K_F6;
181         case SDLK_F7:                 return K_F7;
182         case SDLK_F8:                 return K_F8;
183         case SDLK_F9:                 return K_F9;
184         case SDLK_F10:                return K_F10;
185         case SDLK_F11:                return K_F11;
186         case SDLK_F12:                return K_F12;
187         case SDLK_PRINTSCREEN:        return K_PRINTSCREEN;
188         case SDLK_SCROLLLOCK:         return K_SCROLLOCK;
189         case SDLK_PAUSE:              return K_PAUSE;
190         case SDLK_INSERT:             return K_INS;
191         case SDLK_HOME:               return K_HOME;
192         case SDLK_PAGEUP:             return K_PGUP;
193 #ifdef __IPHONEOS__
194         case SDLK_DELETE:             return K_BACKSPACE;
195 #else
196         case SDLK_DELETE:             return K_DEL;
197 #endif
198         case SDLK_END:                return K_END;
199         case SDLK_PAGEDOWN:           return K_PGDN;
200         case SDLK_RIGHT:              return K_RIGHTARROW;
201         case SDLK_LEFT:               return K_LEFTARROW;
202         case SDLK_DOWN:               return K_DOWNARROW;
203         case SDLK_UP:                 return K_UPARROW;
204         case SDLK_NUMLOCKCLEAR:       return K_NUMLOCK;
205         case SDLK_KP_DIVIDE:          return K_KP_DIVIDE;
206         case SDLK_KP_MULTIPLY:        return K_KP_MULTIPLY;
207         case SDLK_KP_MINUS:           return K_KP_MINUS;
208         case SDLK_KP_PLUS:            return K_KP_PLUS;
209         case SDLK_KP_ENTER:           return K_KP_ENTER;
210         case SDLK_KP_1:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_1 : K_END);
211         case SDLK_KP_2:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_2 : K_DOWNARROW);
212         case SDLK_KP_3:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_3 : K_PGDN);
213         case SDLK_KP_4:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_4 : K_LEFTARROW);
214         case SDLK_KP_5:               return K_KP_5;
215         case SDLK_KP_6:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_6 : K_RIGHTARROW);
216         case SDLK_KP_7:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_7 : K_HOME);
217         case SDLK_KP_8:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_8 : K_UPARROW);
218         case SDLK_KP_9:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_9 : K_PGUP);
219         case SDLK_KP_0:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_0 : K_INS);
220         case SDLK_KP_PERIOD:          return ((SDL_GetModState() & KMOD_NUM) ? K_KP_PERIOD : K_DEL);
221 //      case SDLK_APPLICATION:        return K_APPLICATION;
222 //      case SDLK_POWER:              return K_POWER;
223         case SDLK_KP_EQUALS:          return K_KP_EQUALS;
224 //      case SDLK_F13:                return K_F13;
225 //      case SDLK_F14:                return K_F14;
226 //      case SDLK_F15:                return K_F15;
227 //      case SDLK_F16:                return K_F16;
228 //      case SDLK_F17:                return K_F17;
229 //      case SDLK_F18:                return K_F18;
230 //      case SDLK_F19:                return K_F19;
231 //      case SDLK_F20:                return K_F20;
232 //      case SDLK_F21:                return K_F21;
233 //      case SDLK_F22:                return K_F22;
234 //      case SDLK_F23:                return K_F23;
235 //      case SDLK_F24:                return K_F24;
236 //      case SDLK_EXECUTE:            return K_EXECUTE;
237 //      case SDLK_HELP:               return K_HELP;
238 //      case SDLK_MENU:               return K_MENU;
239 //      case SDLK_SELECT:             return K_SELECT;
240 //      case SDLK_STOP:               return K_STOP;
241 //      case SDLK_AGAIN:              return K_AGAIN;
242 //      case SDLK_UNDO:               return K_UNDO;
243 //      case SDLK_CUT:                return K_CUT;
244 //      case SDLK_COPY:               return K_COPY;
245 //      case SDLK_PASTE:              return K_PASTE;
246 //      case SDLK_FIND:               return K_FIND;
247 //      case SDLK_MUTE:               return K_MUTE;
248 //      case SDLK_VOLUMEUP:           return K_VOLUMEUP;
249 //      case SDLK_VOLUMEDOWN:         return K_VOLUMEDOWN;
250 //      case SDLK_KP_COMMA:           return K_KP_COMMA;
251 //      case SDLK_KP_EQUALSAS400:     return K_KP_EQUALSAS400;
252 //      case SDLK_ALTERASE:           return K_ALTERASE;
253 //      case SDLK_SYSREQ:             return K_SYSREQ;
254 //      case SDLK_CANCEL:             return K_CANCEL;
255 //      case SDLK_CLEAR:              return K_CLEAR;
256 //      case SDLK_PRIOR:              return K_PRIOR;
257 //      case SDLK_RETURN2:            return K_RETURN2;
258 //      case SDLK_SEPARATOR:          return K_SEPARATOR;
259 //      case SDLK_OUT:                return K_OUT;
260 //      case SDLK_OPER:               return K_OPER;
261 //      case SDLK_CLEARAGAIN:         return K_CLEARAGAIN;
262 //      case SDLK_CRSEL:              return K_CRSEL;
263 //      case SDLK_EXSEL:              return K_EXSEL;
264 //      case SDLK_KP_00:              return K_KP_00;
265 //      case SDLK_KP_000:             return K_KP_000;
266 //      case SDLK_THOUSANDSSEPARATOR: return K_THOUSANDSSEPARATOR;
267 //      case SDLK_DECIMALSEPARATOR:   return K_DECIMALSEPARATOR;
268 //      case SDLK_CURRENCYUNIT:       return K_CURRENCYUNIT;
269 //      case SDLK_CURRENCYSUBUNIT:    return K_CURRENCYSUBUNIT;
270 //      case SDLK_KP_LEFTPAREN:       return K_KP_LEFTPAREN;
271 //      case SDLK_KP_RIGHTPAREN:      return K_KP_RIGHTPAREN;
272 //      case SDLK_KP_LEFTBRACE:       return K_KP_LEFTBRACE;
273 //      case SDLK_KP_RIGHTBRACE:      return K_KP_RIGHTBRACE;
274 //      case SDLK_KP_TAB:             return K_KP_TAB;
275 //      case SDLK_KP_BACKSPACE:       return K_KP_BACKSPACE;
276 //      case SDLK_KP_A:               return K_KP_A;
277 //      case SDLK_KP_B:               return K_KP_B;
278 //      case SDLK_KP_C:               return K_KP_C;
279 //      case SDLK_KP_D:               return K_KP_D;
280 //      case SDLK_KP_E:               return K_KP_E;
281 //      case SDLK_KP_F:               return K_KP_F;
282 //      case SDLK_KP_XOR:             return K_KP_XOR;
283 //      case SDLK_KP_POWER:           return K_KP_POWER;
284 //      case SDLK_KP_PERCENT:         return K_KP_PERCENT;
285 //      case SDLK_KP_LESS:            return K_KP_LESS;
286 //      case SDLK_KP_GREATER:         return K_KP_GREATER;
287 //      case SDLK_KP_AMPERSAND:       return K_KP_AMPERSAND;
288 //      case SDLK_KP_DBLAMPERSAND:    return K_KP_DBLAMPERSAND;
289 //      case SDLK_KP_VERTICALBAR:     return K_KP_VERTICALBAR;
290 //      case SDLK_KP_DBLVERTICALBAR:  return K_KP_DBLVERTICALBAR;
291 //      case SDLK_KP_COLON:           return K_KP_COLON;
292 //      case SDLK_KP_HASH:            return K_KP_HASH;
293 //      case SDLK_KP_SPACE:           return K_KP_SPACE;
294 //      case SDLK_KP_AT:              return K_KP_AT;
295 //      case SDLK_KP_EXCLAM:          return K_KP_EXCLAM;
296 //      case SDLK_KP_MEMSTORE:        return K_KP_MEMSTORE;
297 //      case SDLK_KP_MEMRECALL:       return K_KP_MEMRECALL;
298 //      case SDLK_KP_MEMCLEAR:        return K_KP_MEMCLEAR;
299 //      case SDLK_KP_MEMADD:          return K_KP_MEMADD;
300 //      case SDLK_KP_MEMSUBTRACT:     return K_KP_MEMSUBTRACT;
301 //      case SDLK_KP_MEMMULTIPLY:     return K_KP_MEMMULTIPLY;
302 //      case SDLK_KP_MEMDIVIDE:       return K_KP_MEMDIVIDE;
303 //      case SDLK_KP_PLUSMINUS:       return K_KP_PLUSMINUS;
304 //      case SDLK_KP_CLEAR:           return K_KP_CLEAR;
305 //      case SDLK_KP_CLEARENTRY:      return K_KP_CLEARENTRY;
306 //      case SDLK_KP_BINARY:          return K_KP_BINARY;
307 //      case SDLK_KP_OCTAL:           return K_KP_OCTAL;
308 //      case SDLK_KP_DECIMAL:         return K_KP_DECIMAL;
309 //      case SDLK_KP_HEXADECIMAL:     return K_KP_HEXADECIMAL;
310         case SDLK_LCTRL:              return K_CTRL;
311         case SDLK_LSHIFT:             return K_SHIFT;
312         case SDLK_LALT:               return K_ALT;
313 //      case SDLK_LGUI:               return K_LGUI;
314         case SDLK_RCTRL:              return K_CTRL;
315         case SDLK_RSHIFT:             return K_SHIFT;
316         case SDLK_RALT:               return K_ALT;
317 //      case SDLK_RGUI:               return K_RGUI;
318 //      case SDLK_MODE:               return K_MODE;
319 //      case SDLK_AUDIONEXT:          return K_AUDIONEXT;
320 //      case SDLK_AUDIOPREV:          return K_AUDIOPREV;
321 //      case SDLK_AUDIOSTOP:          return K_AUDIOSTOP;
322 //      case SDLK_AUDIOPLAY:          return K_AUDIOPLAY;
323 //      case SDLK_AUDIOMUTE:          return K_AUDIOMUTE;
324 //      case SDLK_MEDIASELECT:        return K_MEDIASELECT;
325 //      case SDLK_WWW:                return K_WWW;
326 //      case SDLK_MAIL:               return K_MAIL;
327 //      case SDLK_CALCULATOR:         return K_CALCULATOR;
328 //      case SDLK_COMPUTER:           return K_COMPUTER;
329 //      case SDLK_AC_SEARCH:          return K_AC_SEARCH; // Android button
330 //      case SDLK_AC_HOME:            return K_AC_HOME; // Android button
331         case SDLK_AC_BACK:            return K_ESCAPE; // Android button
332 //      case SDLK_AC_FORWARD:         return K_AC_FORWARD; // Android button
333 //      case SDLK_AC_STOP:            return K_AC_STOP; // Android button
334 //      case SDLK_AC_REFRESH:         return K_AC_REFRESH; // Android button
335 //      case SDLK_AC_BOOKMARKS:       return K_AC_BOOKMARKS; // Android button
336 //      case SDLK_BRIGHTNESSDOWN:     return K_BRIGHTNESSDOWN;
337 //      case SDLK_BRIGHTNESSUP:       return K_BRIGHTNESSUP;
338 //      case SDLK_DISPLAYSWITCH:      return K_DISPLAYSWITCH;
339 //      case SDLK_KBDILLUMTOGGLE:     return K_KBDILLUMTOGGLE;
340 //      case SDLK_KBDILLUMDOWN:       return K_KBDILLUMDOWN;
341 //      case SDLK_KBDILLUMUP:         return K_KBDILLUMUP;
342 //      case SDLK_EJECT:              return K_EJECT;
343 //      case SDLK_SLEEP:              return K_SLEEP;
344         }
345 }
346
347 qbool VID_HasScreenKeyboardSupport(void)
348 {
349         return SDL_HasScreenKeyboardSupport() != SDL_FALSE;
350 }
351
352 void VID_ShowKeyboard(qbool show)
353 {
354         if (!SDL_HasScreenKeyboardSupport())
355                 return;
356
357         if (show)
358         {
359                 if (!SDL_IsTextInputActive())
360                         SDL_StartTextInput();
361         }
362         else
363         {
364                 if (SDL_IsTextInputActive())
365                         SDL_StopTextInput();
366         }
367 }
368
369 qbool VID_ShowingKeyboard(void)
370 {
371         return SDL_IsTextInputActive() != 0;
372 }
373
374 void VID_SetMouse(qbool fullscreengrab, qbool relative, qbool hidecursor)
375 {
376 #ifndef DP_MOBILETOUCH
377 #ifdef MACOSX
378         if(relative)
379                 if(vid_usingmouse && (vid_usingnoaccel != !!apple_mouse_noaccel.integer))
380                         VID_SetMouse(false, false, false); // ungrab first!
381 #endif
382         if (vid_usingmouse != relative)
383         {
384                 vid_usingmouse = relative;
385                 cl_ignoremousemoves = 2;
386                 vid_usingmouse_relativeworks = SDL_SetRelativeMouseMode(relative ? SDL_TRUE : SDL_FALSE) == 0;
387 //              Con_Printf("VID_SetMouse(%i, %i, %i) relativeworks = %i\n", (int)fullscreengrab, (int)relative, (int)hidecursor, (int)vid_usingmouse_relativeworks);
388 #ifdef MACOSX
389                 if(relative)
390                 {
391                         // Save the status of mouse acceleration
392                         originalMouseSpeed = -1.0; // in case of error
393                         if(apple_mouse_noaccel.integer)
394                         {
395                                 io_connect_t mouseDev = IN_GetIOHandle();
396                                 if(mouseDev != 0)
397                                 {
398                                         if(IOHIDGetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), &originalMouseSpeed) == kIOReturnSuccess)
399                                         {
400                                                 Con_DPrintf("previous mouse acceleration: %f\n", originalMouseSpeed);
401                                                 if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), -1.0) != kIOReturnSuccess)
402                                                 {
403                                                         Con_Print("Could not disable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
404                                                         Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
405                                                 }
406                                         }
407                                         else
408                                         {
409                                                 Con_Print("Could not disable mouse acceleration (failed at IOHIDGetAccelerationWithKey).\n");
410                                                 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
411                                         }
412                                         IOServiceClose(mouseDev);
413                                 }
414                                 else
415                                 {
416                                         Con_Print("Could not disable mouse acceleration (failed at IO_GetIOHandle).\n");
417                                         Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
418                                 }
419                         }
420
421                         vid_usingnoaccel = !!apple_mouse_noaccel.integer;
422                 }
423                 else
424                 {
425                         if(originalMouseSpeed != -1.0)
426                         {
427                                 io_connect_t mouseDev = IN_GetIOHandle();
428                                 if(mouseDev != 0)
429                                 {
430                                         Con_DPrintf("restoring mouse acceleration to: %f\n", originalMouseSpeed);
431                                         if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), originalMouseSpeed) != kIOReturnSuccess)
432                                                 Con_Print("Could not re-enable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
433                                         IOServiceClose(mouseDev);
434                                 }
435                                 else
436                                         Con_Print("Could not re-enable mouse acceleration (failed at IO_GetIOHandle).\n");
437                         }
438                 }
439 #endif
440         }
441         if (vid_usinghidecursor != hidecursor)
442         {
443                 vid_usinghidecursor = hidecursor;
444                 SDL_ShowCursor( hidecursor ? SDL_DISABLE : SDL_ENABLE);
445         }
446 #endif
447 }
448
449 // multitouch[10][] represents the mouse pointer
450 // multitouch[][0]: finger active
451 // multitouch[][1]: Y
452 // multitouch[][2]: Y
453 // X and Y coordinates are 0-1.
454 #define MAXFINGERS 11
455 float multitouch[MAXFINGERS][3];
456
457 // this one stores how many areas this finger has touched
458 int multitouchs[MAXFINGERS];
459
460 // modified heavily by ELUAN
461 static qbool VID_TouchscreenArea(int corner, float px, float py, float pwidth, float pheight, const char *icon, float textheight, const char *text, float *resultmove, qbool *resultbutton, keynum_t key, const char *typedtext, float deadzone, float oversizepixels_x, float oversizepixels_y, qbool iamexclusive)
462 {
463         int finger;
464         float fx, fy, fwidth, fheight;
465         float overfx, overfy, overfwidth, overfheight;
466         float rel[3];
467         float sqsum;
468         qbool button = false;
469         VectorClear(rel);
470         if (pwidth > 0 && pheight > 0)
471         {
472                 if (corner & 1) px += vid_conwidth.value;
473                 if (corner & 2) py += vid_conheight.value;
474                 if (corner & 4) px += vid_conwidth.value * 0.5f;
475                 if (corner & 8) py += vid_conheight.value * 0.5f;
476                 if (corner & 16) {px *= vid_conwidth.value * (1.0f / 640.0f);py *= vid_conheight.value * (1.0f / 480.0f);pwidth *= vid_conwidth.value * (1.0f / 640.0f);pheight *= vid_conheight.value * (1.0f / 480.0f);}
477                 fx = px / vid_conwidth.value;
478                 fy = py / vid_conheight.value;
479                 fwidth = pwidth / vid_conwidth.value;
480                 fheight = pheight / vid_conheight.value;
481
482                 // try to prevent oversizepixels_* from interfering with the iamexclusive cvar by not letting we start controlling from too far of the actual touch area (areas without resultbuttons should NEVER have the oversizepixels_* parameters set to anything other than 0)
483                 if (resultbutton)
484                         if (!(*resultbutton))
485                         {
486                                 oversizepixels_x *= 0.2;
487                                 oversizepixels_y *= 0.2;
488                         }
489
490                 oversizepixels_x /= vid_conwidth.value;
491                 oversizepixels_y /= vid_conheight.value;
492
493                 overfx = fx - oversizepixels_x;
494                 overfy = fy - oversizepixels_y;
495                 overfwidth = fwidth + 2*oversizepixels_x;
496                 overfheight = fheight + 2*oversizepixels_y;
497
498                 for (finger = 0;finger < MAXFINGERS;finger++)
499                 {
500                         if (multitouchs[finger] && iamexclusive) // for this to work correctly, you must call touch areas in order of highest to lowest priority
501                                 continue;
502
503                         if (multitouch[finger][0] && multitouch[finger][1] >= overfx && multitouch[finger][2] >= overfy && multitouch[finger][1] < overfx + overfwidth && multitouch[finger][2] < overfy + overfheight)
504                         {
505                                 multitouchs[finger]++;
506
507                                 rel[0] = bound(-1, (multitouch[finger][1] - (fx + 0.5f * fwidth)) * (2.0f / fwidth), 1);
508                                 rel[1] = bound(-1, (multitouch[finger][2] - (fy + 0.5f * fheight)) * (2.0f / fheight), 1);
509                                 rel[2] = 0;
510
511                                 sqsum = rel[0]*rel[0] + rel[1]*rel[1];
512                                 // 2d deadzone
513                                 if (sqsum < deadzone*deadzone)
514                                 {
515                                         rel[0] = 0;
516                                         rel[1] = 0;
517                                 }
518                                 else if (sqsum > 1)
519                                 {
520                                         // ignore the third component
521                                         Vector2Normalize2(rel, rel);
522                                 }
523                                 button = true;
524                                 break;
525                         }
526                 }
527                 if (scr_numtouchscreenareas < 128)
528                 {
529                         scr_touchscreenareas[scr_numtouchscreenareas].pic = icon;
530                         scr_touchscreenareas[scr_numtouchscreenareas].text = text;
531                         scr_touchscreenareas[scr_numtouchscreenareas].textheight = textheight;
532                         scr_touchscreenareas[scr_numtouchscreenareas].rect[0] = px;
533                         scr_touchscreenareas[scr_numtouchscreenareas].rect[1] = py;
534                         scr_touchscreenareas[scr_numtouchscreenareas].rect[2] = pwidth;
535                         scr_touchscreenareas[scr_numtouchscreenareas].rect[3] = pheight;
536                         scr_touchscreenareas[scr_numtouchscreenareas].active = button;
537                         // the pics may have alpha too.
538                         scr_touchscreenareas[scr_numtouchscreenareas].activealpha = 1.f;
539                         scr_touchscreenareas[scr_numtouchscreenareas].inactivealpha = 0.95f;
540                         scr_numtouchscreenareas++;
541                 }
542         }
543         if (resultmove)
544         {
545                 if (button)
546                         VectorCopy(rel, resultmove);
547                 else
548                         VectorClear(resultmove);
549         }
550         if (resultbutton)
551         {
552                 if (*resultbutton != button)
553                 {
554                         if ((int)key > 0)
555                                 Key_Event(key, 0, button);
556                         if (typedtext && typedtext[0] && !*resultbutton)
557                         {
558                                 // FIXME: implement UTF8 support - nothing actually specifies a UTF8 string here yet, but should support it...
559                                 int i;
560                                 for (i = 0;typedtext[i];i++)
561                                 {
562                                         Key_Event(K_TEXT, typedtext[i], true);
563                                         Key_Event(K_TEXT, typedtext[i], false);
564                                 }
565                         }
566                 }
567                 *resultbutton = button;
568         }
569         return button;
570 }
571
572 // ELUAN:
573 // not reentrant, but we only need one mouse cursor anyway...
574 static void VID_TouchscreenCursor(float px, float py, float pwidth, float pheight, qbool *resultbutton, keynum_t key)
575 {
576         int finger;
577         float fx, fy, fwidth, fheight;
578         qbool button = false;
579         static int cursorfinger = -1;
580         static int cursorfreemovement = false;
581         static int canclick = false;
582         static int clickxy[2];
583         static int relclickxy[2];
584         static double clickrealtime = 0;
585
586         if (steelstorm_showing_mousecursor && steelstorm_showing_mousecursor->integer)
587         if (pwidth > 0 && pheight > 0)
588         {
589                 fx = px / vid_conwidth.value;
590                 fy = py / vid_conheight.value;
591                 fwidth = pwidth / vid_conwidth.value;
592                 fheight = pheight / vid_conheight.value;
593                 for (finger = 0;finger < MAXFINGERS;finger++)
594                 {
595                         if (multitouch[finger][0] && multitouch[finger][1] >= fx && multitouch[finger][2] >= fy && multitouch[finger][1] < fx + fwidth && multitouch[finger][2] < fy + fheight)
596                         {
597                                 if (cursorfinger == -1)
598                                 {
599                                         clickxy[0] =  multitouch[finger][1] * vid_width.value - 0.5f * pwidth;
600                                         clickxy[1] =  multitouch[finger][2] * vid_height.value - 0.5f * pheight;
601                                         relclickxy[0] =  (multitouch[finger][1] - fx) * vid_width.value - 0.5f * pwidth;
602                                         relclickxy[1] =  (multitouch[finger][2] - fy) * vid_height.value - 0.5f * pheight;
603                                 }
604                                 cursorfinger = finger;
605                                 button = true;
606                                 canclick = true;
607                                 cursorfreemovement = false;
608                                 break;
609                         }
610                 }
611                 if (scr_numtouchscreenareas < 128)
612                 {
613                         if (clickrealtime + 1 > host.realtime)
614                         {
615                                 scr_touchscreenareas[scr_numtouchscreenareas].pic = "gfx/gui/touch_puck_cur_click.tga";
616                         }
617                         else if (button)
618                         {
619                                 scr_touchscreenareas[scr_numtouchscreenareas].pic = "gfx/gui/touch_puck_cur_touch.tga";
620                         }
621                         else
622                         {
623                                 switch ((int)host.realtime * 10 % 20)
624                                 {
625                                 case 0:
626                                         scr_touchscreenareas[scr_numtouchscreenareas].pic = "gfx/gui/touch_puck_cur_touch.tga";
627                                         break;
628                                 default:
629                                         scr_touchscreenareas[scr_numtouchscreenareas].pic = "gfx/gui/touch_puck_cur_idle.tga";
630                                 }
631                         }
632                         scr_touchscreenareas[scr_numtouchscreenareas].text = "";
633                         scr_touchscreenareas[scr_numtouchscreenareas].textheight = 0;
634                         scr_touchscreenareas[scr_numtouchscreenareas].rect[0] = px;
635                         scr_touchscreenareas[scr_numtouchscreenareas].rect[1] = py;
636                         scr_touchscreenareas[scr_numtouchscreenareas].rect[2] = pwidth;
637                         scr_touchscreenareas[scr_numtouchscreenareas].rect[3] = pheight;
638                         scr_touchscreenareas[scr_numtouchscreenareas].active = button;
639                         scr_touchscreenareas[scr_numtouchscreenareas].activealpha = 1.0f;
640                         scr_touchscreenareas[scr_numtouchscreenareas].inactivealpha = 1.0f;
641                         scr_numtouchscreenareas++;
642                 }
643         }
644
645         if (cursorfinger != -1)
646         {
647                 if (multitouch[cursorfinger][0])
648                 {
649                         if (multitouch[cursorfinger][1] * vid_width.value - 0.5f * pwidth < clickxy[0] - 1 ||
650                                 multitouch[cursorfinger][1] * vid_width.value - 0.5f * pwidth > clickxy[0] + 1 ||
651                                 multitouch[cursorfinger][2] * vid_height.value - 0.5f * pheight< clickxy[1] - 1 ||
652                                 multitouch[cursorfinger][2] * vid_height.value - 0.5f * pheight> clickxy[1] + 1) // finger drifted more than the allowed amount
653                         {
654                                 cursorfreemovement = true;
655                         }
656                         if (cursorfreemovement)
657                         {
658                                 // in_windowmouse_x* is in screen resolution coordinates, not console resolution
659                                 in_windowmouse_x = multitouch[cursorfinger][1] * vid_width.value - 0.5f * pwidth - relclickxy[0];
660                                 in_windowmouse_y = multitouch[cursorfinger][2] * vid_height.value - 0.5f * pheight - relclickxy[1];
661                         }
662                 }
663                 else
664                 {
665                         cursorfinger = -1;
666                 }
667         }
668
669         if (resultbutton)
670         {
671                 if (/**resultbutton != button && */(int)key > 0)
672                 {
673                         if (!button && !cursorfreemovement && canclick)
674                         {
675                                 Key_Event(key, 0, true);
676                                 canclick = false;
677                                 clickrealtime = host.realtime;
678                         }
679
680                         // SS:BR can't qc can't cope with presses and releases on the same frame
681                         if (clickrealtime && clickrealtime + 0.1 < host.realtime)
682                         {
683                                 Key_Event(key, 0, false);
684                                 clickrealtime = 0;
685                         }
686                 }
687
688                 *resultbutton = button;
689         }
690 }
691
692 void VID_BuildJoyState(vid_joystate_t *joystate)
693 {
694         VID_Shared_BuildJoyState_Begin(joystate);
695
696         if (vid_sdljoystick)
697         {
698                 SDL_Joystick *joy = vid_sdljoystick;
699                 int j;
700
701                 if (vid_sdlgamecontroller)
702                 {
703                         for (j = 0; j <= SDL_CONTROLLER_AXIS_MAX; ++j)
704                         {
705                                 joystate->axis[j] = SDL_GameControllerGetAxis(vid_sdlgamecontroller, (SDL_GameControllerAxis)j) * (1.0f / 32767.0f);
706                         }
707                         for (j = 0; j < SDL_CONTROLLER_BUTTON_MAX; ++j)
708                                 joystate->button[j] = SDL_GameControllerGetButton(vid_sdlgamecontroller, (SDL_GameControllerButton)j);
709                         // emulate joy buttons for trigger "axes"
710                         joystate->button[SDL_CONTROLLER_BUTTON_MAX] = VID_JoyState_GetAxis(joystate, SDL_CONTROLLER_AXIS_TRIGGERLEFT, 1, joy_sdl2_trigger_deadzone.value) > 0.0f;
711                         joystate->button[SDL_CONTROLLER_BUTTON_MAX+1] = VID_JoyState_GetAxis(joystate, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, 1, joy_sdl2_trigger_deadzone.value) > 0.0f;
712                 }
713                 else
714
715                 {
716                         int numaxes;
717                         int numbuttons;
718                         numaxes = SDL_JoystickNumAxes(joy);
719                         for (j = 0;j < numaxes;j++)
720                                 joystate->axis[j] = SDL_JoystickGetAxis(joy, j) * (1.0f / 32767.0f);
721                         numbuttons = SDL_JoystickNumButtons(joy);
722                         for (j = 0;j < numbuttons;j++)
723                                 joystate->button[j] = SDL_JoystickGetButton(joy, j);
724                 }
725         }
726
727         VID_Shared_BuildJoyState_Finish(joystate);
728 }
729
730 // clear every touch screen area, except the one with button[skip]
731 #define Vid_ClearAllTouchscreenAreas(skip) \
732         if (skip != 0) \
733                 VID_TouchscreenCursor(0, 0, 0, 0, &buttons[0], K_MOUSE1); \
734         if (skip != 1) \
735                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, move, &buttons[1], K_MOUSE4, NULL, 0, 0, 0, false); \
736         if (skip != 2) \
737                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, aim,  &buttons[2], K_MOUSE5, NULL, 0, 0, 0, false); \
738         if (skip != 3) \
739                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[3], K_SHIFT, NULL, 0, 0, 0, false); \
740         if (skip != 4) \
741                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[4], K_MOUSE2, NULL, 0, 0, 0, false); \
742         if (skip != 9) \
743                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[9], K_MOUSE3, NULL, 0, 0, 0, false); \
744         if (skip != 10) \
745                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[10], (keynum_t)'m', NULL, 0, 0, 0, false); \
746         if (skip != 11) \
747                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[11], (keynum_t)'b', NULL, 0, 0, 0, false); \
748         if (skip != 12) \
749                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[12], (keynum_t)'q', NULL, 0, 0, 0, false); \
750         if (skip != 13) \
751                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[13], (keynum_t)'`', NULL, 0, 0, 0, false); \
752         if (skip != 14) \
753                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[14], K_ESCAPE, NULL, 0, 0, 0, false); \
754         if (skip != 15) \
755                 VID_TouchscreenArea( 0,  0,  0,  0,  0, NULL                         , 0.0f, NULL, NULL, &buttons[15], K_SPACE, NULL, 0, 0, 0, false); \
756
757 /////////////////////
758 // Movement handling
759 ////
760
761 static void IN_Move_TouchScreen_SteelStorm(void)
762 {
763         // ELUAN
764         int i, numfingers;
765         float xscale, yscale;
766         float move[3], aim[3];
767         static qbool oldbuttons[128];
768         static qbool buttons[128];
769         keydest_t keydest = (key_consoleactive & KEY_CONSOLEACTIVE_USER) ? key_console : key_dest;
770         memcpy(oldbuttons, buttons, sizeof(oldbuttons));
771         memset(multitouchs, 0, sizeof(multitouchs));
772
773         for (i = 0, numfingers = 0; i < MAXFINGERS - 1; i++)
774                 if (multitouch[i][0])
775                         numfingers++;
776
777         /*
778         Enable this to use a mouse as a touch device (it may conflict with the iamexclusive parameter if a finger is also reported as a mouse at the same location
779         if (numfingers == 1)
780         {
781                 multitouch[MAXFINGERS-1][0] = SDL_GetMouseState(&x, &y) ? 11 : 0;
782                 multitouch[MAXFINGERS-1][1] = (float)x / vid.width;
783                 multitouch[MAXFINGERS-1][2] = (float)y / vid.height;
784         }
785         else
786         {
787                 // disable it so it doesn't get stuck, because SDL seems to stop updating it if there are more than 1 finger on screen
788                 multitouch[MAXFINGERS-1][0] = 0;
789         }*/
790
791         // TODO: make touchscreen areas controlled by a config file or the VMs. THIS IS A MESS!
792         // TODO: can't just clear buttons[] when entering a new keydest, some keys would remain pressed
793         // SS:BR menuqc has many peculiarities, including that it can't accept more than one command per frame and pressing and releasing on the same frame
794
795         // Tuned for the SGS3, use it's value as a base. CLEAN THIS.
796         xscale = vid_touchscreen_density.value / 2.0f;
797         yscale = vid_touchscreen_density.value / 2.0f;
798         switch(keydest)
799         {
800         case key_console:
801                 Vid_ClearAllTouchscreenAreas(14);
802                 VID_TouchscreenArea( 0,   0, 160,  64,  64, "gfx/gui/touch_menu_button.tga"         , 0.0f, NULL, NULL, &buttons[14], K_ESCAPE, NULL, 0, 0, 0, false);
803                 break;
804         case key_game:
805                 if (steelstorm_showing_map && steelstorm_showing_map->integer) // FIXME: another hack to be removed when touchscreen areas go to QC
806                 {
807                         VID_TouchscreenArea( 0,   0,   0, vid_conwidth.value, vid_conheight.value, NULL                         , 0.0f, NULL, NULL, &buttons[10], (keynum_t)'m', NULL, 0, 0, 0, false);
808                         Vid_ClearAllTouchscreenAreas(10);
809                 }
810                 else if (steelstorm_showing_mousecursor && steelstorm_showing_mousecursor->integer)
811                 {
812                         // in_windowmouse_x* is in screen resolution coordinates, not console resolution
813                         VID_TouchscreenCursor((float)in_windowmouse_x/vid_width.value*vid_conwidth.value, (float)in_windowmouse_y/vid_height.value*vid_conheight.value, 192*xscale, 192*yscale, &buttons[0], K_MOUSE1);
814                         Vid_ClearAllTouchscreenAreas(0);
815                 }
816                 else
817                 {
818                         VID_TouchscreenCursor(0, 0, 0, 0, &buttons[0], K_MOUSE1);
819
820                         VID_TouchscreenArea( 2,16*xscale,-240*yscale, 224*xscale, 224*yscale, "gfx/gui/touch_l_thumb_dpad.tga", 0.0f, NULL, move, &buttons[1], (keynum_t)0, NULL, 0.15, 112*xscale, 112*yscale, false);
821
822                         VID_TouchscreenArea( 3,-240*xscale,-160*yscale, 224*xscale, 128*yscale, "gfx/gui/touch_r_thumb_turn_n_shoot.tga"    , 0.0f, NULL, NULL,  0, (keynum_t)0, NULL, 0, 56*xscale, 0, false);
823                         VID_TouchscreenArea( 3,-240*xscale,-256*yscale, 224*xscale, 224*yscale, NULL    , 0.0f, NULL, aim,  &buttons[2], (keynum_t)0, NULL, 0.2, 56*xscale, 0, false);
824
825                         VID_TouchscreenArea( 2, (vid_conwidth.value / 2) - 128,-80,  256,  80, NULL, 0.0f, NULL, NULL, &buttons[3], K_SHIFT, NULL, 0, 0, 0, true);
826
827                         VID_TouchscreenArea( 3,-240*xscale,-256*yscale, 224*xscale,  64*yscale, "gfx/gui/touch_secondary_slide.tga", 0.0f, NULL, NULL, &buttons[4], K_MOUSE2, NULL, 0, 56*xscale, 0, false);
828                         VID_TouchscreenArea( 3,-240*xscale,-256*yscale, 224*xscale,  160*yscale, NULL , 0.0f, NULL, NULL, &buttons[9], K_MOUSE3, NULL, 0.2, 56*xscale, 0, false);
829
830                         VID_TouchscreenArea( 1,-100,   0, 100, 100, NULL                         , 0.0f, NULL, NULL, &buttons[10], (keynum_t)'m', NULL, 0, 0, 0, true);
831                         VID_TouchscreenArea( 1,-100, 120, 100, 100, NULL                         , 0.0f, NULL, NULL, &buttons[11], (keynum_t)'b', NULL, 0, 0, 0, true);
832                         VID_TouchscreenArea( 0,   0,   0,  64,  64, NULL                         , 0.0f, NULL, NULL, &buttons[12], (keynum_t)'q', NULL, 0, 0, 0, true);
833                         if (developer.integer)
834                                 VID_TouchscreenArea( 0,   0,  96,  64,  64, NULL                         , 0.0f, NULL, NULL, &buttons[13], (keynum_t)'`', NULL, 0, 0, 0, true);
835                         else
836                                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[13], (keynum_t)'`', NULL, 0, 0, 0, false);
837                         VID_TouchscreenArea( 0,   0, 160,  64,  64, "gfx/gui/touch_menu_button.tga"         , 0.0f, NULL, NULL, &buttons[14], K_ESCAPE, NULL, 0, 0, 0, true);
838                         switch(cl.activeweapon)
839                         {
840                         case 14:
841                                 VID_TouchscreenArea( 2,  16*xscale,-320*yscale, 224*xscale, 64*yscale, "gfx/gui/touch_booster.tga" , 0.0f, NULL, NULL, &buttons[15], K_SPACE, NULL, 0, 0, 0, true);
842                                 break;
843                         case 12:
844                                 VID_TouchscreenArea( 2,  16*xscale,-320*yscale, 224*xscale, 64*yscale, "gfx/gui/touch_shockwave.tga" , 0.0f, NULL, NULL, &buttons[15], K_SPACE, NULL, 0, 0, 0, true);
845                                 break;
846                         default:
847                                 VID_TouchscreenArea( 0,  0,  0,  0,  0, NULL , 0.0f, NULL, NULL, &buttons[15], K_SPACE, NULL, 0, 0, 0, false);
848                         }
849                 }
850                 break;
851         default:
852                 if (!steelstorm_showing_mousecursor || !steelstorm_showing_mousecursor->integer)
853                 {
854                         Vid_ClearAllTouchscreenAreas(14);
855                         // this way we can skip cutscenes
856                         VID_TouchscreenArea( 0,   0,   0, vid_conwidth.value, vid_conheight.value, NULL                         , 0.0f, NULL, NULL, &buttons[14], K_ESCAPE, NULL, 0, 0, 0, false);
857                 }
858                 else
859                 {
860                         // in_windowmouse_x* is in screen resolution coordinates, not console resolution
861                         VID_TouchscreenCursor((float)in_windowmouse_x/vid_width.value*vid_conwidth.value, (float)in_windowmouse_y/vid_height.value*vid_conheight.value, 192*xscale, 192*yscale, &buttons[0], K_MOUSE1);
862                         Vid_ClearAllTouchscreenAreas(0);
863                 }
864                 break;
865         }
866
867         if (VID_ShowingKeyboard() && (float)in_windowmouse_y > vid_height.value / 2 - 10)
868                 in_windowmouse_y = 128;
869
870         cl.cmd.forwardmove -= move[1] * cl_forwardspeed.value;
871         cl.cmd.sidemove += move[0] * cl_sidespeed.value;
872         cl.viewangles[0] += aim[1] * cl_pitchspeed.value * cl.realframetime;
873         cl.viewangles[1] -= aim[0] * cl_yawspeed.value * cl.realframetime;
874 }
875
876 static void IN_Move_TouchScreen_Quake(void)
877 {
878         int x, y;
879         float move[3], aim[3], click[3];
880         static qbool oldbuttons[128];
881         static qbool buttons[128];
882         keydest_t keydest = (key_consoleactive & KEY_CONSOLEACTIVE_USER) ? key_console : key_dest;
883         memcpy(oldbuttons, buttons, sizeof(oldbuttons));
884         memset(multitouchs, 0, sizeof(multitouchs));
885
886         // simple quake controls
887         multitouch[MAXFINGERS-1][0] = SDL_GetMouseState(&x, &y);
888         multitouch[MAXFINGERS-1][1] = x * 32768 / vid.width;
889         multitouch[MAXFINGERS-1][2] = y * 32768 / vid.height;
890
891         // top of screen is toggleconsole and K_ESCAPE
892         switch(keydest)
893         {
894         case key_console:
895                 VID_TouchscreenArea( 0,   0,   0,  64,  64, NULL                         , 0.0f, NULL, NULL, &buttons[13], (keynum_t)'`', NULL, 0, 0, 0, true);
896                 VID_TouchscreenArea( 0,  64,   0,  64,  64, "gfx/touch_menu.tga"         , 0.0f, NULL, NULL, &buttons[14], K_ESCAPE, NULL, 0, 0, 0, true);
897                 if (!VID_ShowingKeyboard())
898                 {
899                         // user entered a command, close the console now
900                         Con_ToggleConsole_f(cmd_local);
901                 }
902                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[15], (keynum_t)0, NULL, 0, 0, 0, true);
903                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, move, &buttons[0], K_MOUSE4, NULL, 0, 0, 0, true);
904                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, aim,  &buttons[1], K_MOUSE5, NULL, 0, 0, 0, true);
905                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, click,&buttons[2], K_MOUSE1, NULL, 0, 0, 0, true);
906                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[3], K_SPACE, NULL, 0, 0, 0, true);
907                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[4], K_MOUSE2, NULL, 0, 0, 0, true);
908                 break;
909         case key_game:
910                 VID_TouchscreenArea( 0,   0,   0,  64,  64, NULL                         , 0.0f, NULL, NULL, &buttons[13], (keynum_t)'`', NULL, 0, 0, 0, true);
911                 VID_TouchscreenArea( 0,  64,   0,  64,  64, "gfx/touch_menu.tga"         , 0.0f, NULL, NULL, &buttons[14], K_ESCAPE, NULL, 0, 0, 0, true);
912                 VID_TouchscreenArea( 2,   0,-128, 128, 128, "gfx/touch_movebutton.tga"   , 0.0f, NULL, move, &buttons[0], K_MOUSE4, NULL, 0, 0, 0, true);
913                 VID_TouchscreenArea( 3,-128,-128, 128, 128, "gfx/touch_aimbutton.tga"    , 0.0f, NULL, aim,  &buttons[1], K_MOUSE5, NULL, 0, 0, 0, true);
914                 VID_TouchscreenArea( 2,   0,-160,  64,  32, "gfx/touch_jumpbutton.tga"   , 0.0f, NULL, NULL, &buttons[3], K_SPACE, NULL, 0, 0, 0, true);
915                 VID_TouchscreenArea( 3,-128,-160,  64,  32, "gfx/touch_attackbutton.tga" , 0.0f, NULL, NULL, &buttons[2], K_MOUSE1, NULL, 0, 0, 0, true);
916                 VID_TouchscreenArea( 3, -64,-160,  64,  32, "gfx/touch_attack2button.tga", 0.0f, NULL, NULL, &buttons[4], K_MOUSE2, NULL, 0, 0, 0, true);
917                 buttons[15] = false;
918                 break;
919         default:
920                 VID_TouchscreenArea( 0,   0,   0,  64,  64, NULL                         , 0.0f, NULL, NULL, &buttons[13], (keynum_t)'`', NULL, 0, 0, 0, true);
921                 VID_TouchscreenArea( 0,  64,   0,  64,  64, "gfx/touch_menu.tga"         , 0.0f, NULL, NULL, &buttons[14], K_ESCAPE, NULL, 0, 0, 0, true);
922                 // in menus, an icon in the corner activates keyboard
923                 VID_TouchscreenArea( 2,   0, -32,  32,  32, "gfx/touch_keyboard.tga"     , 0.0f, NULL, NULL, &buttons[15], (keynum_t)0, NULL, 0, 0, 0, true);
924                 if (buttons[15])
925                         VID_ShowKeyboard(true);
926                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, move, &buttons[0], K_MOUSE4, NULL, 0, 0, 0, true);
927                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, aim,  &buttons[1], K_MOUSE5, NULL, 0, 0, 0, true);
928                 VID_TouchscreenArea(16, -320,-480,640, 960, NULL                         , 0.0f, NULL, click,&buttons[2], K_MOUSE1, NULL, 0, 0, 0, true);
929                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[3], K_SPACE, NULL, 0, 0, 0, true);
930                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[4], K_MOUSE2, NULL, 0, 0, 0, true);
931                 if (buttons[2])
932                 {
933                         in_windowmouse_x = x;
934                         in_windowmouse_y = y;
935                 }
936                 break;
937         }
938
939         cl.cmd.forwardmove -= move[1] * cl_forwardspeed.value;
940         cl.cmd.sidemove += move[0] * cl_sidespeed.value;
941         cl.viewangles[0] += aim[1] * cl_pitchspeed.value * cl.realframetime;
942         cl.viewangles[1] -= aim[0] * cl_yawspeed.value * cl.realframetime;
943 }
944
945 void IN_Move( void )
946 {
947         static int old_x = 0, old_y = 0;
948         static int stuck = 0;
949         static keydest_t oldkeydest;
950         static qbool oldshowkeyboard;
951         int x, y;
952         vid_joystate_t joystate;
953         keydest_t keydest = (key_consoleactive & KEY_CONSOLEACTIVE_USER) ? key_console : key_dest;
954
955         scr_numtouchscreenareas = 0;
956
957         // Only apply the new keyboard state if the input changes.
958         if (keydest != oldkeydest || !!vid_touchscreen_showkeyboard.integer != oldshowkeyboard)
959         {
960                 switch(keydest)
961                 {
962                         case key_console: VID_ShowKeyboard(true);break;
963                         case key_message: VID_ShowKeyboard(true);break;
964                         default: VID_ShowKeyboard(!!vid_touchscreen_showkeyboard.integer); break;
965                 }
966         }
967         oldkeydest = keydest;
968         oldshowkeyboard = !!vid_touchscreen_showkeyboard.integer;
969
970         if (vid_touchscreen.integer)
971         {
972                 switch(gamemode)
973                 {
974                 case GAME_STEELSTORM:
975                         IN_Move_TouchScreen_SteelStorm();
976                         break;
977                 default:
978                         IN_Move_TouchScreen_Quake();
979                         break;
980                 }
981         }
982         else
983         {
984                 if (vid_usingmouse)
985                 {
986                         if (vid_stick_mouse.integer || !vid_usingmouse_relativeworks)
987                         {
988                                 // have the mouse stuck in the middle, example use: prevent expose effect of beryl during the game when not using
989                                 // window grabbing. --blub
990         
991                                 // we need 2 frames to initialize the center position
992                                 if(!stuck)
993                                 {
994                                         SDL_WarpMouseInWindow(window, win_half_width, win_half_height);
995                                         SDL_GetMouseState(&x, &y);
996                                         SDL_GetRelativeMouseState(&x, &y);
997                                         ++stuck;
998                                 } else {
999                                         SDL_GetRelativeMouseState(&x, &y);
1000                                         in_mouse_x = x + old_x;
1001                                         in_mouse_y = y + old_y;
1002                                         SDL_GetMouseState(&x, &y);
1003                                         old_x = x - win_half_width;
1004                                         old_y = y - win_half_height;
1005                                         SDL_WarpMouseInWindow(window, win_half_width, win_half_height);
1006                                 }
1007                         } else {
1008                                 SDL_GetRelativeMouseState( &x, &y );
1009                                 in_mouse_x = x;
1010                                 in_mouse_y = y;
1011                         }
1012                 }
1013
1014                 SDL_GetMouseState(&x, &y);
1015                 in_windowmouse_x = x;
1016                 in_windowmouse_y = y;
1017         }
1018
1019         VID_BuildJoyState(&joystate);
1020         VID_ApplyJoyState(&joystate);
1021 }
1022
1023 /////////////////////
1024 // Message Handling
1025 ////
1026
1027 #ifdef SDL_R_RESTART
1028 static qbool sdl_needs_restart;
1029 static void sdl_start(void)
1030 {
1031 }
1032 static void sdl_shutdown(void)
1033 {
1034         sdl_needs_restart = false;
1035 }
1036 static void sdl_newmap(void)
1037 {
1038 }
1039 #endif
1040
1041 static keynum_t buttonremap[] =
1042 {
1043         K_MOUSE1,
1044         K_MOUSE3,
1045         K_MOUSE2,
1046         K_MOUSE4,
1047         K_MOUSE5,
1048         K_MOUSE6,
1049         K_MOUSE7,
1050         K_MOUSE8,
1051         K_MOUSE9,
1052         K_MOUSE10,
1053         K_MOUSE11,
1054         K_MOUSE12,
1055         K_MOUSE13,
1056         K_MOUSE14,
1057         K_MOUSE15,
1058         K_MOUSE16,
1059 };
1060
1061 //#define DEBUGSDLEVENTS
1062
1063 // SDL2
1064 void Sys_SendKeyEvents( void )
1065 {
1066         static qbool sound_active = true;
1067         int keycode;
1068         int i;
1069         qbool isdown;
1070         Uchar unicode;
1071         SDL_Event event;
1072
1073         VID_EnableJoystick(true);
1074
1075         while( SDL_PollEvent( &event ) )
1076                 loop_start:
1077                 switch( event.type ) {
1078                         case SDL_QUIT:
1079 #ifdef DEBUGSDLEVENTS
1080                                 Con_DPrintf("SDL_Event: SDL_QUIT\n");
1081 #endif
1082                                 host.state = host_shutdown;
1083                                 break;
1084                         case SDL_KEYDOWN:
1085                         case SDL_KEYUP:
1086 #ifdef DEBUGSDLEVENTS
1087                                 if (event.type == SDL_KEYDOWN)
1088                                         Con_DPrintf("SDL_Event: SDL_KEYDOWN %i\n", event.key.keysym.sym);
1089                                 else
1090                                         Con_DPrintf("SDL_Event: SDL_KEYUP %i\n", event.key.keysym.sym);
1091 #endif
1092                                 keycode = MapKey(event.key.keysym.sym);
1093                                 isdown = (event.key.state == SDL_PRESSED);
1094                                 unicode = 0;
1095                                 if(isdown)
1096                                 {
1097                                         if(SDL_PollEvent(&event))
1098                                         {
1099                                                 if(event.type == SDL_TEXTINPUT)
1100                                                 {
1101                                                         // combine key code from SDL_KEYDOWN event and character
1102                                                         // from SDL_TEXTINPUT event in a single Key_Event call
1103 #ifdef DEBUGSDLEVENTS
1104                                                         Con_DPrintf("SDL_Event: SDL_TEXTINPUT - text: %s\n", event.text.text);
1105 #endif
1106                                                         unicode = u8_getchar_utf8_enabled(event.text.text + (int)u8_bytelen(event.text.text, 0), NULL);
1107                                                 }
1108                                                 else
1109                                                 {
1110                                                         if (!VID_JoyBlockEmulatedKeys(keycode))
1111                                                                 Key_Event(keycode, 0, isdown);
1112                                                         goto loop_start;
1113                                                 }
1114                                         }
1115                                 }
1116                                 if (!VID_JoyBlockEmulatedKeys(keycode))
1117                                         Key_Event(keycode, unicode, isdown);
1118                                 break;
1119                         case SDL_MOUSEBUTTONDOWN:
1120                         case SDL_MOUSEBUTTONUP:
1121 #ifdef DEBUGSDLEVENTS
1122                                 if (event.type == SDL_MOUSEBUTTONDOWN)
1123                                         Con_DPrintf("SDL_Event: SDL_MOUSEBUTTONDOWN\n");
1124                                 else
1125                                         Con_DPrintf("SDL_Event: SDL_MOUSEBUTTONUP\n");
1126 #endif
1127                                 if (!vid_touchscreen.integer)
1128                                 if (event.button.button > 0 && event.button.button <= ARRAY_SIZE(buttonremap))
1129                                         Key_Event( buttonremap[event.button.button - 1], 0, event.button.state == SDL_PRESSED );
1130                                 break;
1131                         case SDL_MOUSEWHEEL:
1132                                 // TODO support wheel x direction.
1133                                 i = event.wheel.y;
1134                                 while (i > 0) {
1135                                         --i;
1136                                         Key_Event( K_MWHEELUP, 0, true );
1137                                         Key_Event( K_MWHEELUP, 0, false );
1138                                 }
1139                                 while (i < 0) {
1140                                         ++i;
1141                                         Key_Event( K_MWHEELDOWN, 0, true );
1142                                         Key_Event( K_MWHEELDOWN, 0, false );
1143                                 }
1144                                 break;
1145                         case SDL_JOYBUTTONDOWN:
1146                         case SDL_JOYBUTTONUP:
1147                         case SDL_JOYAXISMOTION:
1148                         case SDL_JOYBALLMOTION:
1149                         case SDL_JOYHATMOTION:
1150 #ifdef DEBUGSDLEVENTS
1151                                 Con_DPrintf("SDL_Event: SDL_JOY*\n");
1152 #endif
1153                                 break;
1154                         case SDL_WINDOWEVENT:
1155 #ifdef DEBUGSDLEVENTS
1156                                 Con_DPrintf("SDL_Event: SDL_WINDOWEVENT %i\n", (int)event.window.event);
1157 #endif
1158                                 //if (event.window.windowID == window) // how to compare?
1159                                 {
1160                                         switch(event.window.event)
1161                                         {
1162                                         case SDL_WINDOWEVENT_SHOWN:
1163                                                 vid_hidden = false;
1164                                                 break;
1165                                         case  SDL_WINDOWEVENT_HIDDEN:
1166                                                 vid_hidden = true;
1167                                                 break;
1168                                         case SDL_WINDOWEVENT_EXPOSED:
1169 #ifdef DEBUGSDLEVENTS
1170                                                 Con_DPrintf("SDL_Event: SDL_WINDOWEVENT_EXPOSED\n");
1171 #endif
1172                                                 break;
1173                                         case SDL_WINDOWEVENT_MOVED:
1174                                                 break;
1175                                         case SDL_WINDOWEVENT_RESIZED:
1176                                                 if(vid_resizable.integer < 2)
1177                                                 {
1178                                                         vid.width = event.window.data1;
1179                                                         vid.height = event.window.data2;
1180 #ifdef SDL_R_RESTART
1181                                                         // better not call R_Modules_Restart_f from here directly, as this may wreak havoc...
1182                                                         // so, let's better queue it for next frame
1183                                                         if(!sdl_needs_restart)
1184                                                         {
1185                                                                 Cbuf_AddText(cmd_local, "\nr_restart\n");
1186                                                                 sdl_needs_restart = true;
1187                                                         }
1188 #endif
1189                                                 }
1190                                                 break;
1191                                         case SDL_WINDOWEVENT_MINIMIZED:
1192                                                 break;
1193                                         case SDL_WINDOWEVENT_MAXIMIZED:
1194                                                 break;
1195                                         case SDL_WINDOWEVENT_RESTORED:
1196                                                 break;
1197                                         case SDL_WINDOWEVENT_ENTER:
1198                                                 break;
1199                                         case SDL_WINDOWEVENT_LEAVE:
1200                                                 break;
1201                                         case SDL_WINDOWEVENT_FOCUS_GAINED:
1202                                                 vid_hasfocus = true;
1203                                                 break;
1204                                         case SDL_WINDOWEVENT_FOCUS_LOST:
1205                                                 vid_hasfocus = false;
1206                                                 break;
1207                                         case SDL_WINDOWEVENT_CLOSE:
1208                                                 host.state = host_shutdown;
1209                                                 break;
1210                                         }
1211                                 }
1212                                 break;
1213                         case SDL_TEXTEDITING:
1214 #ifdef DEBUGSDLEVENTS
1215                                 Con_DPrintf("SDL_Event: SDL_TEXTEDITING - composition = %s, cursor = %d, selection lenght = %d\n", event.edit.text, event.edit.start, event.edit.length);
1216 #endif
1217                                 // FIXME!  this is where composition gets supported
1218                                 break;
1219                         case SDL_TEXTINPUT:
1220 #ifdef DEBUGSDLEVENTS
1221                                 Con_DPrintf("SDL_Event: SDL_TEXTINPUT - text: %s\n", event.text.text);
1222 #endif
1223                                 // convert utf8 string to char
1224                                 // NOTE: this code is supposed to run even if utf8enable is 0
1225                                 unicode = u8_getchar_utf8_enabled(event.text.text + (int)u8_bytelen(event.text.text, 0), NULL);
1226                                 Key_Event(K_TEXT, unicode, true);
1227                                 Key_Event(K_TEXT, unicode, false);
1228                                 break;
1229                         case SDL_MOUSEMOTION:
1230                                 break;
1231                         case SDL_FINGERDOWN:
1232 #ifdef DEBUGSDLEVENTS
1233                                 Con_DPrintf("SDL_FINGERDOWN for finger %i\n", (int)event.tfinger.fingerId);
1234 #endif
1235                                 for (i = 0;i < MAXFINGERS-1;i++)
1236                                 {
1237                                         if (!multitouch[i][0])
1238                                         {
1239                                                 multitouch[i][0] = event.tfinger.fingerId + 1;
1240                                                 multitouch[i][1] = event.tfinger.x;
1241                                                 multitouch[i][2] = event.tfinger.y;
1242                                                 // TODO: use event.tfinger.pressure?
1243                                                 break;
1244                                         }
1245                                 }
1246                                 if (i == MAXFINGERS-1)
1247                                         Con_DPrintf("Too many fingers at once!\n");
1248                                 break;
1249                         case SDL_FINGERUP:
1250 #ifdef DEBUGSDLEVENTS
1251                                 Con_DPrintf("SDL_FINGERUP for finger %i\n", (int)event.tfinger.fingerId);
1252 #endif
1253                                 for (i = 0;i < MAXFINGERS-1;i++)
1254                                 {
1255                                         if (multitouch[i][0] == event.tfinger.fingerId + 1)
1256                                         {
1257                                                 multitouch[i][0] = 0;
1258                                                 break;
1259                                         }
1260                                 }
1261                                 if (i == MAXFINGERS-1)
1262                                         Con_DPrintf("No SDL_FINGERDOWN event matches this SDL_FINGERMOTION event\n");
1263                                 break;
1264                         case SDL_FINGERMOTION:
1265 #ifdef DEBUGSDLEVENTS
1266                                 Con_DPrintf("SDL_FINGERMOTION for finger %i\n", (int)event.tfinger.fingerId);
1267 #endif
1268                                 for (i = 0;i < MAXFINGERS-1;i++)
1269                                 {
1270                                         if (multitouch[i][0] == event.tfinger.fingerId + 1)
1271                                         {
1272                                                 multitouch[i][1] = event.tfinger.x;
1273                                                 multitouch[i][2] = event.tfinger.y;
1274                                                 break;
1275                                         }
1276                                 }
1277                                 if (i == MAXFINGERS-1)
1278                                         Con_DPrintf("No SDL_FINGERDOWN event matches this SDL_FINGERMOTION event\n");
1279                                 break;
1280                         default:
1281 #ifdef DEBUGSDLEVENTS
1282                                 Con_DPrintf("Received unrecognized SDL_Event type 0x%x\n", event.type);
1283 #endif
1284                                 break;
1285                 }
1286
1287         // enable/disable sound on focus gain/loss
1288         if ((!vid_hidden && vid_activewindow) || !snd_mutewhenidle.integer)
1289         {
1290                 if (!sound_active)
1291                 {
1292                         S_UnblockSound ();
1293                         sound_active = true;
1294                 }
1295         }
1296         else
1297         {
1298                 if (sound_active)
1299                 {
1300                         S_BlockSound ();
1301                         sound_active = false;
1302                 }
1303         }
1304 }
1305
1306 /////////////////
1307 // Video system
1308 ////
1309
1310 void *GL_GetProcAddress(const char *name)
1311 {
1312         void *p = NULL;
1313         p = SDL_GL_GetProcAddress(name);
1314         return p;
1315 }
1316
1317 qbool GL_ExtensionSupported(const char *name)
1318 {
1319         return SDL_GL_ExtensionSupported(name);
1320 }
1321
1322 static qbool vid_sdl_initjoysticksystem = false;
1323
1324 void VID_Init (void)
1325 {
1326 #ifndef __IPHONEOS__
1327 #ifdef MACOSX
1328         Cvar_RegisterVariable(&apple_mouse_noaccel);
1329 #endif
1330 #endif
1331 #ifdef DP_MOBILETOUCH
1332         Cvar_SetValueQuick(&vid_touchscreen, 1);
1333 #endif
1334         Cvar_RegisterVariable(&joy_sdl2_trigger_deadzone);
1335
1336 #ifdef SDL_R_RESTART
1337         R_RegisterModule("SDL", sdl_start, sdl_shutdown, sdl_newmap, NULL, NULL);
1338 #endif
1339
1340         if (SDL_Init(SDL_INIT_VIDEO) < 0)
1341                 Sys_Error ("Failed to init SDL video subsystem: %s", SDL_GetError());
1342         vid_sdl_initjoysticksystem = SDL_InitSubSystem(SDL_INIT_JOYSTICK) >= 0;
1343         if (!vid_sdl_initjoysticksystem)
1344                 Con_Printf(CON_ERROR "Failed to init SDL joystick subsystem: %s\n", SDL_GetError());
1345         vid_isfullscreen = false;
1346 }
1347
1348 static int vid_sdljoystickindex = -1;
1349 void VID_EnableJoystick(qbool enable)
1350 {
1351         int index = joy_enable.integer > 0 ? joy_index.integer : -1;
1352         int numsdljoysticks;
1353         qbool success = false;
1354         int sharedcount = 0;
1355         int sdlindex = -1;
1356         sharedcount = VID_Shared_SetJoystick(index);
1357         if (index >= 0 && index < sharedcount)
1358                 success = true;
1359         sdlindex = index - sharedcount;
1360
1361         numsdljoysticks = SDL_NumJoysticks();
1362         if (sdlindex < 0 || sdlindex >= numsdljoysticks)
1363                 sdlindex = -1;
1364
1365         // update cvar containing count of XInput joysticks + SDL joysticks
1366         if (joy_detected.integer != sharedcount + numsdljoysticks)
1367                 Cvar_SetValueQuick(&joy_detected, sharedcount + numsdljoysticks);
1368
1369         if (vid_sdljoystickindex != sdlindex)
1370         {
1371                 vid_sdljoystickindex = sdlindex;
1372                 // close SDL joystick if active
1373                 if (vid_sdljoystick)
1374                 {
1375                         SDL_JoystickClose(vid_sdljoystick);
1376                         vid_sdljoystick = NULL;
1377                 }
1378                 if (vid_sdlgamecontroller)
1379                 {
1380                         SDL_GameControllerClose(vid_sdlgamecontroller);
1381                         vid_sdlgamecontroller = NULL;
1382                 }
1383                 if (sdlindex >= 0)
1384                 {
1385                         vid_sdljoystick = SDL_JoystickOpen(sdlindex);
1386                         if (vid_sdljoystick)
1387                         {
1388                                 const char *joystickname = SDL_JoystickName(vid_sdljoystick);
1389                                 if (SDL_IsGameController(vid_sdljoystickindex))
1390                                 {
1391                                         vid_sdlgamecontroller = SDL_GameControllerOpen(vid_sdljoystickindex);
1392                                         Con_DPrintf("Using SDL GameController mappings for Joystick %i\n", index);
1393                                 }
1394                                 Con_Printf("Joystick %i opened (SDL_Joystick %i is \"%s\" with %i axes, %i buttons, %i balls)\n", index, sdlindex, joystickname, (int)SDL_JoystickNumAxes(vid_sdljoystick), (int)SDL_JoystickNumButtons(vid_sdljoystick), (int)SDL_JoystickNumBalls(vid_sdljoystick));
1395                         }
1396                         else
1397                         {
1398                                 Con_Printf(CON_ERROR "Joystick %i failed (SDL_JoystickOpen(%i) returned: %s)\n", index, sdlindex, SDL_GetError());
1399                                 sdlindex = -1;
1400                         }
1401                 }
1402         }
1403
1404         if (sdlindex >= 0)
1405                 success = true;
1406
1407         if (joy_active.integer != (success ? 1 : 0))
1408                 Cvar_SetValueQuick(&joy_active, success ? 1 : 0);
1409 }
1410
1411 static void VID_OutputVersion(void)
1412 {
1413         SDL_version version;
1414         SDL_GetVersion(&version);
1415         Con_Printf(     "Linked against SDL version %d.%d.%d\n"
1416                                         "Using SDL library version %d.%d.%d\n",
1417                                         SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL,
1418                                         version.major, version.minor, version.patch );
1419 }
1420
1421 #ifdef WIN32
1422 static void AdjustWindowBounds(viddef_mode_t *mode, RECT *rect)
1423 {
1424         int workWidth;
1425         int workHeight;
1426         int titleBarPixels = 2;
1427         int screenHeight;
1428         RECT workArea;
1429         LONG width = mode->width; // vid_width
1430         LONG height = mode->height; // vid_height
1431
1432         // adjust width and height for the space occupied by window decorators (title bar, borders)
1433         rect->top = 0;
1434         rect->left = 0;
1435         rect->right = width;
1436         rect->bottom = height;
1437         AdjustWindowRectEx(rect, WS_CAPTION|WS_THICKFRAME, false, 0);
1438
1439         SystemParametersInfo(SPI_GETWORKAREA, 0, &workArea, 0);
1440         workWidth = workArea.right - workArea.left;
1441         workHeight = workArea.bottom - workArea.top;
1442
1443         // SDL forces the window height to be <= screen height - 27px (on Win8.1 - probably intended for the title bar) 
1444         // If the task bar is docked to the the left screen border and we move the window to negative y,
1445         // there would be some part of the regular desktop visible on the bottom of the screen.
1446         screenHeight = GetSystemMetrics(SM_CYSCREEN);
1447         if (screenHeight == workHeight)
1448                 titleBarPixels = -rect->top;
1449
1450         //Con_Printf("window mode: %dx%d, workArea: %d/%d-%d/%d (%dx%d), title: %d\n", width, height, workArea.left, workArea.top, workArea.right, workArea.bottom, workArea.right - workArea.left, workArea.bottom - workArea.top, titleBarPixels);
1451
1452         // if height and width matches the physical or previously adjusted screen height and width, adjust it to available desktop area
1453         if ((width == GetSystemMetrics(SM_CXSCREEN) || width == workWidth) && (height == screenHeight || height == workHeight - titleBarPixels))
1454         {
1455                 rect->left = workArea.left;
1456                 mode->width = workWidth;
1457                 rect->top = workArea.top + titleBarPixels;
1458                 mode->height = workHeight - titleBarPixels;
1459         }
1460         else 
1461         {
1462                 rect->left = workArea.left + max(0, (workWidth - width) / 2);
1463                 rect->top = workArea.top + max(0, (workHeight - height) / 2);
1464         }
1465 }
1466 #endif
1467
1468 extern cvar_t gl_info_vendor;
1469 extern cvar_t gl_info_renderer;
1470 extern cvar_t gl_info_version;
1471 extern cvar_t gl_info_platform;
1472 extern cvar_t gl_info_driver;
1473
1474 static qbool VID_InitModeGL(viddef_mode_t *mode)
1475 {
1476         int windowflags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL;
1477         // currently SDL_WINDOWPOS_UNDEFINED behaves exactly like SDL_WINDOWPOS_CENTERED, this might change some day
1478         // https://trello.com/c/j56vUcwZ/81-centered-vs-undefined-window-position
1479         int xPos = SDL_WINDOWPOS_UNDEFINED;
1480         int yPos = SDL_WINDOWPOS_UNDEFINED;
1481         int i;
1482 #ifndef USE_GLES2
1483         const char *drivername;
1484 #endif
1485
1486         win_half_width = mode->width>>1;
1487         win_half_height = mode->height>>1;
1488
1489         if(vid_resizable.integer)
1490                 windowflags |= SDL_WINDOW_RESIZABLE;
1491
1492         VID_OutputVersion();
1493
1494 #ifndef USE_GLES2
1495         // SDL usually knows best
1496         drivername = NULL;
1497
1498 // COMMANDLINEOPTION: SDL GL: -gl_driver <drivername> selects a GL driver library, default is whatever SDL recommends, useful only for 3dfxogl.dll/3dfxvgl.dll or fxmesa or similar, if you don't know what this is for, you don't need it
1499         i = Sys_CheckParm("-gl_driver");
1500         if (i && i < sys.argc - 1)
1501                 drivername = sys.argv[i + 1];
1502         if (SDL_GL_LoadLibrary(drivername) < 0)
1503         {
1504                 Con_Printf(CON_ERROR "Unable to load GL driver \"%s\": %s\n", drivername, SDL_GetError());
1505                 return false;
1506         }
1507 #endif
1508
1509 #ifdef DP_MOBILETOUCH
1510         // mobile platforms are always fullscreen, we'll get the resolution after opening the window
1511         mode->fullscreen = true;
1512         // hide the menu with SDL_WINDOW_BORDERLESS
1513         windowflags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS;
1514 #endif
1515
1516         vid_isfullscreen = false;
1517         {
1518                 if (mode->fullscreen) {
1519                         if (vid_desktopfullscreen.integer)
1520                         {
1521                                 vid_mode_t *m = VID_GetDesktopMode();
1522                                 mode->width = m->width;
1523                                 mode->height = m->height;
1524                                 windowflags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
1525                         }
1526                         else
1527                                 windowflags |= SDL_WINDOW_FULLSCREEN;
1528                         vid_isfullscreen = true;
1529                 }
1530                 else {
1531                         if (vid_borderless.integer)
1532                                 windowflags |= SDL_WINDOW_BORDERLESS;
1533 #ifdef WIN32
1534                         if (vid_ignore_taskbar.integer) {
1535                                 xPos = SDL_WINDOWPOS_CENTERED;
1536                                 yPos = SDL_WINDOWPOS_CENTERED;
1537                         }
1538                         else {
1539                                 RECT rect;
1540                                 AdjustWindowBounds(mode, &rect);
1541                                 xPos = rect.left;
1542                                 yPos = rect.top;
1543                         }
1544 #endif
1545                 }
1546         }
1547         //flags |= SDL_HWSURFACE;
1548
1549         if (vid_mouse_clickthrough.integer && !vid_isfullscreen)
1550                 SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
1551
1552         SDL_GL_SetAttribute (SDL_GL_DOUBLEBUFFER, 1);
1553         SDL_GL_SetAttribute (SDL_GL_RED_SIZE, 8);
1554         SDL_GL_SetAttribute (SDL_GL_GREEN_SIZE, 8);
1555         SDL_GL_SetAttribute (SDL_GL_BLUE_SIZE, 8);
1556         SDL_GL_SetAttribute (SDL_GL_ALPHA_SIZE, 8);
1557         SDL_GL_SetAttribute (SDL_GL_DEPTH_SIZE, 24);
1558         SDL_GL_SetAttribute (SDL_GL_STENCIL_SIZE, 8);
1559         if (mode->stereobuffer)
1560                 SDL_GL_SetAttribute (SDL_GL_STEREO, 1);
1561         if (mode->samples > 1)
1562         {
1563                 SDL_GL_SetAttribute (SDL_GL_MULTISAMPLEBUFFERS, 1);
1564                 SDL_GL_SetAttribute (SDL_GL_MULTISAMPLESAMPLES, mode->samples);
1565         }
1566
1567 #ifdef USE_GLES2
1568         SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
1569         SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 2);
1570         SDL_GL_SetAttribute (SDL_GL_CONTEXT_MINOR_VERSION, 0);
1571 #else
1572         SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
1573         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
1574         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
1575 #endif
1576
1577         SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, (gl_debug.integer > 0 ? SDL_GL_CONTEXT_DEBUG_FLAG : 0));
1578
1579         video_bpp = mode->bitsperpixel;
1580         window_flags = windowflags;
1581         window = SDL_CreateWindow(gamename, xPos, yPos, mode->width, mode->height, windowflags);
1582         if (window == NULL)
1583         {
1584                 Con_Printf(CON_ERROR "Failed to set video mode to %ix%i: %s\n", mode->width, mode->height, SDL_GetError());
1585                 VID_Shutdown();
1586                 return false;
1587         }
1588         SDL_GetWindowSize(window, &mode->width, &mode->height);
1589         context = SDL_GL_CreateContext(window);
1590         if (context == NULL)
1591         {
1592                 Con_Printf(CON_ERROR "Failed to initialize OpenGL context: %s\n", SDL_GetError());
1593                 VID_Shutdown();
1594                 return false;
1595         }
1596
1597         SDL_GL_SetSwapInterval(bound(-1, vid_vsync.integer, 1));
1598         vid_usingvsync = (vid_vsync.integer != 0);
1599
1600         gl_platform = "SDL";
1601
1602         GL_Setup();
1603
1604         // VorteX: set other info
1605         Cvar_SetQuick(&gl_info_vendor, gl_vendor);
1606         Cvar_SetQuick(&gl_info_renderer, gl_renderer);
1607         Cvar_SetQuick(&gl_info_version, gl_version);
1608         Cvar_SetQuick(&gl_info_platform, gl_platform ? gl_platform : "");
1609         Cvar_SetQuick(&gl_info_driver, gl_driver);
1610
1611         // LadyHavoc: report supported extensions
1612         Con_DPrintf("\nQuakeC extensions for server and client:");
1613         for (i = 0; vm_sv_extensions[i]; i++)
1614                 Con_DPrintf(" %s", vm_sv_extensions[i]);
1615         Con_DPrintf("\n");
1616 #ifdef CONFIG_MENU
1617         Con_DPrintf("\nQuakeC extensions for menu:");
1618         for (i = 0; vm_m_extensions[i]; i++)
1619                 Con_DPrintf(" %s", vm_m_extensions[i]);
1620         Con_DPrintf("\n");
1621 #endif
1622
1623         // clear to black (loading plaque will be seen over this)
1624         GL_Clear(GL_COLOR_BUFFER_BIT, NULL, 1.0f, 0);
1625
1626         vid_hidden = false;
1627         vid_activewindow = false;
1628         vid_hasfocus = true;
1629         vid_usingmouse = false;
1630         vid_usinghidecursor = false;
1631                 
1632         return true;
1633 }
1634
1635 extern cvar_t gl_info_extensions;
1636 extern cvar_t gl_info_vendor;
1637 extern cvar_t gl_info_renderer;
1638 extern cvar_t gl_info_version;
1639 extern cvar_t gl_info_platform;
1640 extern cvar_t gl_info_driver;
1641
1642 qbool VID_InitMode(viddef_mode_t *mode)
1643 {
1644         // GAME_STEELSTORM specific
1645         steelstorm_showing_map = Cvar_FindVar(&cvars_all, "steelstorm_showing_map", ~0);
1646         steelstorm_showing_mousecursor = Cvar_FindVar(&cvars_all, "steelstorm_showing_mousecursor", ~0);
1647
1648         if (!SDL_WasInit(SDL_INIT_VIDEO) && SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
1649                 Sys_Error ("Failed to init SDL video subsystem: %s", SDL_GetError());
1650
1651         Cvar_SetValueQuick(&vid_touchscreen_supportshowkeyboard, SDL_HasScreenKeyboardSupport() ? 1 : 0);
1652         return VID_InitModeGL(mode);
1653 }
1654
1655 void VID_Shutdown (void)
1656 {
1657         VID_EnableJoystick(false);
1658         VID_SetMouse(false, false, false);
1659
1660         SDL_DestroyWindow(window);
1661         window = NULL;
1662
1663         SDL_QuitSubSystem(SDL_INIT_VIDEO);
1664
1665         gl_driver[0] = 0;
1666         gl_extensions = "";
1667         gl_platform = "";
1668 }
1669
1670 void VID_Finish (void)
1671 {
1672         qbool vid_usevsync;
1673         vid_activewindow = !vid_hidden && vid_hasfocus;
1674
1675         VID_UpdateGamma();
1676
1677         if (!vid_hidden)
1678         {
1679                 switch(vid.renderpath)
1680                 {
1681                 case RENDERPATH_GL32:
1682                 case RENDERPATH_GLES2:
1683                         CHECKGLERROR
1684                         if (r_speeds.integer == 2 || gl_finish.integer)
1685                                 GL_Finish();
1686
1687                         vid_usevsync = (vid_vsync.integer && !cls.timedemo);
1688                         if (vid_usingvsync != vid_usevsync)
1689                         {
1690                                 vid_usingvsync = vid_usevsync;
1691                                 if (SDL_GL_SetSwapInterval(vid_usevsync != 0) >= 0)
1692                                         Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
1693                                 else
1694                                         Con_DPrintf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
1695                         }
1696                         SDL_GL_SwapWindow(window);
1697                         break;
1698                 }
1699         }
1700 }
1701
1702 vid_mode_t *VID_GetDesktopMode(void)
1703 {
1704         SDL_DisplayMode mode;
1705         int bpp;
1706         Uint32 rmask, gmask, bmask, amask;
1707         SDL_GetDesktopDisplayMode(0, &mode);
1708         SDL_PixelFormatEnumToMasks(mode.format, &bpp, &rmask, &gmask, &bmask, &amask);
1709         desktop_mode.width = mode.w;
1710         desktop_mode.height = mode.h;
1711         desktop_mode.bpp = bpp;
1712         desktop_mode.refreshrate = mode.refresh_rate;
1713         desktop_mode.pixelheight_num = 1;
1714         desktop_mode.pixelheight_denom = 1; // SDL does not provide this
1715         // TODO check whether this actually works, or whether we do still need
1716         // a read-window-size-after-entering-desktop-fullscreen hack for
1717         // multiscreen setups.
1718         return &desktop_mode;
1719 }
1720
1721 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
1722 {
1723         size_t k = 0;
1724         int modenum;
1725         int nummodes = SDL_GetNumDisplayModes(0);
1726         SDL_DisplayMode mode;
1727         for (modenum = 0;modenum < nummodes;modenum++)
1728         {
1729                 if (k >= maxcount)
1730                         break;
1731                 if (SDL_GetDisplayMode(0, modenum, &mode))
1732                         continue;
1733                 modes[k].width = mode.w;
1734                 modes[k].height = mode.h;
1735                 // FIXME bpp?
1736                 modes[k].refreshrate = mode.refresh_rate;
1737                 modes[k].pixelheight_num = 1;
1738                 modes[k].pixelheight_denom = 1; // SDL does not provide this
1739                 k++;
1740         }
1741         return k;
1742 }