]> git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_sdl.c
iOS support in progress - accommodating GLES...
[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 <SDL_syswm.h>
22 #include <stdio.h>
23
24 #include "quakedef.h"
25 #include "image.h"
26 #include "dpsoftrast.h"
27
28 #ifndef __IPHONEOS__
29 #ifdef MACOSX
30 #include <Carbon/Carbon.h>
31 #include <IOKit/hidsystem/IOHIDLib.h>
32 #include <IOKit/hidsystem/IOHIDParameter.h>
33 #include <IOKit/hidsystem/event_status_driver.h>
34 static cvar_t apple_mouse_noaccel = {CVAR_SAVE, "apple_mouse_noaccel", "1", "disables mouse acceleration while DarkPlaces is active"};
35 static qboolean vid_usingnoaccel;
36 static double originalMouseSpeed = -1.0;
37 io_connect_t IN_GetIOHandle(void)
38 {
39         io_connect_t iohandle = MACH_PORT_NULL;
40         kern_return_t status;
41         io_service_t iohidsystem = MACH_PORT_NULL;
42         mach_port_t masterport;
43
44         status = IOMasterPort(MACH_PORT_NULL, &masterport);
45         if(status != KERN_SUCCESS)
46                 return 0;
47
48         iohidsystem = IORegistryEntryFromPath(masterport, kIOServicePlane ":/IOResources/IOHIDSystem");
49         if(!iohidsystem)
50                 return 0;
51
52         status = IOServiceOpen(iohidsystem, mach_task_self(), kIOHIDParamConnectType, &iohandle);
53         IOObjectRelease(iohidsystem);
54
55         return iohandle;
56 }
57 #endif
58 #endif
59
60 #ifdef WIN32
61 #define SDL_R_RESTART
62 #endif
63
64 // Tell startup code that we have a client
65 int cl_available = true;
66
67 qboolean vid_supportrefreshrate = false;
68
69 cvar_t vid_soft = {CVAR_SAVE, "vid_soft", "0", "enables use of the DarkPlaces Software Rasterizer rather than OpenGL or Direct3D"};
70 cvar_t vid_soft_threads = {CVAR_SAVE, "vid_soft_threads", "2", "the number of threads the DarkPlaces Software Rasterizer should use"}; 
71 cvar_t joy_detected = {CVAR_READONLY, "joy_detected", "0", "number of joysticks detected by engine"};
72 cvar_t joy_enable = {CVAR_SAVE, "joy_enable", "0", "enables joystick support"};
73 cvar_t joy_index = {0, "joy_index", "0", "selects which joystick to use if you have multiple"};
74 cvar_t joy_axisforward = {0, "joy_axisforward", "1", "which joystick axis to query for forward/backward movement"};
75 cvar_t joy_axisside = {0, "joy_axisside", "0", "which joystick axis to query for right/left movement"};
76 cvar_t joy_axisup = {0, "joy_axisup", "-1", "which joystick axis to query for up/down movement"};
77 cvar_t joy_axispitch = {0, "joy_axispitch", "3", "which joystick axis to query for looking up/down"};
78 cvar_t joy_axisyaw = {0, "joy_axisyaw", "2", "which joystick axis to query for looking right/left"};
79 cvar_t joy_axisroll = {0, "joy_axisroll", "-1", "which joystick axis to query for tilting head right/left"};
80 cvar_t joy_deadzoneforward = {0, "joy_deadzoneforward", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
81 cvar_t joy_deadzoneside = {0, "joy_deadzoneside", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
82 cvar_t joy_deadzoneup = {0, "joy_deadzoneup", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
83 cvar_t joy_deadzonepitch = {0, "joy_deadzonepitch", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
84 cvar_t joy_deadzoneyaw = {0, "joy_deadzoneyaw", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
85 cvar_t joy_deadzoneroll = {0, "joy_deadzoneroll", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
86 cvar_t joy_sensitivityforward = {0, "joy_sensitivityforward", "-1", "movement multiplier"};
87 cvar_t joy_sensitivityside = {0, "joy_sensitivityside", "1", "movement multiplier"};
88 cvar_t joy_sensitivityup = {0, "joy_sensitivityup", "1", "movement multiplier"};
89 cvar_t joy_sensitivitypitch = {0, "joy_sensitivitypitch", "1", "movement multiplier"};
90 cvar_t joy_sensitivityyaw = {0, "joy_sensitivityyaw", "-1", "movement multiplier"};
91 cvar_t joy_sensitivityroll = {0, "joy_sensitivityroll", "1", "movement multiplier"};
92 cvar_t joy_axiskeyevents = {CVAR_SAVE, "joy_axiskeyevents", "0", "generate uparrow/leftarrow etc. keyevents for joystick axes, use if your joystick driver is not generating them"};
93
94 static qboolean vid_usingmouse = false;
95 static qboolean vid_usinghidecursor = false;
96 static qboolean vid_isfullscreen;
97 #if !(SDL_MAJOR_VERSION == 1 && SDL_MINOR_VERSION == 2)
98 static qboolean vid_usingvsync = false;
99 #endif
100 static int vid_numjoysticks = 0;
101 #define MAX_JOYSTICKS 8
102 static SDL_Joystick *vid_joysticks[MAX_JOYSTICKS];
103
104 static int win_half_width = 50;
105 static int win_half_height = 50;
106 static int video_bpp, video_flags;
107
108 static SDL_Surface *screen;
109 static SDL_Surface *vid_softsurface;
110
111 // joystick axes state
112 #define MAX_JOYSTICK_AXES       16
113 typedef struct
114 {
115         float oldmove;
116         float move;
117         double keytime;
118 }joy_axiscache_t;
119 static joy_axiscache_t joy_axescache[MAX_JOYSTICK_AXES];
120
121 /////////////////////////
122 // Input handling
123 ////
124 //TODO: Add joystick support
125 //TODO: Add error checking
126
127
128 //keysym to quake keysym mapping
129 #define tenoh   0,0,0,0,0, 0,0,0,0,0
130 #define fiftyoh tenoh, tenoh, tenoh, tenoh, tenoh
131 #define hundredoh fiftyoh, fiftyoh
132 static unsigned int tbl_sdltoquake[] =
133 {
134         0,0,0,0,                //SDLK_UNKNOWN          = 0,
135         0,0,0,0,                //SDLK_FIRST            = 0,
136         K_BACKSPACE,    //SDLK_BACKSPACE        = 8,
137         K_TAB,                  //SDLK_TAB                      = 9,
138         0,0,
139         0,                              //SDLK_CLEAR            = 12,
140         K_ENTER,                //SDLK_RETURN           = 13,
141     0,0,0,0,0,
142         K_PAUSE,                //SDLK_PAUSE            = 19,
143         0,0,0,0,0,0,0,
144         K_ESCAPE,               //SDLK_ESCAPE           = 27,
145         0,0,0,0,
146         K_SPACE,                //SDLK_SPACE            = 32,
147         '!',                    //SDLK_EXCLAIM          = 33,
148         '"',                    //SDLK_QUOTEDBL         = 34,
149         '#',                    //SDLK_HASH                     = 35,
150         '$',                    //SDLK_DOLLAR           = 36,
151         0,
152         '&',                    //SDLK_AMPERSAND        = 38,
153         '\'',                   //SDLK_QUOTE            = 39,
154         '(',                    //SDLK_LEFTPAREN        = 40,
155         ')',                    //SDLK_RIGHTPAREN       = 41,
156         '*',                    //SDLK_ASTERISK         = 42,
157         '+',                    //SDLK_PLUS                     = 43,
158         ',',                    //SDLK_COMMA            = 44,
159         '-',                    //SDLK_MINUS            = 45,
160         '.',                    //SDLK_PERIOD           = 46,
161         '/',                    //SDLK_SLASH            = 47,
162         '0',                    //SDLK_0                        = 48,
163         '1',                    //SDLK_1                        = 49,
164         '2',                    //SDLK_2                        = 50,
165         '3',                    //SDLK_3                        = 51,
166         '4',                    //SDLK_4                        = 52,
167         '5',                    //SDLK_5                        = 53,
168         '6',                    //SDLK_6                        = 54,
169         '7',                    //SDLK_7                        = 55,
170         '8',                    //SDLK_8                        = 56,
171         '9',                    //SDLK_9                        = 57,
172         ':',                    //SDLK_COLON            = 58,
173         ';',                    //SDLK_SEMICOLON        = 59,
174         '<',                    //SDLK_LESS                     = 60,
175         '=',                    //SDLK_EQUALS           = 61,
176         '>',                    //SDLK_GREATER          = 62,
177         '?',                    //SDLK_QUESTION         = 63,
178         '@',                    //SDLK_AT                       = 64,
179         0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
180         '[',            //SDLK_LEFTBRACKET      = 91,
181         '\\',           //SDLK_BACKSLASH        = 92,
182         ']',            //SDLK_RIGHTBRACKET     = 93,
183         '^',            //SDLK_CARET            = 94,
184         '_',            //SDLK_UNDERSCORE       = 95,
185         '`',            //SDLK_BACKQUOTE        = 96,
186         'a',            //SDLK_a                        = 97,
187         'b',            //SDLK_b                        = 98,
188         'c',            //SDLK_c                        = 99,
189         'd',            //SDLK_d                        = 100,
190         'e',            //SDLK_e                        = 101,
191         'f',            //SDLK_f                        = 102,
192         'g',            //SDLK_g                        = 103,
193         'h',            //SDLK_h                        = 104,
194         'i',            //SDLK_i                        = 105,
195         'j',            //SDLK_j                        = 106,
196         'k',            //SDLK_k                        = 107,
197         'l',            //SDLK_l                        = 108,
198         'm',            //SDLK_m                        = 109,
199         'n',            //SDLK_n                        = 110,
200         'o',            //SDLK_o                        = 111,
201         'p',            //SDLK_p                        = 112,
202         'q',            //SDLK_q                        = 113,
203         'r',            //SDLK_r                        = 114,
204         's',            //SDLK_s                        = 115,
205         't',            //SDLK_t                        = 116,
206         'u',            //SDLK_u                        = 117,
207         'v',            //SDLK_v                        = 118,
208         'w',            //SDLK_w                        = 119,
209         'x',            //SDLK_x                        = 120,
210         'y',            //SDLK_y                        = 121,
211         'z',            //SDLK_z                        = 122,
212         0,0,0,0,
213         K_DEL,          //SDLK_DELETE           = 127,
214         hundredoh /*227*/, tenoh, tenoh, 0,0,0,0,0,0,0,0,
215         K_KP_0,         //SDLK_KP0              = 256,
216         K_KP_1,         //SDLK_KP1              = 257,
217         K_KP_2,         //SDLK_KP2              = 258,
218         K_KP_3,         //SDLK_KP3              = 259,
219         K_KP_4,         //SDLK_KP4              = 260,
220         K_KP_5,         //SDLK_KP5              = 261,
221         K_KP_6,         //SDLK_KP6              = 262,
222         K_KP_7,         //SDLK_KP7              = 263,
223         K_KP_8,         //SDLK_KP8              = 264,
224         K_KP_9,         //SDLK_KP9              = 265,
225         K_KP_PERIOD,//SDLK_KP_PERIOD    = 266,
226         K_KP_DIVIDE,//SDLK_KP_DIVIDE    = 267,
227         K_KP_MULTIPLY,//SDLK_KP_MULTIPLY= 268,
228         K_KP_MINUS,     //SDLK_KP_MINUS         = 269,
229         K_KP_PLUS,      //SDLK_KP_PLUS          = 270,
230         K_KP_ENTER,     //SDLK_KP_ENTER         = 271,
231         K_KP_EQUALS,//SDLK_KP_EQUALS    = 272,
232         K_UPARROW,      //SDLK_UP               = 273,
233         K_DOWNARROW,//SDLK_DOWN         = 274,
234         K_RIGHTARROW,//SDLK_RIGHT       = 275,
235         K_LEFTARROW,//SDLK_LEFT         = 276,
236         K_INS,          //SDLK_INSERT   = 277,
237         K_HOME,         //SDLK_HOME             = 278,
238         K_END,          //SDLK_END              = 279,
239         K_PGUP,         //SDLK_PAGEUP   = 280,
240         K_PGDN,         //SDLK_PAGEDOWN = 281,
241         K_F1,           //SDLK_F1               = 282,
242         K_F2,           //SDLK_F2               = 283,
243         K_F3,           //SDLK_F3               = 284,
244         K_F4,           //SDLK_F4               = 285,
245         K_F5,           //SDLK_F5               = 286,
246         K_F6,           //SDLK_F6               = 287,
247         K_F7,           //SDLK_F7               = 288,
248         K_F8,           //SDLK_F8               = 289,
249         K_F9,           //SDLK_F9               = 290,
250         K_F10,          //SDLK_F10              = 291,
251         K_F11,          //SDLK_F11              = 292,
252         K_F12,          //SDLK_F12              = 293,
253         0,                      //SDLK_F13              = 294,
254         0,                      //SDLK_F14              = 295,
255         0,                      //SDLK_F15              = 296,
256         0,0,0,
257         K_NUMLOCK,      //SDLK_NUMLOCK  = 300,
258         K_CAPSLOCK,     //SDLK_CAPSLOCK = 301,
259         K_SCROLLOCK,//SDLK_SCROLLOCK= 302,
260         K_SHIFT,        //SDLK_RSHIFT   = 303,
261         K_SHIFT,        //SDLK_LSHIFT   = 304,
262         K_CTRL,         //SDLK_RCTRL    = 305,
263         K_CTRL,         //SDLK_LCTRL    = 306,
264         K_ALT,          //SDLK_RALT             = 307,
265         K_ALT,          //SDLK_LALT             = 308,
266         0,                      //SDLK_RMETA    = 309,
267         0,                      //SDLK_LMETA    = 310,
268         0,                      //SDLK_LSUPER   = 311,          /* Left "Windows" key */
269         0,                      //SDLK_RSUPER   = 312,          /* Right "Windows" key */
270         K_ALT,                  //SDLK_MODE             = 313,          /* "Alt Gr" key */
271         0,                      //SDLK_COMPOSE  = 314,          /* Multi-key compose key */
272         0,                      //SDLK_HELP             = 315,
273         0,                      //SDLK_PRINT    = 316,
274         0,                      //SDLK_SYSREQ   = 317,
275         K_PAUSE,        //SDLK_BREAK    = 318,
276         0,                      //SDLK_MENU             = 319,
277         0,                      //SDLK_POWER    = 320,          /* Power Macintosh power key */
278         'e',            //SDLK_EURO             = 321,          /* Some european keyboards */
279         0                       //SDLK_UNDO             = 322,          /* Atari keyboard has Undo */
280 };
281 #undef tenoh
282 #undef fiftyoh
283 #undef hundredoh
284
285 static int MapKey( unsigned int sdlkey )
286 {
287         if( sdlkey > sizeof(tbl_sdltoquake)/ sizeof(int) )
288                 return 0;
289     return tbl_sdltoquake[ sdlkey ];
290 }
291
292 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
293 {
294 #ifndef __IPHONEOS__
295 #ifdef MACOSX
296         if(relative)
297                 if(vid_usingmouse && (vid_usingnoaccel != !!apple_mouse_noaccel.integer))
298                         VID_SetMouse(false, false, false); // ungrab first!
299 #endif
300 #endif
301         if (vid_usingmouse != relative)
302         {
303                 vid_usingmouse = relative;
304                 cl_ignoremousemoves = 2;
305                 SDL_WM_GrabInput( relative ? SDL_GRAB_ON : SDL_GRAB_OFF );
306 #ifndef __IPHONEOS__
307 #ifdef MACOSX
308                 if(relative)
309                 {
310                         // Save the status of mouse acceleration
311                         originalMouseSpeed = -1.0; // in case of error
312                         if(apple_mouse_noaccel.integer)
313                         {
314                                 io_connect_t mouseDev = IN_GetIOHandle();
315                                 if(mouseDev != 0)
316                                 {
317                                         if(IOHIDGetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), &originalMouseSpeed) == kIOReturnSuccess)
318                                         {
319                                                 Con_DPrintf("previous mouse acceleration: %f\n", originalMouseSpeed);
320                                                 if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), -1.0) != kIOReturnSuccess)
321                                                 {
322                                                         Con_Print("Could not disable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
323                                                         Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
324                                                 }
325                                         }
326                                         else
327                                         {
328                                                 Con_Print("Could not disable mouse acceleration (failed at IOHIDGetAccelerationWithKey).\n");
329                                                 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
330                                         }
331                                         IOServiceClose(mouseDev);
332                                 }
333                                 else
334                                 {
335                                         Con_Print("Could not disable mouse acceleration (failed at IO_GetIOHandle).\n");
336                                         Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
337                                 }
338                         }
339
340                         vid_usingnoaccel = !!apple_mouse_noaccel.integer;
341                 }
342                 else
343                 {
344                         if(originalMouseSpeed != -1.0)
345                         {
346                                 io_connect_t mouseDev = IN_GetIOHandle();
347                                 if(mouseDev != 0)
348                                 {
349                                         Con_DPrintf("restoring mouse acceleration to: %f\n", originalMouseSpeed);
350                                         if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), originalMouseSpeed) != kIOReturnSuccess)
351                                                 Con_Print("Could not re-enable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
352                                         IOServiceClose(mouseDev);
353                                 }
354                                 else
355                                         Con_Print("Could not re-enable mouse acceleration (failed at IO_GetIOHandle).\n");
356                         }
357                 }
358 #endif
359 #endif
360         }
361         if (vid_usinghidecursor != hidecursor)
362         {
363                 vid_usinghidecursor = hidecursor;
364                 SDL_ShowCursor( hidecursor ? SDL_DISABLE : SDL_ENABLE);
365         }
366 }
367
368 static double IN_JoystickGetAxis(SDL_Joystick *joy, int axis, double sensitivity, double deadzone)
369 {
370         double value;
371         if (axis < 0 || axis >= SDL_JoystickNumAxes(joy))
372                 return 0; // no such axis on this joystick
373         value = SDL_JoystickGetAxis(joy, axis) * (1.0 / 32767.0);
374         value = bound(-1, value, 1);
375         if (fabs(value) < deadzone)
376                 return 0; // within deadzone around center
377         return value * sensitivity;
378 }
379
380 /////////////////////
381 // Joystick axis keyevents
382 // a sort of hack emulating Arrow keys for joystick axises
383 // as some drives dont send such keyevents for them
384 // additionally we should block drivers that do send arrow keyevents to prevent double events
385 ////
386
387 static void IN_JoystickKeyeventForAxis(SDL_Joystick *joy, int axis, int key_pos, int key_neg)
388 {
389         double joytime;
390
391         if (axis < 0 || axis >= SDL_JoystickNumAxes(joy))
392                 return; // no such axis on this joystick
393
394         joytime = Sys_DoubleTime();
395         // no key event, continuous keydown event
396         if (joy_axescache[axis].move == joy_axescache[axis].oldmove)
397         {
398                 if (joy_axescache[axis].move != 0 && joytime > joy_axescache[axis].keytime)
399                 {
400                         //Con_Printf("joy %s %i %f\n", Key_KeynumToString((joy_axescache[axis].move > 0) ? key_pos : key_neg), 1, cl.time);
401                         Key_Event((joy_axescache[axis].move > 0) ? key_pos : key_neg, 0, 1);
402                         joy_axescache[axis].keytime = joytime + 0.5 / 20;
403                 }
404                 return;
405         }
406         // generate key up event
407         if (joy_axescache[axis].oldmove)
408         {
409                 //Con_Printf("joy %s %i %f\n", Key_KeynumToString((joy_axescache[axis].oldmove > 0) ? key_pos : key_neg), 1, cl.time);
410                 Key_Event((joy_axescache[axis].oldmove > 0) ? key_pos : key_neg, 0, 0);
411         }
412         // generate key down event
413         if (joy_axescache[axis].move)
414         {
415                 //Con_Printf("joy %s %i %f\n", Key_KeynumToString((joy_axescache[axis].move > 0) ? key_pos : key_neg), 1, cl.time);
416                 Key_Event((joy_axescache[axis].move > 0) ? key_pos : key_neg, 0, 1);
417                 joy_axescache[axis].keytime = joytime + 0.5;
418         }
419 }
420
421 static qboolean IN_JoystickBlockDoubledKeyEvents(int keycode)
422 {
423         if (!joy_axiskeyevents.integer)
424                 return false;
425
426         // block keyevent if it's going to be provided by joystick keyevent system
427         if (vid_numjoysticks && joy_enable.integer && joy_index.integer >= 0 && joy_index.integer < vid_numjoysticks)
428         {
429                 SDL_Joystick *joy = vid_joysticks[joy_index.integer];
430
431                 if (keycode == K_UPARROW || keycode == K_DOWNARROW)
432                         if (IN_JoystickGetAxis(joy, joy_axisforward.integer, 1, 0.01) || joy_axescache[joy_axisforward.integer].move || joy_axescache[joy_axisforward.integer].oldmove)
433                                 return true;
434                 if (keycode == K_RIGHTARROW || keycode == K_LEFTARROW)
435                         if (IN_JoystickGetAxis(joy, joy_axisside.integer, 1, 0.01) || joy_axescache[joy_axisside.integer].move || joy_axescache[joy_axisside.integer].oldmove)
436                                 return true;
437         }
438
439         return false;
440 }
441
442 /////////////////////
443 // Movement handling
444 ////
445
446 void IN_Move( void )
447 {
448         int j;
449         static int old_x = 0, old_y = 0;
450         static int stuck = 0;
451         int x, y, numaxes, numballs;
452
453         if (vid_usingmouse)
454         {
455                 if(vid_stick_mouse.integer)
456                 {
457                         // have the mouse stuck in the middle, example use: prevent expose effect of beryl during the game when not using
458                         // window grabbing. --blub
459
460                         // we need 2 frames to initialize the center position
461                         if(!stuck)
462                         {
463                                 SDL_WarpMouse(win_half_width, win_half_height);
464                                 SDL_GetMouseState(&x, &y);
465                                 SDL_GetRelativeMouseState(&x, &y);
466                                 ++stuck;
467                         } else {
468                                 SDL_GetRelativeMouseState(&x, &y);
469                                 in_mouse_x = x + old_x;
470                                 in_mouse_y = y + old_y;
471                                 SDL_GetMouseState(&x, &y);
472                                 old_x = x - win_half_width;
473                                 old_y = y - win_half_height;
474                                 SDL_WarpMouse(win_half_width, win_half_height);
475                         }
476                 } else {
477                         SDL_GetRelativeMouseState( &x, &y );
478                         in_mouse_x = x;
479                         in_mouse_y = y;
480                 }
481         }
482
483         SDL_GetMouseState(&x, &y);
484         in_windowmouse_x = x;
485         in_windowmouse_y = y;
486
487         if (vid_numjoysticks && joy_enable.integer && joy_index.integer >= 0 && joy_index.integer < vid_numjoysticks)
488         {
489                 SDL_Joystick *joy = vid_joysticks[joy_index.integer];
490
491                 // balls convert to mousemove
492                 numballs = SDL_JoystickNumBalls(joy);
493                 for (j = 0;j < numballs;j++)
494                 {
495                         SDL_JoystickGetBall(joy, j, &x, &y);
496                         in_mouse_x += x;
497                         in_mouse_y += y;
498                 }
499
500                 // axes
501                 cl.cmd.forwardmove += IN_JoystickGetAxis(joy, joy_axisforward.integer, joy_sensitivityforward.value, joy_deadzoneforward.value) * cl_forwardspeed.value;
502                 cl.cmd.sidemove    += IN_JoystickGetAxis(joy, joy_axisside.integer, joy_sensitivityside.value, joy_deadzoneside.value) * cl_sidespeed.value;
503                 cl.cmd.upmove      += IN_JoystickGetAxis(joy, joy_axisup.integer, joy_sensitivityup.value, joy_deadzoneup.value) * cl_upspeed.value;
504                 cl.viewangles[0]   += IN_JoystickGetAxis(joy, joy_axispitch.integer, joy_sensitivitypitch.value, joy_deadzonepitch.value) * cl.realframetime * cl_pitchspeed.value;
505                 cl.viewangles[1]   += IN_JoystickGetAxis(joy, joy_axisyaw.integer, joy_sensitivityyaw.value, joy_deadzoneyaw.value) * cl.realframetime * cl_yawspeed.value;
506                 //cl.viewangles[2]   += IN_JoystickGetAxis(joy, joy_axisroll.integer, joy_sensitivityroll.value, joy_deadzoneroll.value) * cl.realframetime * cl_rollspeed.value;
507         
508                 // cache state of axes to emulate button events for them
509                 numaxes = min(MAX_JOYSTICK_AXES, SDL_JoystickNumAxes(joy));
510                 for (j = 0; j < numaxes; j++)
511                 {
512                         joy_axescache[j].oldmove = joy_axescache[j].move;
513                         joy_axescache[j].move = IN_JoystickGetAxis(joy, j, 1, 0.01);
514                 }
515
516                 // run keyevents
517                 if (joy_axiskeyevents.integer)
518                 {
519                         IN_JoystickKeyeventForAxis(joy, joy_axisforward.integer, K_DOWNARROW, K_UPARROW);
520                         IN_JoystickKeyeventForAxis(joy, joy_axisside.integer, K_RIGHTARROW, K_LEFTARROW);
521                 }
522         }
523 }
524
525 /////////////////////
526 // Message Handling
527 ////
528
529 #if SDL_MAJOR_VERSION == 1 && SDL_MINOR_VERSION == 2
530 static int Sys_EventFilter( SDL_Event *event )
531 {
532         //TODO: Add a quit query in linux, too - though linux user are more likely to know what they do
533         if (event->type == SDL_QUIT)
534         {
535 #ifdef WIN32
536                 if (MessageBox( NULL, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION ) == IDNO)
537                         return 0;
538 #endif
539         }
540         return 1;
541 }
542 #endif
543
544 #ifdef SDL_R_RESTART
545 static qboolean sdl_needs_restart;
546 static void sdl_start(void)
547 {
548 }
549 static void sdl_shutdown(void)
550 {
551         sdl_needs_restart = false;
552 }
553 static void sdl_newmap(void)
554 {
555 }
556 #endif
557
558 static keynum_t buttonremap[18] =
559 {
560         K_MOUSE1,
561         K_MOUSE3,
562         K_MOUSE2,
563         K_MWHEELUP,
564         K_MWHEELDOWN,
565         K_MOUSE4,
566         K_MOUSE5,
567         K_MOUSE6,
568         K_MOUSE7,
569         K_MOUSE8,
570         K_MOUSE9,
571         K_MOUSE10,
572         K_MOUSE11,
573         K_MOUSE12,
574         K_MOUSE13,
575         K_MOUSE14,
576         K_MOUSE15,
577         K_MOUSE16,
578 };
579
580 void Sys_SendKeyEvents( void )
581 {
582         static qboolean sound_active = true;
583         int keycode;
584         SDL_Event event;
585
586         while( SDL_PollEvent( &event ) )
587                 switch( event.type ) {
588                         case SDL_QUIT:
589 #if !(SDL_MAJOR_VERSION == 1 && SDL_MINOR_VERSION == 2)
590 #ifdef WIN32
591                                 if (MessageBox( NULL, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION ) == IDNO)
592                                         return 0;
593 #endif
594 #endif
595                                 Sys_Quit(0);
596                                 break;
597                         case SDL_KEYDOWN:
598                         case SDL_KEYUP:
599                                 keycode = MapKey(event.key.keysym.sym);
600                                 if (!IN_JoystickBlockDoubledKeyEvents(keycode))
601                                         Key_Event(keycode, event.key.keysym.unicode, (event.key.state == SDL_PRESSED));
602                                 break;
603                         case SDL_ACTIVEEVENT:
604                                 if( event.active.state & SDL_APPACTIVE )
605                                 {
606                                         if( event.active.gain )
607                                                 vid_hidden = false;
608                                         else
609                                                 vid_hidden = true;
610                                 }
611                                 break;
612                         case SDL_MOUSEBUTTONDOWN:
613                         case SDL_MOUSEBUTTONUP:
614                                 if (event.button.button <= 18)
615                                         Key_Event( buttonremap[event.button.button - 1], 0, event.button.state == SDL_PRESSED );
616                                 break;
617                         case SDL_JOYBUTTONDOWN:
618                                 if (!joy_enable.integer)
619                                         break; // ignore down events if joystick has been disabled
620                         case SDL_JOYBUTTONUP:
621                                 if (event.jbutton.button < 48)
622                                         Key_Event( event.jbutton.button + (event.jbutton.button < 16 ? K_JOY1 : K_AUX1 - 16), 0, (event.jbutton.state == SDL_PRESSED) );
623                                 break;
624                         case SDL_VIDEORESIZE:
625                                 if(vid_resizable.integer < 2)
626                                 {
627                                         vid.width = event.resize.w;
628                                         vid.height = event.resize.h;
629                                         SDL_SetVideoMode(vid.width, vid.height, video_bpp, video_flags);
630                                         if (vid_softsurface)
631                                         {
632                                                 SDL_FreeSurface(vid_softsurface);
633                                                 vid_softsurface = SDL_CreateRGBSurface(SDL_SWSURFACE, vid.width, vid.height, 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
634                                                 vid.softpixels = (unsigned int *)vid_softsurface->pixels;
635                                                 SDL_SetAlpha(vid_softsurface, 0, 255);
636                                                 if (vid.softdepthpixels)
637                                                         free(vid.softdepthpixels);
638                                                 vid.softdepthpixels = (unsigned int*)calloc(1, vid.width * vid.height * 4);
639                                         }
640 #ifdef SDL_R_RESTART
641                                         // better not call R_Modules_Restart from here directly, as this may wreak havoc...
642                                         // so, let's better queue it for next frame
643                                         if(!sdl_needs_restart)
644                                         {
645                                                 Cbuf_AddText("\nr_restart\n");
646                                                 sdl_needs_restart = true;
647                                         }
648 #endif
649                                 }
650                                 break;
651                 }
652
653         // enable/disable sound on focus gain/loss
654         if ((!vid_hidden && vid_activewindow) || !snd_mutewhenidle.integer)
655         {
656                 if (!sound_active)
657                 {
658                         S_UnblockSound ();
659                         sound_active = true;
660                 }
661         }
662         else
663         {
664                 if (sound_active)
665                 {
666                         S_BlockSound ();
667                         sound_active = false;
668                 }
669         }
670 }
671
672 /////////////////
673 // Video system
674 ////
675
676 #ifdef __IPHONEOS__
677 //#include <SDL_opengles.h>
678 #include <OpenGLES/ES2/gl.h>
679
680 GLboolean wrapglIsBuffer(GLuint buffer) {return glIsBuffer(buffer);}
681 GLboolean wrapglIsEnabled(GLenum cap) {return glIsEnabled(cap);}
682 GLboolean wrapglIsFramebuffer(GLuint framebuffer) {return glIsFramebuffer(framebuffer);}
683 //GLboolean wrapglIsQuery(GLuint qid) {return glIsQuery(qid);}
684 GLboolean wrapglIsRenderbuffer(GLuint renderbuffer) {return glIsRenderbuffer(renderbuffer);}
685 //GLboolean wrapglUnmapBuffer(GLenum target) {return glUnmapBuffer(target);}
686 GLenum wrapglCheckFramebufferStatus(GLenum target) {return glCheckFramebufferStatus(target);}
687 GLenum wrapglGetError(void) {return glGetError();}
688 GLuint wrapglCreateProgram(void) {return glCreateProgram();}
689 GLuint wrapglCreateShader(GLenum shaderType) {return glCreateShader(shaderType);}
690 //GLuint wrapglGetHandle(GLenum pname) {return glGetHandle(pname);}
691 GLint wrapglGetAttribLocation(GLuint programObj, const GLchar *name) {return glGetAttribLocation(programObj, name);}
692 GLint wrapglGetUniformLocation(GLuint programObj, const GLchar *name) {return glGetUniformLocation(programObj, name);}
693 //GLvoid* wrapglMapBuffer(GLenum target, GLenum access) {return glMapBuffer(target, access);}
694 const GLubyte* wrapglGetString(GLenum name) {return glGetString(name);}
695 //void wrapglActiveStencilFace(GLenum e) {glActiveStencilFace(e);}
696 void wrapglActiveTexture(GLenum e) {glActiveTexture(e);}
697 void wrapglAlphaFunc(GLenum func, GLclampf ref) {Con_Printf("glAlphaFunc(func, ref)\n");}
698 //void wrapglArrayElement(GLint i) {glArrayElement(i);}
699 void wrapglAttachShader(GLuint containerObj, GLuint obj) {glAttachShader(containerObj, obj);}
700 //void wrapglBegin(GLenum mode) {glBegin(mode);}
701 //void wrapglBeginQuery(GLenum target, GLuint qid) {glBeginQuery(target, qid);}
702 void wrapglBindAttribLocation(GLuint programObj, GLuint index, const GLchar *name) {glBindAttribLocation(programObj, index, name);}
703 void wrapglBindBuffer(GLenum target, GLuint buffer) {glBindBuffer(target, buffer);}
704 void wrapglBindFramebuffer(GLenum target, GLuint framebuffer) {glBindFramebuffer(target, framebuffer);}
705 void wrapglBindRenderbuffer(GLenum target, GLuint renderbuffer) {glBindRenderbuffer(target, renderbuffer);}
706 void wrapglBindTexture(GLenum target, GLuint texture) {glBindTexture(target, texture);}
707 void wrapglBlendEquation(GLenum e) {glBlendEquation(e);}
708 void wrapglBlendFunc(GLenum sfactor, GLenum dfactor) {glBlendFunc(sfactor, dfactor);}
709 void wrapglBufferData(GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage) {glBufferData(target, size, data, usage);}
710 void wrapglBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data) {glBufferSubData(target, offset, size, data);}
711 void wrapglClear(GLbitfield mask) {glClear(mask);}
712 void wrapglClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) {glClearColor(red, green, blue, alpha);}
713 void wrapglClearDepth(GLclampd depth) {glClearDepthf((float)depth);}
714 void wrapglClearStencil(GLint s) {glClearStencil(s);}
715 void wrapglClientActiveTexture(GLenum target) {Con_Printf("glClientActiveTexture(target)\n");}
716 void wrapglColor4f(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) {Con_Printf("glColor4f(red, green, blue, alpha)\n");}
717 void wrapglColor4ub(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha) {Con_Printf("glColor4ub(red, green, blue, alpha)\n");}
718 void wrapglColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) {Con_Printf("glColorMask(red, green, blue, alpha)\n");}
719 void wrapglColorPointer(GLint size, GLenum type, GLsizei stride, const GLvoid *ptr) {Con_Printf("glColorPointer(size, type, stride, ptr)\n");}
720 void wrapglCompileShader(GLuint shaderObj) {glCompileShader(shaderObj);}
721 void wrapglCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border,  GLsizei imageSize, const void *data) {glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data);}
722 //void wrapglCompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data) {glCompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, data);}
723 void wrapglCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data) {glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data);}
724 //void wrapglCompressedTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data) {glCompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data);}
725 void wrapglCopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border) {glCopyTexImage2D(target, level, internalformat, x, y, width, height, border);}
726 void wrapglCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height) {glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);}
727 //void wrapglCopyTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height) {glCopyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height);}
728 void wrapglCullFace(GLenum mode) {glCullFace(mode);}
729 void wrapglDeleteBuffers(GLsizei n, const GLuint *buffers) {glDeleteBuffers(n, buffers);}
730 void wrapglDeleteFramebuffers(GLsizei n, const GLuint *framebuffers) {glDeleteFramebuffers(n, framebuffers);}
731 void wrapglDeleteShader(GLuint obj) {glDeleteShader(obj);}
732 void wrapglDeleteProgram(GLuint obj) {glDeleteProgram(obj);}
733 //void wrapglDeleteQueries(GLsizei n, const GLuint *ids) {glDeleteQueries(n, ids);}
734 void wrapglDeleteRenderbuffers(GLsizei n, const GLuint *renderbuffers) {glDeleteRenderbuffers(n, renderbuffers);}
735 void wrapglDeleteTextures(GLsizei n, const GLuint *textures) {glDeleteTextures(n, textures);}
736 void wrapglDepthFunc(GLenum func) {glDepthFunc(func);}
737 void wrapglDepthMask(GLboolean flag) {glDepthMask(flag);}
738 void wrapglDepthRange(GLclampd near_val, GLclampd far_val) {glDepthRangef((float)near_val, (float)far_val);}
739 void wrapglDetachShader(GLuint containerObj, GLuint attachedObj) {glDetachShader(containerObj, attachedObj);}
740 void wrapglDisable(GLenum cap) {glDisable(cap);}
741 void wrapglDisableClientState(GLenum cap) {Con_Printf("glDisableClientState(cap)\n");}
742 void wrapglDisableVertexAttribArray(GLuint index) {glDisableVertexAttribArray(index);}
743 void wrapglDrawArrays(GLenum mode, GLint first, GLsizei count) {glDrawArrays(mode, first, count);}
744 //void wrapglDrawBuffer(GLenum mode) {glDrawBuffer(mode);}
745 //void wrapglDrawBuffers(GLsizei n, const GLenum *bufs) {glDrawBuffers(n, bufs);}
746 void wrapglDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices) {glDrawElements(mode, count, type, indices);}
747 //void wrapglDrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices) {glDrawRangeElements(mode, start, end, count, type, indices);}
748 //void wrapglDrawRangeElementsEXT(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices) {glDrawRangeElements(mode, start, end, count, type, indices);}
749 void wrapglEnable(GLenum cap) {glEnable(cap);}
750 void wrapglEnableClientState(GLenum cap) {Con_Printf("glEnableClientState(cap)\n");}
751 void wrapglEnableVertexAttribArray(GLuint index) {glEnableVertexAttribArray(index);}
752 //void wrapglEnd(void) {glEnd();}
753 //void wrapglEndQuery(GLenum target) {glEndQuery(target);}
754 void wrapglFinish(void) {glFinish();}
755 void wrapglFlush(void) {glFlush();}
756 void wrapglFramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer) {glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer);}
757 void wrapglFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) {glFramebufferTexture2D(target, attachment, textarget, texture, level);}
758 //void wrapglFramebufferTexture3D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset) {glFramebufferTexture3D();}
759 void wrapglGenBuffers(GLsizei n, GLuint *buffers) {glGenBuffers(n, buffers);}
760 void wrapglGenFramebuffers(GLsizei n, GLuint *framebuffers) {glGenFramebuffers(n, framebuffers);}
761 //void wrapglGenQueries(GLsizei n, GLuint *ids) {glGenQueries(n, ids);}
762 void wrapglGenRenderbuffers(GLsizei n, GLuint *renderbuffers) {glGenRenderbuffers(n, renderbuffers);}
763 void wrapglGenTextures(GLsizei n, GLuint *textures) {glGenTextures(n, textures);}
764 void wrapglGenerateMipmap(GLenum target) {glGenerateMipmap(target);}
765 void wrapglGetActiveAttrib(GLuint programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLchar *name) {glGetActiveAttrib(programObj, index, maxLength, length, size, type, name);}
766 void wrapglGetActiveUniform(GLuint programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLchar *name) {glGetActiveUniform(programObj, index, maxLength, length, size, type, name);}
767 void wrapglGetAttachedShaders(GLuint containerObj, GLsizei maxCount, GLsizei *count, GLuint *obj) {glGetAttachedShaders(containerObj, maxCount, count, obj);}
768 void wrapglGetBooleanv(GLenum pname, GLboolean *params) {glGetBooleanv(pname, params);}
769 //void wrapglGetCompressedTexImage(GLenum target, GLint lod, void *img) {glGetCompressedTexImage(target, lod, img);}
770 //void wrapglGetDoublev(GLenum pname, GLdouble *params) {glGetDoublev(pname, params);}
771 void wrapglGetFloatv(GLenum pname, GLfloat *params) {glGetFloatv(pname, params);}
772 void wrapglGetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLint *params) {glGetFramebufferAttachmentParameteriv(target, attachment, pname, params);}
773 void wrapglGetShaderInfoLog(GLuint obj, GLsizei maxLength, GLsizei *length, GLchar *infoLog) {glGetShaderInfoLog(obj, maxLength, length, infoLog);}
774 void wrapglGetProgramInfoLog(GLuint obj, GLsizei maxLength, GLsizei *length, GLchar *infoLog) {glGetProgramInfoLog(obj, maxLength, length, infoLog);}
775 void wrapglGetIntegerv(GLenum pname, GLint *params) {glGetIntegerv(pname, params);}
776 void wrapglGetShaderiv(GLuint obj, GLenum pname, GLint *params) {glGetShaderiv(obj, pname, params);}
777 void wrapglGetProgramiv(GLuint obj, GLenum pname, GLint *params) {glGetProgramiv(obj, pname, params);}
778 //void wrapglGetQueryObjectiv(GLuint qid, GLenum pname, GLint *params) {glGetQueryObjectiv(qid, pname, params);}
779 //void wrapglGetQueryObjectuiv(GLuint qid, GLenum pname, GLuint *params) {glGetQueryObjectuiv(qid, pname, params);}
780 //void wrapglGetQueryiv(GLenum target, GLenum pname, GLint *params) {glGetQueryiv(target, pname, params);}
781 void wrapglGetRenderbufferParameteriv(GLenum target, GLenum pname, GLint *params) {glGetRenderbufferParameteriv(target, pname, params);}
782 void wrapglGetShaderSource(GLuint obj, GLsizei maxLength, GLsizei *length, GLchar *source) {glGetShaderSource(obj, maxLength, length, source);}
783 //void wrapglGetTexImage(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels) {glGetTexImage(target, level, format, type, pixels);}
784 //void wrapglGetTexLevelParameterfv(GLenum target, GLint level, GLenum pname, GLfloat *params) {glGetTexLevelParameterfv(target, level, pname, params);}
785 //void wrapglGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLint *params) {glGetTexLevelParameteriv(target, level, pname, params);}
786 void wrapglGetTexParameterfv(GLenum target, GLenum pname, GLfloat *params) {glGetTexParameterfv(target, pname, params);}
787 void wrapglGetTexParameteriv(GLenum target, GLenum pname, GLint *params) {glGetTexParameteriv(target, pname, params);}
788 void wrapglGetUniformfv(GLuint programObj, GLint location, GLfloat *params) {glGetUniformfv(programObj, location, params);}
789 void wrapglGetUniformiv(GLuint programObj, GLint location, GLint *params) {glGetUniformiv(programObj, location, params);}
790 void wrapglHint(GLenum target, GLenum mode) {glHint(target, mode);}
791 void wrapglLineWidth(GLfloat width) {glLineWidth(width);}
792 void wrapglLinkProgram(GLuint programObj) {glLinkProgram(programObj);}
793 void wrapglLoadIdentity(void) {Con_Printf("glLoadIdentity()\n");}
794 void wrapglLoadMatrixf(const GLfloat *m) {Con_Printf("glLoadMatrixf(m)\n");}
795 void wrapglMatrixMode(GLenum mode) {Con_Printf("glMatrixMode(mode)\n");}
796 void wrapglMultiTexCoord1f(GLenum target, GLfloat s) {Con_Printf("glMultiTexCoord1f(target, s)\n");}
797 void wrapglMultiTexCoord2f(GLenum target, GLfloat s, GLfloat t) {Con_Printf("glMultiTexCoord2f(target, s, t)\n");}
798 void wrapglMultiTexCoord3f(GLenum target, GLfloat s, GLfloat t, GLfloat r) {Con_Printf("glMultiTexCoord3f(target, s, t, r)\n");}
799 void wrapglMultiTexCoord4f(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q) {Con_Printf("glMultiTexCoord4f(target, s, t, r, q)\n");}
800 void wrapglNormalPointer(GLenum type, GLsizei stride, const GLvoid *ptr) {Con_Printf("glNormalPointer(type, stride, ptr)\n");}
801 void wrapglPixelStorei(GLenum pname, GLint param) {glPixelStorei(pname, param);}
802 void wrapglPointSize(GLfloat size) {Con_Printf("glPointSize(size)\n");}
803 void wrapglPolygonMode(GLenum face, GLenum mode) {Con_Printf("glPolygonMode(face, mode)\n");}
804 void wrapglPolygonOffset(GLfloat factor, GLfloat units) {Con_Printf("glPolygonOffset(factor, units)\n");}
805 void wrapglPolygonStipple(const GLubyte *mask) {Con_Printf("glPolygonStipple(mask)\n");}
806 void wrapglReadBuffer(GLenum mode) {Con_Printf("glReadBuffer(mode)\n");}
807 void wrapglReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels) {glReadPixels(x, y, width, height, format, type, pixels);}
808 void wrapglRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height) {glRenderbufferStorage(target, internalformat, width, height);}
809 void wrapglScissor(GLint x, GLint y, GLsizei width, GLsizei height) {glScissor(x, y, width, height);}
810 void wrapglShaderSource(GLuint shaderObj, GLsizei count, const GLchar **string, const GLint *length) {glShaderSource(shaderObj, count, string, length);}
811 void wrapglStencilFunc(GLenum func, GLint ref, GLuint mask) {glStencilFunc(func, ref, mask);}
812 void wrapglStencilFuncSeparate(GLenum func1, GLenum func2, GLint ref, GLuint mask) {glStencilFuncSeparate(func1, func2, ref, mask);}
813 void wrapglStencilMask(GLuint mask) {glStencilMask(mask);}
814 void wrapglStencilOp(GLenum fail, GLenum zfail, GLenum zpass) {glStencilOp(fail, zfail, zpass);}
815 void wrapglStencilOpSeparate(GLenum e1, GLenum e2, GLenum e3, GLenum e4) {glStencilOpSeparate(e1, e2, e3, e4);}
816 //void wrapglTexCoord1f(GLfloat s) {glTexCoord1f(s);}
817 //void wrapglTexCoord2f(GLfloat s, GLfloat t) {glTexCoord2f(s, t);}
818 //void wrapglTexCoord3f(GLfloat s, GLfloat t, GLfloat r) {glTexCoord3f(s, t, r);}
819 //void wrapglTexCoord4f(GLfloat s, GLfloat t, GLfloat r, GLfloat q) {glTexCoord4f(s, t, r, q);}
820 //void wrapglTexCoordPointer(GLint size, GLenum type, GLsizei stride, const GLvoid *ptr) {glTexCoordPointer(size, type, stride, ptr);}
821 //void wrapglTexEnvf(GLenum target, GLenum pname, GLfloat param) {glTexEnvf(target, pname, param);}
822 //void wrapglTexEnvfv(GLenum target, GLenum pname, const GLfloat *params) {glTexEnvfv(target, pname, params);}
823 //void wrapglTexEnvi(GLenum target, GLenum pname, GLint param) {glTexEnvi(target, pname, param);}
824 void wrapglTexImage2D(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels) {glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels);}
825 //void wrapglTexImage3D(GLenum target, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels) {glTexImage3D(target, level, internalformat, width, height, depth, border, format, type, pixels);}
826 void wrapglTexParameterf(GLenum target, GLenum pname, GLfloat param) {glTexParameterf(target, pname, param);}
827 void wrapglTexParameterfv(GLenum target, GLenum pname, GLfloat *params) {glTexParameterfv(target, pname, params);}
828 void wrapglTexParameteri(GLenum target, GLenum pname, GLint param) {glTexParameteri(target, pname, param);}
829 void wrapglTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels) {glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);}
830 //void wrapglTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels) {glTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);}
831 void wrapglUniform1f(GLint location, GLfloat v0) {glUniform1f(location, v0);}
832 void wrapglUniform1fv(GLint location, GLsizei count, const GLfloat *value) {glUniform1fv(location, count, value);}
833 void wrapglUniform1i(GLint location, GLint v0) {glUniform1i(location, v0);}
834 void wrapglUniform1iv(GLint location, GLsizei count, const GLint *value) {glUniform1iv(location, count, value);}
835 void wrapglUniform2f(GLint location, GLfloat v0, GLfloat v1) {glUniform2f(location, v0, v1);}
836 void wrapglUniform2fv(GLint location, GLsizei count, const GLfloat *value) {glUniform2fv(location, count, value);}
837 void wrapglUniform2i(GLint location, GLint v0, GLint v1) {glUniform2i(location, v0, v1);}
838 void wrapglUniform2iv(GLint location, GLsizei count, const GLint *value) {glUniform2iv(location, count, value);}
839 void wrapglUniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2) {glUniform3f(location, v0, v1, v2);}
840 void wrapglUniform3fv(GLint location, GLsizei count, const GLfloat *value) {glUniform3fv(location, count, value);}
841 void wrapglUniform3i(GLint location, GLint v0, GLint v1, GLint v2) {glUniform3i(location, v0, v1, v2);}
842 void wrapglUniform3iv(GLint location, GLsizei count, const GLint *value) {glUniform3iv(location, count, value);}
843 void wrapglUniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) {glUniform4f(location, v0, v1, v2, v3);}
844 void wrapglUniform4fv(GLint location, GLsizei count, const GLfloat *value) {glUniform4fv(location, count, value);}
845 void wrapglUniform4i(GLint location, GLint v0, GLint v1, GLint v2, GLint v3) {glUniform4i(location, v0, v1, v2, v3);}
846 void wrapglUniform4iv(GLint location, GLsizei count, const GLint *value) {glUniform4iv(location, count, value);}
847 void wrapglUniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) {glUniformMatrix2fv(location, count, transpose, value);}
848 void wrapglUniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) {glUniformMatrix3fv(location, count, transpose, value);}
849 void wrapglUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) {glUniformMatrix4fv(location, count, transpose, value);}
850 void wrapglUseProgram(GLuint programObj) {glUseProgram(programObj);}
851 void wrapglValidateProgram(GLuint programObj) {glValidateProgram(programObj);}
852 //void wrapglVertex2f(GLfloat x, GLfloat y) {glVertex2f(x, y);}
853 //void wrapglVertex3f(GLfloat x, GLfloat y, GLfloat z) {glVertex3f(x, y, z);}
854 //void wrapglVertex4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w) {glVertex4f(x, y, z, w);}
855 void wrapglVertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) {glVertexAttribPointer(index, size, type, normalized, stride, pointer);}
856 void wrapglVertexPointer(GLint size, GLenum type, GLsizei stride, const GLvoid *ptr) {Con_Printf("glVertexPointer(size, type, stride, ptr)\n");}
857 void wrapglViewport(GLint x, GLint y, GLsizei width, GLsizei height) {glViewport(x, y, width, height);}
858
859 void GLES_Init(void)
860 {
861         qglIsBufferARB = wrapglIsBuffer;
862         qglIsEnabled = wrapglIsEnabled;
863         qglIsFramebufferEXT = wrapglIsFramebuffer;
864         qglIsQueryARB = wrapglIsQuery;
865         qglIsRenderbufferEXT = wrapglIsRenderbuffer;
866         qglUnmapBufferARB = wrapglUnmapBuffer;
867         qglCheckFramebufferStatusEXT = wrapglCheckFramebufferStatus;
868         qglGetError = wrapglGetError;
869         qglCreateProgram = wrapglCreateProgram;
870         qglCreateShader = wrapglCreateShader;
871 //      qglGetHandleARB = wrapglGetHandle;
872         qglGetAttribLocation = wrapglGetAttribLocation;
873         qglGetUniformLocation = wrapglGetUniformLocation;
874         qglMapBufferARB = wrapglMapBuffer;
875         qglGetString = wrapglGetString;
876         qglActiveStencilFaceEXT = wrapglActiveStencilFace;
877         qglActiveTexture = wrapglActiveTexture;
878         qglAlphaFunc = wrapglAlphaFunc;
879         qglArrayElement = wrapglArrayElement;
880         qglAttachShader = wrapglAttachShader;
881         qglBegin = wrapglBegin;
882         qglBeginQueryARB = wrapglBeginQuery;
883         qglBindAttribLocation = wrapglBindAttribLocation;
884         qglBindBufferARB = wrapglBindBuffer;
885         qglBindFramebufferEXT = wrapglBindFramebuffer;
886         qglBindRenderbufferEXT = wrapglBindRenderbuffer;
887         qglBindTexture = wrapglBindTexture;
888         qglBlendEquationEXT = wrapglBlendEquation;
889         qglBlendFunc = wrapglBlendFunc;
890         qglBufferDataARB = wrapglBufferData;
891         qglBufferSubDataARB = wrapglBufferSubData;
892         qglClear = wrapglClear;
893         qglClearColor = wrapglClearColor;
894         qglClearDepth = wrapglClearDepth;
895         qglClearStencil = wrapglClearStencil;
896         qglClientActiveTexture = wrapglClientActiveTexture;
897         qglColor4f = wrapglColor4f;
898         qglColor4ub = wrapglColor4ub;
899         qglColorMask = wrapglColorMask;
900         qglColorPointer = wrapglColorPointer;
901         qglCompileShader = wrapglCompileShader;
902         qglCompressedTexImage2DARB = wrapglCompressedTexImage2D;
903         qglCompressedTexImage3DARB = wrapglCompressedTexImage3D;
904         qglCompressedTexSubImage2DARB = wrapglCompressedTexSubImage2D;
905         qglCompressedTexSubImage3DARB = wrapglCompressedTexSubImage3D;
906         qglCopyTexImage2D = wrapglCopyTexImage2D;
907         qglCopyTexSubImage2D = wrapglCopyTexSubImage2D;
908         qglCopyTexSubImage3D = wrapglCopyTexSubImage3D;
909         qglCullFace = wrapglCullFace;
910         qglDeleteBuffersARB = wrapglDeleteBuffers;
911         qglDeleteFramebuffersEXT = wrapglDeleteFramebuffers;
912         qglDeleteProgram = wrapglDeleteProgram;
913         qglDeleteShader = wrapglDeleteShader;
914         qglDeleteQueriesARB = wrapglDeleteQueries;
915         qglDeleteRenderbuffersEXT = wrapglDeleteRenderbuffers;
916         qglDeleteTextures = wrapglDeleteTextures;
917         qglDepthFunc = wrapglDepthFunc;
918         qglDepthMask = wrapglDepthMask;
919         qglDepthRange = wrapglDepthRange;
920         qglDetachShader = wrapglDetachShader;
921         qglDisable = wrapglDisable;
922         qglDisableClientState = wrapglDisableClientState;
923         qglDisableVertexAttribArray = wrapglDisableVertexAttribArray;
924         qglDrawArrays = wrapglDrawArrays;
925         qglDrawBuffer = wrapglDrawBuffer;
926         qglDrawBuffersARB = wrapglDrawBuffers;
927         qglDrawElements = wrapglDrawElements;
928         qglDrawRangeElements = wrapglDrawRangeElements;
929         qglEnable = wrapglEnable;
930         qglEnableClientState = wrapglEnableClientState;
931         qglEnableVertexAttribArray = wrapglEnableVertexAttribArray;
932         qglEnd = wrapglEnd;
933         qglEndQueryARB = wrapglEndQuery;
934         qglFinish = wrapglFinish;
935         qglFlush = wrapglFlush;
936         qglFramebufferRenderbufferEXT = wrapglFramebufferRenderbuffer;
937         qglFramebufferTexture2DEXT = wrapglFramebufferTexture2D;
938         qglFramebufferTexture3DEXT = wrapglFramebufferTexture3D;
939         qglGenBuffersARB = wrapglGenBuffers;
940         qglGenFramebuffersEXT = wrapglGenFramebuffers;
941         qglGenQueriesARB = wrapglGenQueries;
942         qglGenRenderbuffersEXT = wrapglGenRenderbuffers;
943         qglGenTextures = wrapglGenTextures;
944         qglGenerateMipmapEXT = wrapglGenerateMipmap;
945         qglGetActiveAttrib = wrapglGetActiveAttrib;
946         qglGetActiveUniform = wrapglGetActiveUniform;
947         qglGetAttachedShaders = wrapglGetAttachedShaders;
948         qglGetBooleanv = wrapglGetBooleanv;
949         qglGetCompressedTexImageARB = wrapglGetCompressedTexImage;
950         qglGetDoublev = wrapglGetDoublev;
951         qglGetFloatv = wrapglGetFloatv;
952         qglGetFramebufferAttachmentParameterivEXT = wrapglGetFramebufferAttachmentParameteriv;
953         qglGetProgramInfoLog = wrapglGetProgramInfoLog;
954         qglGetShaderInfoLog = wrapglGetShaderInfoLog;
955         qglGetIntegerv = wrapglGetIntegerv;
956         qglGetShaderiv = wrapglGetShaderiv;
957         qglGetProgramiv = wrapglGetProgramiv;
958         qglGetQueryObjectivARB = wrapglGetQueryObjectiv;
959         qglGetQueryObjectuivARB = wrapglGetQueryObjectuiv;
960         qglGetQueryivARB = wrapglGetQueryiv;
961         qglGetRenderbufferParameterivEXT = wrapglGetRenderbufferParameteriv;
962         qglGetShaderSource = wrapglGetShaderSource;
963         qglGetTexImage = wrapglGetTexImage;
964         qglGetTexLevelParameterfv = wrapglGetTexLevelParameterfv;
965         qglGetTexLevelParameteriv = wrapglGetTexLevelParameteriv;
966         qglGetTexParameterfv = wrapglGetTexParameterfv;
967         qglGetTexParameteriv = wrapglGetTexParameteriv;
968         qglGetUniformfv = wrapglGetUniformfv;
969         qglGetUniformiv = wrapglGetUniformiv;
970         qglHint = wrapglHint;
971         qglLineWidth = wrapglLineWidth;
972         qglLinkProgram = wrapglLinkProgram;
973         qglLoadIdentity = wrapglLoadIdentity;
974         qglLoadMatrixf = wrapglLoadMatrixf;
975         qglMatrixMode = wrapglMatrixMode;
976         qglMultiTexCoord1f = wrapglMultiTexCoord1f;
977         qglMultiTexCoord2f = wrapglMultiTexCoord2f;
978         qglMultiTexCoord3f = wrapglMultiTexCoord3f;
979         qglMultiTexCoord4f = wrapglMultiTexCoord4f;
980         qglNormalPointer = wrapglNormalPointer;
981         qglPixelStorei = wrapglPixelStorei;
982         qglPointSize = wrapglPointSize;
983         qglPolygonMode = wrapglPolygonMode;
984         qglPolygonOffset = wrapglPolygonOffset;
985         qglPolygonStipple = wrapglPolygonStipple;
986         qglReadBuffer = wrapglReadBuffer;
987         qglReadPixels = wrapglReadPixels;
988         qglRenderbufferStorageEXT = wrapglRenderbufferStorage;
989         qglScissor = wrapglScissor;
990         qglShaderSource = wrapglShaderSource;
991         qglStencilFunc = wrapglStencilFunc;
992         qglStencilFuncSeparate = wrapglStencilFuncSeparate;
993         qglStencilMask = wrapglStencilMask;
994         qglStencilOp = wrapglStencilOp;
995         qglStencilOpSeparate = wrapglStencilOpSeparate;
996         qglTexCoord1f = wrapglTexCoord1f;
997         qglTexCoord2f = wrapglTexCoord2f;
998         qglTexCoord3f = wrapglTexCoord3f;
999         qglTexCoord4f = wrapglTexCoord4f;
1000         qglTexCoordPointer = wrapglTexCoordPointer;
1001         qglTexEnvf = wrapglTexEnvf;
1002         qglTexEnvfv = wrapglTexEnvfv;
1003         qglTexEnvi = wrapglTexEnvi;
1004         qglTexImage2D = wrapglTexImage2D;
1005         qglTexImage3D = wrapglTexImage3D;
1006         qglTexParameterf = wrapglTexParameterf;
1007         qglTexParameterfv = wrapglTexParameterfv;
1008         qglTexParameteri = wrapglTexParameteri;
1009         qglTexSubImage2D = wrapglTexSubImage2D;
1010         qglTexSubImage3D = wrapglTexSubImage3D;
1011         qglUniform1f = wrapglUniform1f;
1012         qglUniform1fv = wrapglUniform1fv;
1013         qglUniform1i = wrapglUniform1i;
1014         qglUniform1iv = wrapglUniform1iv;
1015         qglUniform2f = wrapglUniform2f;
1016         qglUniform2fv = wrapglUniform2fv;
1017         qglUniform2i = wrapglUniform2i;
1018         qglUniform2iv = wrapglUniform2iv;
1019         qglUniform3f = wrapglUniform3f;
1020         qglUniform3fv = wrapglUniform3fv;
1021         qglUniform3i = wrapglUniform3i;
1022         qglUniform3iv = wrapglUniform3iv;
1023         qglUniform4f = wrapglUniform4f;
1024         qglUniform4fv = wrapglUniform4fv;
1025         qglUniform4i = wrapglUniform4i;
1026         qglUniform4iv = wrapglUniform4iv;
1027         qglUniformMatrix2fv = wrapglUniformMatrix2fv;
1028         qglUniformMatrix3fv = wrapglUniformMatrix3fv;
1029         qglUniformMatrix4fv = wrapglUniformMatrix4fv;
1030         qglUseProgram = wrapglUseProgram;
1031         qglValidateProgram = wrapglValidateProgram;
1032         qglVertex2f = wrapglVertex2f;
1033         qglVertex3f = wrapglVertex3f;
1034         qglVertex4f = wrapglVertex4f;
1035         qglVertexAttribPointer = wrapglVertexAttribPointer;
1036         qglVertexPointer = wrapglVertexPointer;
1037         qglViewport = wrapglViewport;
1038
1039         gl_renderer = (const char *)qglGetString(GL_RENDERER);
1040         gl_vendor = (const char *)qglGetString(GL_VENDOR);
1041         gl_version = (const char *)qglGetString(GL_VERSION);
1042         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
1043         
1044         if (!gl_extensions)
1045                 gl_extensions = "";
1046         if (!gl_platformextensions)
1047                 gl_platformextensions = "";
1048         
1049         Con_Printf("GL_VENDOR: %s\n", gl_vendor);
1050         Con_Printf("GL_RENDERER: %s\n", gl_renderer);
1051         Con_Printf("GL_VERSION: %s\n", gl_version);
1052         Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
1053         Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
1054         
1055         // LordHavoc: report supported extensions
1056         Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
1057         
1058         vid.support.gl20shaders = true;
1059         vid.support.amd_texture_texture4 = false;
1060         vid.support.arb_depth_texture = false;
1061         vid.support.arb_draw_buffers = false;
1062         vid.support.arb_multitexture = false;
1063         vid.support.arb_occlusion_query = false;
1064         vid.support.arb_shadow = false;
1065         vid.support.arb_texture_compression = false; // different (vendor-specific) formats than on desktop OpenGL...
1066         vid.support.arb_texture_cube_map = true;
1067         vid.support.arb_texture_env_combine = false;
1068         vid.support.arb_texture_gather = false;
1069         vid.support.arb_texture_non_power_of_two = strstr(gl_extensions, "GL_OES_texture_npot") != NULL;
1070         vid.support.arb_vertex_buffer_object = true;
1071         vid.support.ati_separate_stencil = false;
1072         vid.support.ext_blend_minmax = false;
1073         vid.support.ext_blend_subtract = true;
1074         vid.support.ext_draw_range_elements = true;
1075         vid.support.ext_framebuffer_object = true;
1076         vid.support.ext_stencil_two_side = false;
1077         vid.support.ext_texture_3d = false;//SDL_GL_ExtensionSupported("GL_OES_texture_3D"); // iPhoneOS does not support 3D textures, odd...
1078         vid.support.ext_texture_compression_s3tc = false;
1079         vid.support.ext_texture_edge_clamp = true;
1080         vid.support.ext_texture_filter_anisotropic = false; // probably don't want to use it...
1081
1082         qglGetIntegerv(GL_MAX_TEXTURE_SIZE, (GLint*)&vid.maxtexturesize_2d);
1083         if (vid.support.ext_texture_filter_anisotropic)
1084                 qglGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, (GLint*)&vid.max_anisotropy);
1085         if (vid.support.arb_texture_cube_map)
1086                 qglGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB, (GLint*)&vid.maxtexturesize_cubemap);
1087         if (vid.support.ext_texture_3d)
1088                 qglGetIntegerv(GL_MAX_3D_TEXTURE_SIZE, (GLint*)&vid.maxtexturesize_3d);
1089
1090         // verify that 3d textures are really supported
1091         if (vid.support.ext_texture_3d && vid.maxtexturesize_3d < 32)
1092         {
1093                 vid.support.ext_texture_3d = false;
1094                 Con_Printf("GL_OES_texture_3d reported bogus GL_MAX_3D_TEXTURE_SIZE, disabled\n");
1095         }
1096
1097         vid.texunits = 4;
1098         vid.teximageunits = 8;
1099         vid.texarrayunits = 5;
1100         vid.texunits = bound(1, vid.texunits, MAX_TEXTUREUNITS);
1101         vid.teximageunits = bound(1, vid.teximageunits, MAX_TEXTUREUNITS);
1102         vid.texarrayunits = bound(1, vid.texarrayunits, MAX_TEXTUREUNITS);
1103         Con_DPrintf("Using GLES2.0 rendering path - %i texture matrix, %i texture images, %i texcoords%s\n", vid.texunits, vid.teximageunits, vid.texarrayunits, vid.support.ext_framebuffer_object ? ", shadowmapping supported" : "");
1104         vid.renderpath = RENDERPATH_GL20;
1105         vid.useinterleavedarrays = false;
1106
1107         // VorteX: set other info (maybe place them in VID_InitMode?)
1108         extern cvar_t gl_info_vendor;
1109         extern cvar_t gl_info_renderer;
1110         extern cvar_t gl_info_version;
1111         extern cvar_t gl_info_platform;
1112         extern cvar_t gl_info_driver;
1113         Cvar_SetQuick(&gl_info_vendor, gl_vendor);
1114         Cvar_SetQuick(&gl_info_renderer, gl_renderer);
1115         Cvar_SetQuick(&gl_info_version, gl_version);
1116         Cvar_SetQuick(&gl_info_platform, gl_platform ? gl_platform : "");
1117         Cvar_SetQuick(&gl_info_driver, gl_driver);
1118 }
1119 #endif
1120
1121 void *GL_GetProcAddress(const char *name)
1122 {
1123         void *p = NULL;
1124         p = SDL_GL_GetProcAddress(name);
1125         return p;
1126 }
1127
1128 #if SDL_MAJOR_VERSION == 1 && SDL_MINOR_VERSION == 2
1129 static int Sys_EventFilter( SDL_Event *event );
1130 #endif
1131 static qboolean vid_sdl_initjoysticksystem = false;
1132
1133 void VID_Init (void)
1134 {
1135 #ifndef __IPHONEOS__
1136 #ifdef MACOSX
1137         Cvar_RegisterVariable(&apple_mouse_noaccel);
1138 #endif
1139 #endif
1140         Cvar_RegisterVariable(&vid_soft);
1141         Cvar_RegisterVariable(&vid_soft_threads);
1142         Cvar_RegisterVariable(&joy_detected);
1143         Cvar_RegisterVariable(&joy_enable);
1144         Cvar_RegisterVariable(&joy_index);
1145         Cvar_RegisterVariable(&joy_axisforward);
1146         Cvar_RegisterVariable(&joy_axisside);
1147         Cvar_RegisterVariable(&joy_axisup);
1148         Cvar_RegisterVariable(&joy_axispitch);
1149         Cvar_RegisterVariable(&joy_axisyaw);
1150         //Cvar_RegisterVariable(&joy_axisroll);
1151         Cvar_RegisterVariable(&joy_deadzoneforward);
1152         Cvar_RegisterVariable(&joy_deadzoneside);
1153         Cvar_RegisterVariable(&joy_deadzoneup);
1154         Cvar_RegisterVariable(&joy_deadzonepitch);
1155         Cvar_RegisterVariable(&joy_deadzoneyaw);
1156         //Cvar_RegisterVariable(&joy_deadzoneroll);
1157         Cvar_RegisterVariable(&joy_sensitivityforward);
1158         Cvar_RegisterVariable(&joy_sensitivityside);
1159         Cvar_RegisterVariable(&joy_sensitivityup);
1160         Cvar_RegisterVariable(&joy_sensitivitypitch);
1161         Cvar_RegisterVariable(&joy_sensitivityyaw);
1162         //Cvar_RegisterVariable(&joy_sensitivityroll);
1163         Cvar_RegisterVariable(&joy_axiskeyevents);
1164         
1165 #ifdef SDL_R_RESTART
1166         R_RegisterModule("SDL", sdl_start, sdl_shutdown, sdl_newmap, NULL, NULL);
1167 #endif
1168
1169         if (SDL_Init(SDL_INIT_VIDEO) < 0)
1170                 Sys_Error ("Failed to init SDL video subsystem: %s", SDL_GetError());
1171         vid_sdl_initjoysticksystem = SDL_InitSubSystem(SDL_INIT_JOYSTICK) >= 0;
1172         if (vid_sdl_initjoysticksystem)
1173                 Con_Printf("Failed to init SDL joystick subsystem: %s\n", SDL_GetError());
1174         vid_isfullscreen = false;
1175 }
1176
1177 // set the icon (we dont use SDL here since it would be too much a PITA)
1178 #ifdef WIN32
1179 #include "resource.h"
1180 #include <SDL_syswm.h>
1181 static void VID_SetCaption(void)
1182 {
1183     SDL_SysWMinfo       info;
1184         HICON                   icon;
1185
1186         // set the caption
1187         SDL_WM_SetCaption( gamename, NULL );
1188
1189         // get the HWND handle
1190     SDL_VERSION( &info.version );
1191         if( !SDL_GetWMInfo( &info ) )
1192                 return;
1193
1194         icon = LoadIcon( GetModuleHandle( NULL ), MAKEINTRESOURCE( IDI_ICON1 ) );
1195 #ifndef _W64 //If Windows 64bit data types don't exist
1196 #ifndef SetClassLongPtr
1197 #define SetClassLongPtr SetClassLong
1198 #endif
1199 #ifndef GCLP_HICON
1200 #define GCLP_HICON GCL_HICON
1201 #endif
1202 #ifndef LONG_PTR
1203 #define LONG_PTR LONG
1204 #endif
1205 #endif
1206         SetClassLongPtr( info.window, GCLP_HICON, (LONG_PTR)icon );
1207 }
1208 static void VID_SetIcon_Pre(void)
1209 {
1210 }
1211 static void VID_SetIcon_Post(void)
1212 {
1213 }
1214 #else
1215 // Adding the OS independent XPM version --blub
1216 #include "darkplaces.xpm"
1217 #include "nexuiz.xpm"
1218 static SDL_Surface *icon = NULL;
1219 static void VID_SetIcon_Pre(void)
1220 {
1221         /*
1222          * Somewhat restricted XPM reader. Only supports XPMs saved by GIMP 2.4 at
1223          * default settings with less than 91 colors and transparency.
1224          */
1225
1226         int width, height, colors, isize, i, j;
1227         int thenone = -1;
1228         static SDL_Color palette[256];
1229         unsigned short palenc[256]; // store color id by char
1230         char *xpm;
1231         char **idata, *data;
1232         const SDL_version *version;
1233
1234         version = SDL_Linked_Version();
1235         // only use non-XPM icon support in SDL v1.3 and higher
1236         // SDL v1.2 does not support "smooth" transparency, and thus is better
1237         // off the xpm way
1238         if(version->major >= 2 || (version->major == 1 && version->minor >= 3))
1239         {
1240                 data = (char *) loadimagepixelsbgra("darkplaces-icon", false, false, false, NULL);
1241                 if(data)
1242                 {
1243                         unsigned int red = 0x00FF0000;
1244                         unsigned int green = 0x0000FF00;
1245                         unsigned int blue = 0x000000FF;
1246                         unsigned int alpha = 0xFF000000;
1247                         width = image_width;
1248                         height = image_height;
1249
1250                         // reallocate with malloc, as this is in tempmempool (do not want)
1251                         xpm = data;
1252                         data = malloc(width * height * 4);
1253                         memcpy(data, xpm, width * height * 4);
1254                         Mem_Free(xpm);
1255                         xpm = NULL;
1256
1257                         icon = SDL_CreateRGBSurface(SDL_SRCALPHA, width, height, 32, LittleLong(red), LittleLong(green), LittleLong(blue), LittleLong(alpha));
1258
1259                         if(icon == NULL) {
1260                                 Con_Printf(     "Failed to create surface for the window Icon!\n"
1261                                                 "%s\n", SDL_GetError());
1262                                 free(data);
1263                                 return;
1264                         }
1265
1266                         icon->pixels = data;
1267                 }
1268         }
1269
1270         // we only get here if non-XPM icon was missing, or SDL version is not
1271         // sufficient for transparent non-XPM icons
1272         if(!icon)
1273         {
1274                 xpm = (char *) FS_LoadFile("darkplaces-icon.xpm", tempmempool, false, NULL);
1275                 idata = NULL;
1276                 if(xpm)
1277                         idata = XPM_DecodeString(xpm);
1278                 if(!idata)
1279                         idata = ENGINE_ICON;
1280                 if(xpm)
1281                         Mem_Free(xpm);
1282
1283                 data = idata[0];
1284
1285                 if(sscanf(data, "%i %i %i %i", &width, &height, &colors, &isize) != 4)
1286                 {
1287                         // NOTE: Only 1-char colornames are supported
1288                         Con_Printf("Sorry, but this does not even look similar to an XPM.\n");
1289                         return;
1290                 }
1291
1292                 if(isize != 1)
1293                 {
1294                         // NOTE: Only 1-char colornames are supported
1295                         Con_Printf("This XPM's palette is either huge or idiotically unoptimized. It's key size is %i\n", isize);
1296                         return;
1297                 }
1298
1299                 for(i = 0; i < colors; ++i)
1300                 {
1301                         unsigned int r, g, b;
1302                         char idx;
1303
1304                         if(sscanf(idata[i+1], "%c c #%02x%02x%02x", &idx, &r, &g, &b) != 4)
1305                         {
1306                                 char foo[2];
1307                                 if(sscanf(idata[i+1], "%c c Non%1[e]", &idx, foo) != 2) // I take the DailyWTF credit for this. --div0
1308                                 {
1309                                         Con_Printf("This XPM's palette looks odd. Can't continue.\n");
1310                                         return;
1311                                 }
1312                                 else
1313                                 {
1314                                         palette[i].r = 255; // color key
1315                                         palette[i].g = 0;
1316                                         palette[i].b = 255;
1317                                         thenone = i; // weeeee
1318                                 }
1319                         }
1320                         else
1321                         {
1322                                 palette[i].r = r - (r == 255 && g == 0 && b == 255); // change 255/0/255 pink to 254/0/255 for color key
1323                                 palette[i].g = g;
1324                                 palette[i].b = b;
1325                         }
1326
1327                         palenc[(unsigned char) idx] = i;
1328                 }
1329
1330                 // allocate the image data
1331                 data = (char*) malloc(width*height);
1332
1333                 for(j = 0; j < height; ++j)
1334                 {
1335                         for(i = 0; i < width; ++i)
1336                         {
1337                                 // casting to the safest possible datatypes ^^
1338                                 data[j * width + i] = palenc[((unsigned char*)idata[colors+j+1])[i]];
1339                         }
1340                 }
1341
1342                 if(icon != NULL)
1343                 {
1344                         // SDL_FreeSurface should free the data too
1345                         // but for completeness' sake...
1346                         if(icon->flags & SDL_PREALLOC)
1347                         {
1348                                 free(icon->pixels);
1349                                 icon->pixels = NULL; // safety
1350                         }
1351                         SDL_FreeSurface(icon);
1352                 }
1353
1354                 icon = SDL_CreateRGBSurface(SDL_SRCCOLORKEY, width, height, 8, 0,0,0,0);// rmask, gmask, bmask, amask); no mask needed
1355                 // 8 bit surfaces get an empty palette allocated according to the docs
1356                 // so it's a palette image for sure :) no endian check necessary for the mask
1357
1358                 if(icon == NULL) {
1359                         Con_Printf(     "Failed to create surface for the window Icon!\n"
1360                                         "%s\n", SDL_GetError());
1361                         free(data);
1362                         return;
1363                 }
1364
1365                 icon->pixels = data;
1366                 SDL_SetPalette(icon, SDL_PHYSPAL|SDL_LOGPAL, palette, 0, colors);
1367                 SDL_SetColorKey(icon, SDL_SRCCOLORKEY, thenone);
1368         }
1369
1370         SDL_WM_SetIcon(icon, NULL);
1371 }
1372 static void VID_SetIcon_Post(void)
1373 {
1374 #if SDL_MAJOR_VERSION == 1 && SDL_MINOR_VERSION == 2
1375 // LordHavoc: info.info.x11.lock_func and accompanying code do not seem to compile with SDL 1.3
1376 #if SDL_VIDEO_DRIVER_X11 && !SDL_VIDEO_DRIVER_QUARTZ
1377         int j;
1378         char *data;
1379         const SDL_version *version;
1380
1381         version = SDL_Linked_Version();
1382         // only use non-XPM icon support in SDL v1.3 and higher
1383         // SDL v1.2 does not support "smooth" transparency, and thus is better
1384         // off the xpm way
1385         if(!(version->major >= 2 || (version->major == 1 && version->minor >= 3)))
1386         {
1387                 // in this case, we did not set the good icon yet
1388                 SDL_SysWMinfo info;
1389                 SDL_VERSION(&info.version);
1390                 if(SDL_GetWMInfo(&info) == 1 && info.subsystem == SDL_SYSWM_X11)
1391                 {
1392                         data = (char *) loadimagepixelsbgra("darkplaces-icon", false, false, false, NULL);
1393                         if(data)
1394                         {
1395                                 // use _NET_WM_ICON too
1396                                 static long netwm_icon[MAX_NETWM_ICON];
1397                                 int pos = 0;
1398                                 int i = 1;
1399
1400                                 while(data)
1401                                 {
1402                                         if(pos + 2 * image_width * image_height < MAX_NETWM_ICON)
1403                                         {
1404                                                 netwm_icon[pos++] = image_width;
1405                                                 netwm_icon[pos++] = image_height;
1406                                                 for(i = 0; i < image_height; ++i)
1407                                                         for(j = 0; j < image_width; ++j)
1408                                                                 netwm_icon[pos++] = BuffLittleLong((unsigned char *) &data[(i*image_width+j)*4]);
1409                                         }
1410                                         else
1411                                         {
1412                                                 Con_Printf("Skipping NETWM icon #%d because there is no space left\n", i);
1413                                         }
1414                                         ++i;
1415                                         Mem_Free(data);
1416                                         data = (char *) loadimagepixelsbgra(va("darkplaces-icon%d", i), false, false, false, NULL);
1417                                 }
1418
1419                                 info.info.x11.lock_func();
1420                                 {
1421                                         Atom net_wm_icon = XInternAtom(info.info.x11.display, "_NET_WM_ICON", false);
1422                                         XChangeProperty(info.info.x11.display, info.info.x11.wmwindow, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (const unsigned char *) netwm_icon, pos);
1423                                 }
1424                                 info.info.x11.unlock_func();
1425                         }
1426                 }
1427         }
1428 #endif
1429 #endif
1430 }
1431
1432
1433 static void VID_SetCaption(void)
1434 {
1435         SDL_WM_SetCaption( gamename, NULL );
1436 }
1437 #endif
1438
1439 static void VID_OutputVersion(void)
1440 {
1441         const SDL_version *version;
1442         version = SDL_Linked_Version();
1443         Con_Printf(     "Linked against SDL version %d.%d.%d\n"
1444                                         "Using SDL library version %d.%d.%d\n",
1445                                         SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL,
1446                                         version->major, version->minor, version->patch );
1447 }
1448
1449 qboolean VID_InitModeGL(viddef_mode_t *mode)
1450 {
1451         int i;
1452 // FIXME SDL_SetVideoMode
1453         static int notfirstvideomode = false;
1454         int flags = SDL_OPENGL;
1455         const char *drivername;
1456
1457         win_half_width = mode->width>>1;
1458         win_half_height = mode->height>>1;
1459
1460         if(vid_resizable.integer)
1461                 flags |= SDL_RESIZABLE;
1462
1463         VID_OutputVersion();
1464
1465         /*
1466         SDL Hack
1467                 We cant switch from one OpenGL video mode to another.
1468                 Thus we first switch to some stupid 2D mode and then back to OpenGL.
1469         */
1470         if (notfirstvideomode)
1471                 SDL_SetVideoMode( 0, 0, 0, 0 );
1472         notfirstvideomode = true;
1473
1474         // SDL usually knows best
1475         drivername = NULL;
1476
1477 // 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
1478         i = COM_CheckParm("-gl_driver");
1479         if (i && i < com_argc - 1)
1480                 drivername = com_argv[i + 1];
1481         if (SDL_GL_LoadLibrary(drivername) < 0)
1482         {
1483                 Con_Printf("Unable to load GL driver \"%s\": %s\n", drivername, SDL_GetError());
1484                 return false;
1485         }
1486
1487 #ifndef __IPHONEOS__
1488         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
1489         {
1490                 VID_Shutdown();
1491                 Con_Print("Required OpenGL function glGetString not found\n");
1492                 return false;
1493         }
1494 #endif
1495
1496         // Knghtbrd: should do platform-specific extension string function here
1497
1498         vid_isfullscreen = false;
1499         if (mode->fullscreen) {
1500                 flags |= SDL_FULLSCREEN;
1501                 vid_isfullscreen = true;
1502         }
1503         //flags |= SDL_HWSURFACE;
1504
1505         SDL_GL_SetAttribute (SDL_GL_DOUBLEBUFFER, 1);
1506         if (mode->bitsperpixel >= 32)
1507         {
1508                 SDL_GL_SetAttribute (SDL_GL_RED_SIZE, 8);
1509                 SDL_GL_SetAttribute (SDL_GL_GREEN_SIZE, 8);
1510                 SDL_GL_SetAttribute (SDL_GL_BLUE_SIZE, 8);
1511                 SDL_GL_SetAttribute (SDL_GL_ALPHA_SIZE, 8);
1512                 SDL_GL_SetAttribute (SDL_GL_DEPTH_SIZE, 24);
1513                 SDL_GL_SetAttribute (SDL_GL_STENCIL_SIZE, 8);
1514         }
1515         else
1516         {
1517                 SDL_GL_SetAttribute (SDL_GL_RED_SIZE, 5);
1518                 SDL_GL_SetAttribute (SDL_GL_GREEN_SIZE, 5);
1519                 SDL_GL_SetAttribute (SDL_GL_BLUE_SIZE, 5);
1520                 SDL_GL_SetAttribute (SDL_GL_DEPTH_SIZE, 16);
1521         }
1522         if (mode->stereobuffer)
1523                 SDL_GL_SetAttribute (SDL_GL_STEREO, 1);
1524         if (mode->samples > 1)
1525         {
1526                 SDL_GL_SetAttribute (SDL_GL_MULTISAMPLEBUFFERS, 1);
1527                 SDL_GL_SetAttribute (SDL_GL_MULTISAMPLESAMPLES, mode->samples);
1528         }
1529 #if SDL_MAJOR_VERSION == 1 && SDL_MINOR_VERSION == 2
1530         if (vid_vsync.integer)
1531                 SDL_GL_SetAttribute (SDL_GL_SWAP_CONTROL, 1);
1532         else
1533                 SDL_GL_SetAttribute (SDL_GL_SWAP_CONTROL, 0);
1534 #else
1535         // TODO: SDL_GL_CONTEXT_MAJOR_VERSION, SDL_GL_CONTEXT_MINOR_VERSION
1536 #endif
1537
1538         video_bpp = mode->bitsperpixel;
1539         video_flags = flags;
1540         VID_SetIcon_Pre();
1541         screen = SDL_SetVideoMode(mode->width, mode->height, mode->bitsperpixel, flags);
1542         VID_SetIcon_Post();
1543
1544         if (screen == NULL)
1545         {
1546                 Con_Printf("Failed to set video mode to %ix%i: %s\n", mode->width, mode->height, SDL_GetError());
1547                 VID_Shutdown();
1548                 return false;
1549         }
1550
1551         vid_softsurface = NULL;
1552         vid.softpixels = NULL;
1553
1554         // set window title
1555         VID_SetCaption();
1556 #if SDL_MAJOR_VERSION == 1 && SDL_MINOR_VERSION == 2
1557         // set up an event filter to ask confirmation on close button in WIN32
1558         SDL_SetEventFilter( (SDL_EventFilter) Sys_EventFilter );
1559 #endif
1560         // init keyboard
1561         SDL_EnableUNICODE( SDL_ENABLE );
1562         // enable key repeat since everyone expects it
1563         SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
1564
1565 #if !(SDL_MAJOR_VERSION == 1 && SDL_MINOR_VERSION == 2)
1566         SDL_GL_SetSwapInterval(vid_vsync.integer != 0);
1567         vid_usingvsync = (vid_vsync.integer != 0);
1568 #endif
1569
1570         gl_platform = "SDL";
1571         gl_platformextensions = "";
1572
1573 #ifdef __IPHONEOS__
1574         GLES_Init();
1575 #else
1576         GL_Init();
1577 #endif
1578
1579         vid_numjoysticks = SDL_NumJoysticks();
1580         vid_numjoysticks = bound(0, vid_numjoysticks, MAX_JOYSTICKS);
1581         Cvar_SetValueQuick(&joy_detected, vid_numjoysticks);
1582         Con_Printf("%d SDL joystick(s) found:\n", vid_numjoysticks);
1583         memset(vid_joysticks, 0, sizeof(vid_joysticks));
1584         for (i = 0;i < vid_numjoysticks;i++)
1585         {
1586                 SDL_Joystick *joy;
1587                 joy = vid_joysticks[i] = SDL_JoystickOpen(i);
1588                 if (!joy)
1589                 {
1590                         Con_Printf("joystick #%i: open failed: %s\n", i, SDL_GetError());
1591                         continue;
1592                 }
1593                 Con_Printf("joystick #%i: opened \"%s\" with %i axes, %i buttons, %i balls\n", i, SDL_JoystickName(i), (int)SDL_JoystickNumAxes(joy), (int)SDL_JoystickNumButtons(joy), (int)SDL_JoystickNumBalls(joy));
1594         }
1595
1596         vid_hidden = false;
1597         vid_activewindow = false;
1598         vid_usingmouse = false;
1599         vid_usinghidecursor = false;
1600
1601         SDL_WM_GrabInput(SDL_GRAB_OFF);
1602         return true;
1603 }
1604
1605 extern cvar_t gl_info_extensions;
1606 extern cvar_t gl_info_vendor;
1607 extern cvar_t gl_info_renderer;
1608 extern cvar_t gl_info_version;
1609 extern cvar_t gl_info_platform;
1610 extern cvar_t gl_info_driver;
1611
1612 qboolean VID_InitModeSoft(viddef_mode_t *mode)
1613 {
1614 // FIXME SDL_SetVideoMode
1615         int i;
1616         int flags = SDL_HWSURFACE;
1617
1618         win_half_width = mode->width>>1;
1619         win_half_height = mode->height>>1;
1620
1621         if(vid_resizable.integer)
1622                 flags |= SDL_RESIZABLE;
1623
1624         VID_OutputVersion();
1625
1626         vid_isfullscreen = false;
1627         if (mode->fullscreen) {
1628                 flags |= SDL_FULLSCREEN;
1629                 vid_isfullscreen = true;
1630         }
1631
1632         video_bpp = mode->bitsperpixel;
1633         video_flags = flags;
1634         VID_SetIcon_Pre();
1635         screen = SDL_SetVideoMode(mode->width, mode->height, mode->bitsperpixel, flags);
1636         VID_SetIcon_Post();
1637
1638         if (screen == NULL)
1639         {
1640                 Con_Printf("Failed to set video mode to %ix%i: %s\n", mode->width, mode->height, SDL_GetError());
1641                 VID_Shutdown();
1642                 return false;
1643         }
1644
1645         // create a framebuffer using our specific color format, we let the SDL blit function convert it in VID_Finish
1646         vid_softsurface = SDL_CreateRGBSurface(SDL_SWSURFACE, mode->width, mode->height, 32, 0x00FF0000, 0x0000FF00, 0x00000000FF, 0xFF000000);
1647         if (vid_softsurface == NULL)
1648         {
1649                 Con_Printf("Failed to setup software rasterizer framebuffer %ix%ix32bpp: %s\n", mode->width, mode->height, SDL_GetError());
1650                 VID_Shutdown();
1651                 return false;
1652         }
1653         SDL_SetAlpha(vid_softsurface, 0, 255);
1654
1655         vid.softpixels = (unsigned int *)vid_softsurface->pixels;
1656         vid.softdepthpixels = (unsigned int *)calloc(1, mode->width * mode->height * 4);
1657         DPSOFTRAST_Init(mode->width, mode->height, vid_soft_threads.integer, (unsigned int *)vid_softsurface->pixels, (unsigned int *)vid.softdepthpixels);
1658
1659         // set window title
1660         VID_SetCaption();
1661         // set up an event filter to ask confirmation on close button in WIN32
1662 #if SDL_MAJOR_VERSION == 1 && SDL_MINOR_VERSION == 2
1663         SDL_SetEventFilter( (SDL_EventFilter) Sys_EventFilter );
1664 #endif
1665         // init keyboard
1666         SDL_EnableUNICODE( SDL_ENABLE );
1667         // enable key repeat since everyone expects it
1668         SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
1669
1670         gl_platform = "SDLSoft";
1671         gl_platformextensions = "";
1672
1673         gl_renderer = "DarkPlaces-Soft";
1674         gl_vendor = "Forest Hale";
1675         gl_version = "0.0";
1676         gl_extensions = "";
1677
1678         // clear the extension flags
1679         memset(&vid.support, 0, sizeof(vid.support));
1680         Cvar_SetQuick(&gl_info_extensions, "");
1681
1682         vid.forcevbo = false;
1683         vid.support.arb_depth_texture = true;
1684         vid.support.arb_draw_buffers = true;
1685         vid.support.arb_occlusion_query = true;
1686         vid.support.arb_shadow = true;
1687         //vid.support.arb_texture_compression = true;
1688         vid.support.arb_texture_cube_map = true;
1689         vid.support.arb_texture_non_power_of_two = false;
1690         vid.support.arb_vertex_buffer_object = true;
1691         vid.support.ext_blend_subtract = true;
1692         vid.support.ext_draw_range_elements = true;
1693         vid.support.ext_framebuffer_object = true;
1694         vid.support.ext_texture_3d = true;
1695         //vid.support.ext_texture_compression_s3tc = true;
1696         vid.support.ext_texture_filter_anisotropic = true;
1697         vid.support.ati_separate_stencil = true;
1698
1699         vid.maxtexturesize_2d = 16384;
1700         vid.maxtexturesize_3d = 512;
1701         vid.maxtexturesize_cubemap = 16384;
1702         vid.texunits = 4;
1703         vid.teximageunits = 32;
1704         vid.texarrayunits = 8;
1705         vid.max_anisotropy = 1;
1706         vid.maxdrawbuffers = 4;
1707
1708         vid.texunits = bound(4, vid.texunits, MAX_TEXTUREUNITS);
1709         vid.teximageunits = bound(16, vid.teximageunits, MAX_TEXTUREUNITS);
1710         vid.texarrayunits = bound(8, vid.texarrayunits, MAX_TEXTUREUNITS);
1711         Con_DPrintf("Using DarkPlaces Software Rasterizer rendering path\n");
1712         vid.renderpath = RENDERPATH_SOFT;
1713         vid.useinterleavedarrays = false;
1714
1715         Cvar_SetQuick(&gl_info_vendor, gl_vendor);
1716         Cvar_SetQuick(&gl_info_renderer, gl_renderer);
1717         Cvar_SetQuick(&gl_info_version, gl_version);
1718         Cvar_SetQuick(&gl_info_platform, gl_platform ? gl_platform : "");
1719         Cvar_SetQuick(&gl_info_driver, gl_driver);
1720
1721         // LordHavoc: report supported extensions
1722         Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
1723
1724         // clear to black (loading plaque will be seen over this)
1725         GL_Clear(GL_COLOR_BUFFER_BIT, NULL, 1.0f, 128);
1726
1727         vid_numjoysticks = SDL_NumJoysticks();
1728         vid_numjoysticks = bound(0, vid_numjoysticks, MAX_JOYSTICKS);
1729         Cvar_SetValueQuick(&joy_detected, vid_numjoysticks);
1730         Con_Printf("%d SDL joystick(s) found:\n", vid_numjoysticks);
1731         memset(vid_joysticks, 0, sizeof(vid_joysticks));
1732         for (i = 0;i < vid_numjoysticks;i++)
1733         {
1734                 SDL_Joystick *joy;
1735                 joy = vid_joysticks[i] = SDL_JoystickOpen(i);
1736                 if (!joy)
1737                 {
1738                         Con_Printf("joystick #%i: open failed: %s\n", i, SDL_GetError());
1739                         continue;
1740                 }
1741                 Con_Printf("joystick #%i: opened \"%s\" with %i axes, %i buttons, %i balls\n", i, SDL_JoystickName(i), (int)SDL_JoystickNumAxes(joy), (int)SDL_JoystickNumButtons(joy), (int)SDL_JoystickNumBalls(joy));
1742         }
1743
1744         vid_hidden = false;
1745         vid_activewindow = false;
1746         vid_usingmouse = false;
1747         vid_usinghidecursor = false;
1748
1749         SDL_WM_GrabInput(SDL_GRAB_OFF);
1750         return true;
1751 }
1752
1753 qboolean VID_InitMode(viddef_mode_t *mode)
1754 {
1755         if (!SDL_WasInit(SDL_INIT_VIDEO) && SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
1756                 Sys_Error ("Failed to init SDL video subsystem: %s", SDL_GetError());
1757 #ifdef SSE2_PRESENT
1758         if (vid_soft.integer)
1759                 return VID_InitModeSoft(mode);
1760         else
1761 #endif
1762                 return VID_InitModeGL(mode);
1763 }
1764
1765 void VID_Shutdown (void)
1766 {
1767         VID_SetMouse(false, false, false);
1768         VID_RestoreSystemGamma();
1769
1770 #ifndef WIN32
1771         if (icon)
1772                 SDL_FreeSurface(icon);
1773         icon = NULL;
1774 #endif
1775
1776         if (vid_softsurface)
1777                 SDL_FreeSurface(vid_softsurface);
1778         vid_softsurface = NULL;
1779         vid.softpixels = NULL;
1780         if (vid.softdepthpixels)
1781                 free(vid.softdepthpixels);
1782         vid.softdepthpixels = NULL;
1783
1784         SDL_QuitSubSystem(SDL_INIT_VIDEO);
1785
1786         gl_driver[0] = 0;
1787         gl_extensions = "";
1788         gl_platform = "";
1789         gl_platformextensions = "";
1790 }
1791
1792 int VID_SetGamma (unsigned short *ramps, int rampsize)
1793 {
1794         return !SDL_SetGammaRamp (ramps, ramps + rampsize, ramps + rampsize*2);
1795 }
1796
1797 int VID_GetGamma (unsigned short *ramps, int rampsize)
1798 {
1799         return !SDL_GetGammaRamp (ramps, ramps + rampsize, ramps + rampsize*2);
1800 }
1801
1802 void VID_Finish (void)
1803 {
1804         Uint8 appstate;
1805
1806         //react on appstate changes
1807         appstate = SDL_GetAppState();
1808
1809         vid_hidden = !(appstate & SDL_APPACTIVE);
1810
1811         if( vid_hidden || !( appstate & SDL_APPMOUSEFOCUS ) || !( appstate & SDL_APPINPUTFOCUS ) )
1812                 vid_activewindow = false;
1813         else
1814                 vid_activewindow = true;
1815
1816         VID_UpdateGamma(false, 256);
1817
1818         if (!vid_hidden)
1819         {
1820                 switch(vid.renderpath)
1821                 {
1822                 case RENDERPATH_GL11:
1823                 case RENDERPATH_GL13:
1824                 case RENDERPATH_GL20:
1825                 case RENDERPATH_CGGL:
1826                         CHECKGLERROR
1827                         if (r_speeds.integer == 2 || gl_finish.integer)
1828                         {
1829                                 qglFinish();CHECKGLERROR
1830                         }
1831 #if !(SDL_MAJOR_VERSION == 1 && SDL_MINOR_VERSION == 2)
1832 {
1833         qboolean vid_usevsync;
1834         vid_usevsync = (vid_vsync.integer && !cls.timedemo);
1835         if (vid_usingvsync != vid_usevsync)
1836         {
1837                 if (SDL_GL_SetSwapInterval(vid_usevsync != 0) >= 0)
1838                         Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
1839                 else
1840                         Con_DPrintf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
1841         }
1842 }
1843 #endif
1844                         SDL_GL_SwapBuffers();
1845                         break;
1846                 case RENDERPATH_SOFT:
1847                         DPSOFTRAST_Finish();
1848                         SDL_BlitSurface(vid_softsurface, NULL, screen, NULL);
1849                         SDL_Flip(screen);
1850                         break;
1851                 case RENDERPATH_D3D9:
1852                 case RENDERPATH_D3D10:
1853                 case RENDERPATH_D3D11:
1854                         break;
1855                 }
1856         }
1857 }
1858
1859 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
1860 {
1861         size_t k;
1862         SDL_Rect **vidmodes;
1863         int bpp = SDL_GetVideoInfo()->vfmt->BitsPerPixel;
1864
1865         k = 0;
1866         for(vidmodes = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_HWSURFACE); *vidmodes; ++vidmodes)
1867         {
1868                 if(k >= maxcount)
1869                         break;
1870                 modes[k].width = (*vidmodes)->w;
1871                 modes[k].height = (*vidmodes)->h;
1872                 modes[k].bpp = bpp;
1873                 modes[k].refreshrate = 60; // no support for refresh rate in SDL
1874                 modes[k].pixelheight_num = 1;
1875                 modes[k].pixelheight_denom = 1; // SDL does not provide this
1876                 ++k;
1877         }
1878         return k;
1879 }