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