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