diff options
author | IronClawTrem <louie.nutman@gmail.com> | 2020-02-16 03:40:06 +0000 |
---|---|---|
committer | IronClawTrem <louie.nutman@gmail.com> | 2020-02-16 03:40:06 +0000 |
commit | 425decdf7e9284d15aa726e3ae96b9942fb0e3ea (patch) | |
tree | 6c0dd7edfefff1be7b9e75fe0b3a0a85fe1595f3 /src/sdl | |
parent | ccb0b2e4d6674a7a00c9bf491f08fc73b6898c54 (diff) |
create tremded branch
Diffstat (limited to 'src/sdl')
-rw-r--r-- | src/sdl/CMakeLists.txt | 8 | ||||
-rw-r--r-- | src/sdl/sdl_gamma.cpp | 100 | ||||
-rw-r--r-- | src/sdl/sdl_glimp.cpp | 935 | ||||
-rw-r--r-- | src/sdl/sdl_icon.h | 138 | ||||
-rw-r--r-- | src/sdl/sdl_input.cpp | 1336 | ||||
-rw-r--r-- | src/sdl/sdl_snd.cpp | 298 |
6 files changed, 2815 insertions, 0 deletions
diff --git a/src/sdl/CMakeLists.txt b/src/sdl/CMakeLists.txt new file mode 100644 index 0000000..20dbe32 --- /dev/null +++ b/src/sdl/CMakeLists.txt @@ -0,0 +1,8 @@ +add_library ( + sdl STATIC + sdl_gamma.cpp + sdl_glimp.cpp + sdl_icon.h + sdl_input.cpp + sdl_snd.cpp +) diff --git a/src/sdl/sdl_gamma.cpp b/src/sdl/sdl_gamma.cpp new file mode 100644 index 0000000..372fdf2 --- /dev/null +++ b/src/sdl/sdl_gamma.cpp @@ -0,0 +1,100 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. +Copyright (C) 2000-2013 Darklegion Development +Copyright (C) 2015-2019 GrangerHub + +This file is part of Tremulous. + +Tremulous is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 3 of the License, +or (at your option) any later version. + +Tremulous is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Tremulous; if not, see <https://www.gnu.org/licenses/> + +=========================================================================== +*/ + +#ifdef _WIN32 +#include <windows.h> +#endif + +#ifdef USE_LOCAL_HEADERS +# include "SDL.h" +#else +# include <SDL.h> +#endif + +#include "qcommon/cvar.h" +#include "qcommon/qcommon.h" +#include "renderercommon/tr_common.h" + +extern SDL_Window *SDL_window; + +/* +================= +GLimp_SetGamma +================= +*/ +void GLimp_SetGamma( unsigned char red[256], unsigned char green[256], unsigned char blue[256] ) +{ + Uint16 table[3][256]; + int i, j; + + if( !glConfig.deviceSupportsGamma || r_ignorehwgamma->integer > 0 ) + return; + + for (i = 0; i < 256; i++) + { + table[0][i] = ( ( ( Uint16 ) red[i] ) << 8 ) | red[i]; + table[1][i] = ( ( ( Uint16 ) green[i] ) << 8 ) | green[i]; + table[2][i] = ( ( ( Uint16 ) blue[i] ) << 8 ) | blue[i]; + } + +#ifdef _WIN32 + // Win2K and newer put this odd restriction on gamma ramps... + { + OSVERSIONINFO vinfo; + + vinfo.dwOSVersionInfoSize = sizeof( vinfo ); + GetVersionEx( &vinfo ); + if( vinfo.dwMajorVersion >= 5 && vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT ) + { + ri.Printf( PRINT_DEVELOPER, "performing gamma clamp.\n" ); + for( j = 0 ; j < 3 ; j++ ) + { + for( i = 0 ; i < 128 ; i++ ) + { + if( table[ j ] [ i] > ( ( 128 + i ) << 8 ) ) + table[ j ][ i ] = ( 128 + i ) << 8; + } + + if( table[ j ] [127 ] > 254 << 8 ) + table[ j ][ 127 ] = 254 << 8; + } + } + } +#endif + + // enforce constantly increasing + for (j = 0; j < 3; j++) + { + for (i = 1; i < 256; i++) + { + if (table[j][i] < table[j][i-1]) + table[j][i] = table[j][i-1]; + } + } + + if (SDL_SetWindowGammaRamp(SDL_window, table[0], table[1], table[2]) < 0) + { + ri.Printf( PRINT_DEVELOPER, "SDL_SetWindowGammaRamp() failed: %s\n", SDL_GetError() ); + } +} diff --git a/src/sdl/sdl_glimp.cpp b/src/sdl/sdl_glimp.cpp new file mode 100644 index 0000000..9ecd224 --- /dev/null +++ b/src/sdl/sdl_glimp.cpp @@ -0,0 +1,935 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. +Copyright (C) 2000-2013 Darklegion Development +Copyright (C) 2015-2019 GrangerHub + +This file is part of Tremulous. + +Tremulous is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 3 of the License, +or (at your option) any later version. + +Tremulous is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Tremulous; if not, see <https://www.gnu.org/licenses/> + +=========================================================================== +*/ + +#ifdef USE_LOCAL_HEADERS +# include "SDL.h" +#else +# include <SDL.h> +#endif + +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <math.h> + +#include "renderercommon/tr_common.h" +#include "qcommon/cvar.h" +#include "sys/sys_local.h" +#include "sdl_icon.h" + +typedef enum +{ + RSERR_OK, + + RSERR_INVALID_FULLSCREEN, + RSERR_INVALID_MODE, + + RSERR_UNKNOWN +} rserr_t; + +SDL_Window *SDL_window = NULL; +static SDL_GLContext SDL_glContext = NULL; + +cvar_t *r_allowSoftwareGL; // Don't abort out if a hardware visual can't be obtained +cvar_t *r_allowResize; // make window resizable +cvar_t *r_centerWindow; +cvar_t *r_sdlDriver; + +void (APIENTRYP qglActiveTextureARB) (GLenum texture); +void (APIENTRYP qglClientActiveTextureARB) (GLenum texture); +void (APIENTRYP qglMultiTexCoord2fARB) (GLenum target, GLfloat s, GLfloat t); + +void (APIENTRYP qglLockArraysEXT) (GLint first, GLsizei count); +void (APIENTRYP qglUnlockArraysEXT) (void); + +/* +=============== +GLimp_Shutdown +=============== +*/ +void GLimp_Shutdown( void ) +{ + float oldDisplayAspect = glConfig.displayAspect; + + ri.IN_Shutdown(); + + SDL_QuitSubSystem( SDL_INIT_VIDEO ); + + glConfig.displayAspect = oldDisplayAspect; +} + +/* +=============== +GLimp_Minimize + +Minimize the game so that user is back at the desktop +=============== +*/ +void GLimp_Minimize( void ) +{ + SDL_MinimizeWindow( SDL_window ); +} + + +/* +=============== +GLimp_LogComment +=============== +*/ +void GLimp_LogComment( const char *comment ) +{ +} + +/* +=============== +GLimp_CompareModes +=============== +*/ +static int GLimp_CompareModes( const void *a, const void *b ) +{ + const float ASPECT_EPSILON = 0.001f; + SDL_Rect *modeA = (SDL_Rect *)a; + SDL_Rect *modeB = (SDL_Rect *)b; + float aspectA = (float)modeA->w / (float)modeA->h; + float aspectB = (float)modeB->w / (float)modeB->h; + int areaA = modeA->w * modeA->h; + int areaB = modeB->w * modeB->h; + float aspectDiffA = fabs( aspectA - glConfig.displayAspect ); + float aspectDiffB = fabs( aspectB - glConfig.displayAspect ); + float aspectDiffsDiff = aspectDiffA - aspectDiffB; + + if( aspectDiffsDiff > ASPECT_EPSILON ) + return 1; + else if( aspectDiffsDiff < -ASPECT_EPSILON ) + return -1; + else + return areaA - areaB; +} + + +/* +=============== +GLimp_DetectAvailableModes +=============== +*/ +static void GLimp_DetectAvailableModes(void) +{ + int i, j; + char buf[ MAX_STRING_CHARS ] = { 0 }; + int numSDLModes; + SDL_Rect *modes; + int numModes = 0; + + SDL_DisplayMode windowMode; + int display = SDL_GetWindowDisplayIndex( SDL_window ); + if( display < 0 ) + { + ri.Printf( PRINT_WARNING, "Couldn't get window display index, no resolutions detected: %s\n", SDL_GetError() ); + return; + } + numSDLModes = SDL_GetNumDisplayModes( display ); + + if( SDL_GetWindowDisplayMode( SDL_window, &windowMode ) < 0 || numSDLModes <= 0 ) + { + ri.Printf( PRINT_WARNING, "Couldn't get window display mode, no resolutions detected: %s\n", SDL_GetError() ); + return; + } + + modes = (SDL_Rect*)SDL_calloc( (size_t)numSDLModes, sizeof( SDL_Rect ) ); + if ( !modes ) + { + ri.Error( ERR_FATAL, "Out of memory" ); + } + + for( i = 0; i < numSDLModes; i++ ) + { + SDL_DisplayMode mode; + + if( SDL_GetDisplayMode( display, i, &mode ) < 0 ) + continue; + + if( !mode.w || !mode.h ) + { + ri.Printf( PRINT_ALL, "Display supports any resolution\n" ); + SDL_free( modes ); + return; + } + + if( windowMode.format != mode.format ) + continue; + + // SDL can give the same resolution with different refresh rates. + // Only list resolution once. + for( j = 0; j < numModes; j++ ) + { + if( mode.w == modes[ j ].w && mode.h == modes[ j ].h ) + break; + } + + if( j != numModes ) + continue; + + modes[ numModes ].w = mode.w; + modes[ numModes ].h = mode.h; + numModes++; + } + + if( numModes > 1 ) + qsort( modes, numModes, sizeof( SDL_Rect ), GLimp_CompareModes ); + + for( i = 0; i < numModes; i++ ) + { + const char *newModeString = va( "%ux%u ", modes[ i ].w, modes[ i ].h ); + + if( strlen( newModeString ) < (int)sizeof( buf ) - strlen( buf ) ) + Q_strcat( buf, sizeof( buf ), newModeString ); + else + ri.Printf( PRINT_WARNING, "Skipping mode %ux%u, buffer too small\n", modes[ i ].w, modes[ i ].h ); + } + + if( *buf ) + { + buf[ strlen( buf ) - 1 ] = 0; + ri.Printf( PRINT_ALL, "Available modes: '%s'\n", buf ); + ri.Cvar_Set( "r_availableModes", buf ); + } + SDL_free( modes ); +} + +#define R_FAILSAFE_WIDTH 640 +#define R_FAILSAFE_HEIGHT 480 + +/* +=============== +GLimp_SetMode +=============== +*/ +static int GLimp_SetMode( bool failSafe, bool fullscreen, bool noborder, bool coreContext ) +{ + const char *glstring; + int perChannelColorBits; + int colorBits, alphaBits, depthBits, stencilBits; + int samples; + int i = 0; + SDL_Surface *icon = NULL; + Uint32 flags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL; + SDL_DisplayMode desktopMode; + int display = 0; + int x = SDL_WINDOWPOS_UNDEFINED, y = SDL_WINDOWPOS_UNDEFINED; + + ri.Printf( PRINT_ALL, "Initializing OpenGL display\n"); + + if ( r_allowResize->integer ) + flags |= SDL_WINDOW_RESIZABLE; + +#ifdef USE_ICON + icon = SDL_CreateRGBSurfaceFrom( + (void *)CLIENT_WINDOW_ICON.pixel_data, + CLIENT_WINDOW_ICON.width, + CLIENT_WINDOW_ICON.height, + CLIENT_WINDOW_ICON.bytes_per_pixel * 8, + CLIENT_WINDOW_ICON.bytes_per_pixel * CLIENT_WINDOW_ICON.width, +#ifdef Q3_LITTLE_ENDIAN + 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 +#else + 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF +#endif + ); +#endif + + // If a window exists, note its display index + if( SDL_window != NULL ) + { + display = SDL_GetWindowDisplayIndex( SDL_window ); + if( display < 0 ) + { + ri.Printf( PRINT_DEVELOPER, "SDL_GetWindowDisplayIndex() failed: %s\n", SDL_GetError() ); + } + } + + if( display >= 0 && SDL_GetDesktopDisplayMode( display, &desktopMode ) == 0 ) + { + glConfig.displayAspect = (float)desktopMode.w / (float)desktopMode.h; + + ri.Printf( PRINT_ALL, "Display aspect: %.3f\n", glConfig.displayAspect ); + } + else + { + Com_Memset( &desktopMode, 0, sizeof( SDL_DisplayMode ) ); + + ri.Printf( PRINT_ALL, + "Cannot determine display aspect, assuming 1.333\n" ); + } + + if( !failSafe ) + { + if( r_width->integer > 0 && r_height->integer > 0 ) + { + glConfig.vidWidth = r_width->integer; + glConfig.vidHeight = r_height->integer; + } + else if( desktopMode.h > 0 ) + { + // use desktop video resolution + glConfig.vidWidth = desktopMode.w; + glConfig.vidHeight = desktopMode.h; + } + else + { + glConfig.vidWidth = 640; + glConfig.vidHeight = 480; + ri.Printf( PRINT_ALL, + "Cannot determine display resolution, assuming 640x480\n" ); + } + + glConfig.windowAspect = (float)glConfig.vidWidth / + ( (float)glConfig.vidHeight * r_pixelAspect->value ); + } + else if( glConfig.vidWidth != R_FAILSAFE_WIDTH && + glConfig.vidHeight != R_FAILSAFE_HEIGHT ) + { + ri.Printf( PRINT_ALL, "Setting mode %dx%d failed, falling back on mode %dx%d\n", + glConfig.vidWidth, glConfig.vidHeight, R_FAILSAFE_WIDTH, R_FAILSAFE_HEIGHT ); + + glConfig.vidWidth = R_FAILSAFE_WIDTH; + glConfig.vidHeight = R_FAILSAFE_HEIGHT; + glConfig.windowAspect = 1.0f; + } + else + return RSERR_INVALID_MODE; + + ri.Printf (PRINT_ALL, "...setting mode %dx%d\n", glConfig.vidWidth, glConfig.vidHeight); + + // Center window + if( r_centerWindow->integer && !fullscreen ) + { + x = ( desktopMode.w / 2 ) - ( glConfig.vidWidth / 2 ); + y = ( desktopMode.h / 2 ) - ( glConfig.vidHeight / 2 ); + } + + // Destroy existing state if it exists + if( SDL_glContext != NULL ) + { + SDL_GL_DeleteContext( SDL_glContext ); + SDL_glContext = NULL; + } + + if( SDL_window != NULL ) + { + SDL_GetWindowPosition( SDL_window, &x, &y ); + ri.Printf( PRINT_DEVELOPER, "Existing window at %dx%d before being destroyed\n", x, y ); + SDL_DestroyWindow( SDL_window ); + SDL_window = NULL; + } + + if( fullscreen ) + { + flags |= SDL_WINDOW_FULLSCREEN; + glConfig.isFullscreen = qtrue; + } + else + { + if( noborder ) + flags |= SDL_WINDOW_BORDERLESS; + + glConfig.isFullscreen = qfalse; + } + + colorBits = r_colorbits->value; + if ((!colorBits) || (colorBits >= 32)) + colorBits = 24; + + alphaBits = r_alphabits->value; + + if (!r_depthbits->value) + depthBits = 24; + else + depthBits = r_depthbits->value; + + stencilBits = r_stencilbits->value; + samples = r_ext_multisample->value; + + for (i = 0; i < 16; i++) + { + int testColorBits, testDepthBits, testStencilBits; + + // 0 - default + // 1 - minus colorBits + // 2 - minus depthBits + // 3 - minus stencil + if ((i % 4) == 0 && i) + { + // one pass, reduce + switch (i / 4) + { + case 2 : + if (colorBits == 24) + colorBits = 16; + break; + case 1 : + if (depthBits == 24) + depthBits = 16; + else if (depthBits == 16) + depthBits = 8; + case 3 : + if (stencilBits == 24) + stencilBits = 16; + else if (stencilBits == 16) + stencilBits = 8; + } + } + + testColorBits = colorBits; + testDepthBits = depthBits; + testStencilBits = stencilBits; + + if ((i % 4) == 3) + { // reduce colorBits + if (testColorBits == 24) + testColorBits = 16; + } + + if ((i % 4) == 2) + { // reduce depthBits + if (testDepthBits == 24) + testDepthBits = 16; + else if (testDepthBits == 16) + testDepthBits = 8; + } + + if ((i % 4) == 1) + { // reduce stencilBits + if (testStencilBits == 24) + testStencilBits = 16; + else if (testStencilBits == 16) + testStencilBits = 8; + else + testStencilBits = 0; + } + + if (testColorBits == 24) + perChannelColorBits = 8; + else + perChannelColorBits = 4; + +#ifdef __sgi /* Fix for SGIs grabbing too many bits of color */ + if (perChannelColorBits == 4) + perChannelColorBits = 0; /* Use minimum size for 16-bit color */ + + /* Need alpha or else SGIs choose 36+ bit RGB mode */ + if (alphaBits < 1) + alphaBits = 1; +#endif + + SDL_GL_SetAttribute( SDL_GL_RED_SIZE, perChannelColorBits ); + SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, perChannelColorBits ); + SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, perChannelColorBits ); + SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, alphaBits ); + SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, testDepthBits ); + SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, testStencilBits ); + + SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, samples ? 1 : 0 ); + SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, samples ); + + if(r_stereoEnabled->integer) + { + glConfig.stereoEnabled = qtrue; + SDL_GL_SetAttribute(SDL_GL_STEREO, 1); + } + else + { + glConfig.stereoEnabled = qfalse; + SDL_GL_SetAttribute(SDL_GL_STEREO, 0); + } + + SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); + +#if 0 // if multisampling is enabled on X11, this causes create window to fail. + // If not allowing software GL, demand accelerated + if( !r_allowSoftwareGL->integer ) + SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 ); +#endif + + if( ( SDL_window = SDL_CreateWindow( CLIENT_WINDOW_TITLE, x, y, + glConfig.vidWidth, glConfig.vidHeight, flags ) ) == NULL ) + { + ri.Printf( PRINT_DEVELOPER, "SDL_CreateWindow failed: %s\n", SDL_GetError( ) ); + continue; + } + + if( fullscreen ) + { + SDL_DisplayMode mode; + + switch( testColorBits ) + { + case 16: mode.format = SDL_PIXELFORMAT_RGB565; break; + case 24: mode.format = SDL_PIXELFORMAT_RGB24; break; + default: ri.Printf( PRINT_DEVELOPER, "testColorBits is %d, can't fullscreen\n", testColorBits ); continue; + } + + mode.w = glConfig.vidWidth; + mode.h = glConfig.vidHeight; + mode.refresh_rate = glConfig.displayFrequency = ri.Cvar_VariableIntegerValue( "r_displayRefresh" ); + mode.driverdata = NULL; + + if( SDL_SetWindowDisplayMode( SDL_window, &mode ) < 0 ) + { + ri.Printf( PRINT_DEVELOPER, "SDL_SetWindowDisplayMode failed: %s\n", SDL_GetError( ) ); + continue; + } + } + + SDL_SetWindowIcon( SDL_window, icon ); + + if (coreContext) + { + int profileMask, majorVersion, minorVersion; + SDL_GL_GetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, &profileMask); + SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &majorVersion); + SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &minorVersion); + + ri.Printf(PRINT_ALL, "Trying to get an OpenGL 3.2 core context\n"); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); + if ((SDL_glContext = SDL_GL_CreateContext(SDL_window)) == NULL) + { + ri.Printf(PRINT_ALL, "SDL_GL_CreateContext failed: %s\n", SDL_GetError()); + ri.Printf(PRINT_ALL, "Reverting to default context\n"); + + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, profileMask); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, majorVersion); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minorVersion); + } + else + { + ri.Printf(PRINT_ALL, "SDL_GL_CreateContext succeeded.\n"); + + const char *renderer = (const char*)qglGetString(GL_RENDERER); + if (renderer && (strstr(renderer, "Software Renderer") || strstr(renderer, "Software Rasterizer"))) + { + ri.Printf(PRINT_ALL, "GL_RENDERER is %s, rejecting context\n", renderer); + + SDL_GL_DeleteContext(SDL_glContext); + SDL_glContext = NULL; + + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, profileMask); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, majorVersion); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minorVersion); + } + } + } + else + { + SDL_glContext = NULL; + } + + if( !SDL_glContext && ( SDL_glContext = SDL_GL_CreateContext( SDL_window ) ) == NULL ) + { + ri.Printf( PRINT_DEVELOPER, "SDL_GL_CreateContext failed: %s\n", SDL_GetError( ) ); + continue; + } + + qglClearColor( 0, 0, 0, 1 ); + qglClear( GL_COLOR_BUFFER_BIT ); + SDL_GL_SwapWindow( SDL_window ); + + if( SDL_GL_SetSwapInterval( r_swapInterval->integer ) == -1 ) + { + ri.Printf( PRINT_DEVELOPER, "SDL_GL_SetSwapInterval failed: %s\n", SDL_GetError( ) ); + } + + glConfig.colorBits = testColorBits; + glConfig.depthBits = testDepthBits; + glConfig.stencilBits = testStencilBits; + + ri.Printf( PRINT_ALL, "Using %d color bits, %d depth, %d stencil display.\n", + glConfig.colorBits, glConfig.depthBits, glConfig.stencilBits ); + break; + } + + SDL_FreeSurface( icon ); + + if( !SDL_window ) + { + ri.Printf( PRINT_ALL, "Couldn't get a visual\n" ); + return RSERR_INVALID_MODE; + } + + GLimp_DetectAvailableModes(); + + glstring = (char *) qglGetString (GL_RENDERER); + ri.Printf( PRINT_ALL, "GL_RENDERER: %s\n", glstring ); + + return RSERR_OK; +} + +/* +=============== +GLimp_StartDriverAndSetMode +=============== +*/ +static bool GLimp_StartDriverAndSetMode( bool failSafe, bool fullscreen, bool noborder, bool gl3Core ) +{ + if (!SDL_WasInit(SDL_INIT_VIDEO)) + { + + if (SDL_Init(SDL_INIT_VIDEO) != 0) + { + ri.Printf( PRINT_ALL, "SDL_Init( SDL_INIT_VIDEO ) FAILED (%s)\n", SDL_GetError()); + return false; + } + + const char *driverName = SDL_GetCurrentVideoDriver( ); + ri.Printf( PRINT_ALL, "SDL using driver \"%s\"\n", driverName ); + ri.Cvar_Set( "r_sdlDriver", driverName ); + } + + if (fullscreen && ri.Cvar_VariableIntegerValue( "in_nograb" ) ) + { + ri.Printf( PRINT_ALL, "Fullscreen not allowed with in_nograb 1\n"); + ri.Cvar_Set( "r_fullscreen", "0" ); + r_fullscreen->modified = qfalse; + fullscreen = false; + } + + rserr_t err = (rserr_t)GLimp_SetMode( failSafe, fullscreen, noborder, gl3Core ); + + switch ( err ) + { + case RSERR_INVALID_FULLSCREEN: + ri.Printf( PRINT_ALL, "...WARNING: fullscreen unavailable in this mode\n" ); + return false; + case RSERR_INVALID_MODE: + ri.Printf( PRINT_ALL, "...WARNING: could not set the given mode\n" ); + return false; + default: + break; + } + + return true; +} + +static bool GLimp_HaveExtension(const char *ext) +{ + const char *ptr = Q_stristr( glConfig.extensions_string, ext ); + if (ptr == NULL) + return qfalse; + ptr += strlen(ext); + return ((*ptr == ' ') || (*ptr == '\0')); // verify it's complete string. +} + + +/* +=============== +GLimp_InitExtensions +=============== +*/ +static void GLimp_InitExtensions( void ) +{ + if ( !r_allowExtensions->integer ) + { + ri.Printf( PRINT_ALL, "* IGNORING OPENGL EXTENSIONS *\n" ); + return; + } + + ri.Printf( PRINT_ALL, "Initializing OpenGL extensions\n" ); + + glConfig.textureCompression = TC_NONE; + + // GL_EXT_texture_compression_s3tc + if ( GLimp_HaveExtension( "GL_ARB_texture_compression" ) && + GLimp_HaveExtension( "GL_EXT_texture_compression_s3tc" ) ) + { + if ( r_ext_compressed_textures->value ) + { + glConfig.textureCompression = TC_S3TC_ARB; + ri.Printf( PRINT_ALL, "...using GL_EXT_texture_compression_s3tc\n" ); + } + else + { + ri.Printf( PRINT_ALL, "...ignoring GL_EXT_texture_compression_s3tc\n" ); + } + } + else + { + ri.Printf( PRINT_ALL, "...GL_EXT_texture_compression_s3tc not found\n" ); + } + + // GL_S3_s3tc ... legacy extension before GL_EXT_texture_compression_s3tc. + if (glConfig.textureCompression == TC_NONE) + { + if ( GLimp_HaveExtension( "GL_S3_s3tc" ) ) + { + if ( r_ext_compressed_textures->value ) + { + glConfig.textureCompression = TC_S3TC; + ri.Printf( PRINT_ALL, "...using GL_S3_s3tc\n" ); + } + else + { + ri.Printf( PRINT_ALL, "...ignoring GL_S3_s3tc\n" ); + } + } + else + { + ri.Printf( PRINT_ALL, "...GL_S3_s3tc not found\n" ); + } + } + + + // GL_EXT_texture_env_add + glConfig.textureEnvAddAvailable = qfalse; + if ( GLimp_HaveExtension( "GL_EXT_texture_env_add" ) ) + { + if ( r_ext_texture_env_add->integer ) + { + glConfig.textureEnvAddAvailable = qtrue; + ri.Printf( PRINT_ALL, "...using GL_EXT_texture_env_add\n" ); + } + else + { + glConfig.textureEnvAddAvailable = qfalse; + ri.Printf( PRINT_ALL, "...ignoring GL_EXT_texture_env_add\n" ); + } + } + else + { + ri.Printf( PRINT_ALL, "...GL_EXT_texture_env_add not found\n" ); + } + + // GL_ARB_multitexture + qglMultiTexCoord2fARB = NULL; + qglActiveTextureARB = NULL; + qglClientActiveTextureARB = NULL; + if ( GLimp_HaveExtension( "GL_ARB_multitexture" ) ) + { + if ( r_ext_multitexture->value ) + { + qglMultiTexCoord2fARB = (decltype(qglMultiTexCoord2fARB)) SDL_GL_GetProcAddress( "glMultiTexCoord2fARB" ); + qglActiveTextureARB = (decltype(qglActiveTextureARB)) SDL_GL_GetProcAddress( "glActiveTextureARB" ); + qglClientActiveTextureARB = (decltype(qglClientActiveTextureARB)) SDL_GL_GetProcAddress( "glClientActiveTextureARB" ); + + if ( qglActiveTextureARB ) + { + GLint glint = 0; + qglGetIntegerv( GL_MAX_TEXTURE_UNITS_ARB, &glint ); + glConfig.numTextureUnits = (int) glint; + if ( glConfig.numTextureUnits > 1 ) + { + ri.Printf( PRINT_ALL, "...using GL_ARB_multitexture\n" ); + } + else + { + qglMultiTexCoord2fARB = NULL; + qglActiveTextureARB = NULL; + qglClientActiveTextureARB = NULL; + ri.Printf( PRINT_ALL, "...not using GL_ARB_multitexture, < 2 texture units\n" ); + } + } + } + else + { + ri.Printf( PRINT_ALL, "...ignoring GL_ARB_multitexture\n" ); + } + } + else + { + ri.Printf( PRINT_ALL, "...GL_ARB_multitexture not found\n" ); + } + + // GL_EXT_compiled_vertex_array + if ( GLimp_HaveExtension( "GL_EXT_compiled_vertex_array" ) ) + { + if ( r_ext_compiled_vertex_array->value ) + { + ri.Printf( PRINT_ALL, "...using GL_EXT_compiled_vertex_array\n" ); + qglLockArraysEXT = ( void ( APIENTRY * )( GLint, GLint ) ) SDL_GL_GetProcAddress( "glLockArraysEXT" ); + qglUnlockArraysEXT = ( void ( APIENTRY * )( void ) ) SDL_GL_GetProcAddress( "glUnlockArraysEXT" ); + if (!qglLockArraysEXT || !qglUnlockArraysEXT) + { + ri.Error (ERR_FATAL, "bad getprocaddress"); + } + } + else + { + ri.Printf( PRINT_ALL, "...ignoring GL_EXT_compiled_vertex_array\n" ); + } + } + else + { + ri.Printf( PRINT_ALL, "...GL_EXT_compiled_vertex_array not found\n" ); + } + + glConfig.textureFilterAnisotropic = qfalse; + if ( GLimp_HaveExtension( "GL_EXT_texture_filter_anisotropic" ) ) + { + if ( r_ext_texture_filter_anisotropic->integer ) { + qglGetIntegerv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, (GLint *)&glConfig.maxAnisotropy ); + if ( glConfig.maxAnisotropy <= 0 ) { + ri.Printf( PRINT_ALL, "...GL_EXT_texture_filter_anisotropic not properly supported!\n" ); + glConfig.maxAnisotropy = 0; + } + else + { + ri.Printf( PRINT_ALL, "...using GL_EXT_texture_filter_anisotropic (max: %i)\n", glConfig.maxAnisotropy ); + glConfig.textureFilterAnisotropic = qtrue; + } + } + else + { + ri.Printf( PRINT_ALL, "...ignoring GL_EXT_texture_filter_anisotropic\n" ); + } + } + else + { + ri.Printf( PRINT_ALL, "...GL_EXT_texture_filter_anisotropic not found\n" ); + } +} + +/* +=============== +GLimp_Init + +This routine is responsible for initializing the OS specific portions +of OpenGL +=============== +*/ +void GLimp_Init(bool coreContext) +{ + ri.Printf( PRINT_DEVELOPER, "Glimp_Init( )\n" ); + + r_allowSoftwareGL = ri.Cvar_Get( "r_allowSoftwareGL", "0", CVAR_LATCH ); + r_sdlDriver = ri.Cvar_Get( "r_sdlDriver", "", CVAR_ROM ); + r_allowResize = ri.Cvar_Get( "r_allowResize", "0", CVAR_ARCHIVE | CVAR_LATCH ); + r_centerWindow = ri.Cvar_Get( "r_centerWindow", "0", CVAR_ARCHIVE | CVAR_LATCH ); + +#ifndef DEBUG + if( ri.Cvar_VariableIntegerValue( "com_abnormalExit" ) ) + { + ri.Cvar_Set( "r_width", va( "%d", R_FAILSAFE_WIDTH ) ); + ri.Cvar_Set( "r_height", va( "%d", R_FAILSAFE_HEIGHT ) ); + ri.Cvar_Set( "r_fullscreen", "0" ); + ri.Cvar_Set( "r_centerWindow", "0" ); + ri.Cvar_Set( "com_abnormalExit", "0" ); + } +#endif + + ri.Sys_GLimpInit( ); + + // Create the window and set up the context + if( GLimp_StartDriverAndSetMode( false, r_fullscreen->integer, r_noborder->integer, coreContext ) ) + goto success; + + // Try again, this time in a platform specific "safe mode" + ri.Sys_GLimpSafeInit( ); + + if( GLimp_StartDriverAndSetMode( false, r_fullscreen->integer, false, coreContext ) ) + goto success; + + // Finally, try the default screen resolution + if( GLimp_StartDriverAndSetMode( true, r_fullscreen->integer, false, coreContext ) ) + goto success; + + // Nothing worked, give up + ri.Error( ERR_FATAL, "GLimp_Init() - could not load OpenGL subsystem" ); + +success: + // These values force the UI to disable driver selection + glConfig.driverType = GLDRV_ICD; + glConfig.hardwareType = GLHW_GENERIC; + + // Only using SDL_SetWindowBrightness to determine if hardware gamma is supported + glConfig.deviceSupportsGamma = (qboolean)(!r_ignorehwgamma->integer && SDL_SetWindowBrightness( SDL_window, 1.0f ) >= 0); + + // get our config strings + Q_strncpyz( glConfig.vendor_string, (char *) qglGetString (GL_VENDOR), sizeof( glConfig.vendor_string ) ); + Q_strncpyz( glConfig.renderer_string, (char *) qglGetString (GL_RENDERER), sizeof( glConfig.renderer_string ) ); + if (*glConfig.renderer_string && glConfig.renderer_string[strlen(glConfig.renderer_string) - 1] == '\n') + glConfig.renderer_string[strlen(glConfig.renderer_string) - 1] = 0; + Q_strncpyz( glConfig.version_string, (char *) qglGetString (GL_VERSION), sizeof( glConfig.version_string ) ); + if (qglGetString(GL_EXTENSIONS)) + Q_strncpyz( glConfig.extensions_string, (char *) qglGetString (GL_EXTENSIONS), sizeof( glConfig.extensions_string ) ); + else + Q_strncpyz( glConfig.extensions_string, "Not available (core context, fixme)", sizeof( glConfig.extensions_string ) ); + + // initialize extensions + GLimp_InitExtensions( ); + + ri.Cvar_Get( "r_availableModes", "", CVAR_ROM ); + + // This depends on SDL_INIT_VIDEO, hence having it here + ri.IN_Init( SDL_window ); +} + + +/* +=============== +GLimp_EndFrame + +Responsible for doing a swapbuffers +=============== +*/ +void GLimp_EndFrame( void ) +{ + // don't flip if drawing to front buffer + if ( Q_stricmp( r_drawBuffer->string, "GL_FRONT" ) != 0 ) + { + SDL_GL_SwapWindow( SDL_window ); + } + + if( r_fullscreen->modified ) + { + int fullscreen; + bool needToToggle; + bool sdlToggled = false; + + // Find out the current state + fullscreen = !!( SDL_GetWindowFlags( SDL_window ) & SDL_WINDOW_FULLSCREEN ); + + if( r_fullscreen->integer && ri.Cvar_VariableIntegerValue( "in_nograb" ) ) + { + ri.Printf( PRINT_ALL, "Fullscreen not allowed with in_nograb 1\n"); + ri.Cvar_Set( "r_fullscreen", "0" ); + r_fullscreen->modified = false; + } + + // Is the state we want different from the current state? + needToToggle = !!r_fullscreen->integer != fullscreen; + + if( needToToggle ) + { + sdlToggled = SDL_SetWindowFullscreen( SDL_window, r_fullscreen->integer ) >= 0; + + // SDL_WM_ToggleFullScreen didn't work, so do it the slow way + if( !sdlToggled ) + ri.Cmd_ExecuteText(EXEC_APPEND, "vid_restart\n"); + + ri.IN_Restart( ); + } + + r_fullscreen->modified = false; + } +} diff --git a/src/sdl/sdl_icon.h b/src/sdl/sdl_icon.h new file mode 100644 index 0000000..03f7420 --- /dev/null +++ b/src/sdl/sdl_icon.h @@ -0,0 +1,138 @@ +/* GIMP RGBA C-Source image dump (sdl_icon.h) */ + +static const struct { + unsigned int width; + unsigned int height; + unsigned int bytes_per_pixel; /* 3:RGB, 4:RGBA */ + unsigned char pixel_data[32 * 32 * 4 + 1]; +} CLIENT_WINDOW_ICON = { + 32, 32, 4, + "\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\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\0\0\0\0\0\0\0\0\0\0\0\0\17\17\17\34\17\17" + "\17U\17\17\17""9\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\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\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\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\0\0\0\0\0\0\0\0\30\30\30q\2\2\2\306\5\5\5\377\4\4\4\343\33\33\33" + "\252\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\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\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\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\31\31" + "\31\216\7\7\7\377\0\0\0\377\0\0\0\377\0\0\0\377\3\3\3\377\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\0\0\0\0\0\0\0\0\0\0\0\0\0\0%%%9\0\0" + "\0\0\0\0\0\0\10\10\10q\16\16\16q\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\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\11\11\11\377\0\0\0\377\0" + "\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\13\13\13q\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\0\0\0\0\0\0\14\14\14q\15\15\15\343\16\16\16" + """9\0\0\0\0\12\12\12\252\10\10\10\377\30\30\30U\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\0\0\0\0\0\0\0\0\0\0\0\0\0\0\3\3\3\377\0\0\0\377" + "\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\252\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\0\0\12\12\12\216\3\3\3\377\2\2\2\252\0\0\0" + "\0\0\0\0\0\37\37\37""9\3\3\3\377\3\3\3\306\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\0\0\0\0\0\0\0\0\0\0\0\0\0\0\2\2\2\377\0\0\0\377\0" + "\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\3\3\3\343\15\15\15""9\0\0\0\0\0\0" + "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\14\14\14q\3\3\3\377\2\2\2\377\5\5\5""9\0\0\0" + "\0\0\0\0\0\0\0\0\0\16\16\16\306\2\2\2\377\2\2\2\306\5\5\5\34\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\0\0\36\36\36\252\0\0\0\377\0\0\0" + "\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\13\13\13\306\0\0\0" + "\0\0\0\0\0\0\0\0\0\0\0\0\0\13\13\13\216\3\3\3\377\4\4\4\377\15\15\15U\0\0" + "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\17\17\17\34\14\14\14\306\1\1\1\377\2\2\2\306" + "\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\0\0\36\36\36\252\0\0" + "\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0" + "U\0\0\0\0\0\0\0\0(((9\16\16\16\252\3\3\3\377\0\0\0\377\16\16\16\306\36\36" + "\36\34\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\0\306\0\0\0\377" + "\3\3\3\306\3\3\3\34\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\36\36\36q\0\0" + "\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\6\6\6\343\31\31" + "\31""9\0\0\0\0\0\0\0\0\0\0\0\216\0\0\0\377\2\2\2\377\12\12\12\306\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\0\0\0\0\0\0\26\26\26U\7\7\7" + "\377\0\0\0\377\3\3\3\306\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" + "\3\3\3\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\6\6\6\252\0" + "\0\0\0\15\15\15""9\6\6\6\252\0\0\0\377\0\0\0\377\12\12\12\306\16\16\16\34" + "\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\0\0\0\0\0\0\0\0\0\0" + "\6\6\6q\1\1\1\377\0\0\0\377\4\4\4\306\5\5\5\34\0\0\0\0\0\0\0\0\22\22\22\34" + "\32\32\32\306\1\1\1\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377" + "\21\21\21\216\33\33\33\306\3\3\3\377\0\0\0\377\1\1\1\377\11\11\11\306\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\0\0\0\0\0\0\0\0\0\0\0\0" + "\0\0\0\0\0\0\0\0\0\0\3\3\3\216\1\1\1\377\1\1\1\377\4\4\4\306\0\0\0\0\0\0" + "\0\0\14\14\14U\4\4\4\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377" + "\0\0\0\377\4\4\4\306\3\3\3\377\0\0\0\377\0\0\0\377\11\11\11\306\15\15\15" + "\34\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\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\5\5\5\252\0\0\0\377\0\0\0\377\3\3\3\377" + "\5\5\5\377\3\3\3\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0" + "\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\1\1\1\343\12\12\12\252\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\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\0\0\0\0\0\0\0\0\16\16\16""9\7\7\7\377\0\0\0\377\0\0" + "\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0" + "\377\0\0\0\377\0\0\0\377\0\0\0\377\2\2\2\377\2\2\2""9\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\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\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\2\2\2q\3\3\3\377\0\0" + "\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0" + "\377\0\0\0\377\0\0\0\377\0\0\0U\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\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\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\0\0\20\20\20\216\5\5\5\377\0\0" + "\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0" + "\377\0\0\0\377\0\0\0\306\0\0\0\252\0\0\0\252\0\0\0\252\0\0\0\252\0\0\0\252" + "\0\0\0\252\12\12\12\252\36\36\36""9\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\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\15\15\15U\6\6" + "\6\306\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0" + "\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\1\1\1\377\0\0\0\252\0\0\0\252" + "\0\0\0\252\0\0\0\252\12\12\12\252\36\36\36""9\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\0\0\0\0\0\0\0\0\0\0\0\0\0\0\14\14\14""9\4\4\4\252" + "\4\4\4\377\1\1\1\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0" + "\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\2\2\2\216\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\0\0\0\0\0\0\0\0\0\0\0\0" + "\0\0\0\0\0\0\0\0\0\0\31\31\31U\20\20\20\306\5\5\5\377\0\0\0\377\0\0\0\377" + "\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0" + "\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\12\12\12\343\26" + "\26\26""9\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\0\0\0\0\0\0" + "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\10\10\10\377\0\0\0\377\5\5\5\377\5\5\5\377" + "\0\0\0U\6\6\6\306\1\1\1\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0" + "\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\24\24\24" + """9\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\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\"\"\"\252###\252\0\0\0\0\0\0\0\0\0\0\0" + "\0\0\0\0\0\21\21\21""9\7\7\7\343\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377" + "\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\20\20\20\306" + "\30\30\30\34\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\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\0\0\0\0\0\0\0\0\0\0\0\0\0\0" + "\0\0\0\0\0\0\0\0\0\0\7\7\7\252\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0" + "\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\3\3\3\377\22\22" + "\22\306\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\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\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" + "\0\0\0\23\23\23U\6\6\6\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0" + "\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377" + "\22\22\22\306\36\36\36\34\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\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\0\0\0\0\0\0\0\0" + "\0\0\0\0\14\14\14\306\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0" + "\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\2\2\2\377\4\4\4\216\3\3\3\216\2\2" + "\2\377\5\5\5\377\17\17\17U\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\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\0\0\0\0\0\0\0" + "\0\0\0\0\0\2\2\2\377\4\4\4\377\1\1\1\252\1\1\1\252\4\4\4\377\0\0\0\377\0" + "\0\0\377\0\0\0\377\0\0\0\377\2\2\2\377\11\11\11q\0\0\0\0\0\0\0\0\6\6\6q\2" + "\2\2\377\4\4\4\377\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\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\0\0\0\0\0\0\0\0\14\14" + "\14q\0\0\0\377\6\6\6\216\0\0\0\0\0\0\0\0\15\15\15U\2\2\2\306\0\0\0\377\0" + "\0\0\377\1\1\1\306\7\7\7U\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\5\5\5\216\1\1\1" + "\377\3\3\3q\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\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\0\0\0\0\3\3\3\252\2\2\2\377\5" + "\5\5U\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\31\31\31""9\31\31\31\252\0\0\0\0\0" + "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\26\26\26""9\13\13\13\343\5\5\5\377" + "\30\30\30\216\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\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\2\2\2\252\6\6\6\377\21\21\21" + "U\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\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\26\26\26""9\10\10\10\377\14\14\14\377\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\0\0\0\0\0\0\0\0\0\0\0" + "\0\0\0\0\0\0\0\0\0\0\0\32\32\32U\11\11\11\377\0\0\0\252\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\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\0\0\0\0\0\0\0\0\2\2\2""9\12\12\12\343\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\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" + "\0\0\32\32\32U\11\11\11\377\33\33\33\252\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\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" + "\0\0\0\0\0\0\0\0\0\0\0\0%%%9\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\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\32\32\32""9\12\12\12" + "\343\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\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\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\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\0\0" + "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\17\17\17""9\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\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\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\0\0\0\0\0\0" + "\0\0\0\0", +}; + diff --git a/src/sdl/sdl_input.cpp b/src/sdl/sdl_input.cpp new file mode 100644 index 0000000..1e1056a --- /dev/null +++ b/src/sdl/sdl_input.cpp @@ -0,0 +1,1336 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. +Copyright (C) 2000-2013 Darklegion Development +Copyright (C) 2015-2019 GrangerHub + +This file is part of Tremulous. + +Tremulous is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 3 of the License, +or (at your option) any later version. + +Tremulous is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Tremulous; if not, see <https://www.gnu.org/licenses/> + +=========================================================================== +*/ + +#include <cstdarg> +#include <cstdio> +#include <cstdlib> + +#ifdef USE_LOCAL_HEADERS +# include "SDL.h" +#else +# include <SDL.h> +#endif + +#include "client/client.h" +#include "sys/sys_local.h" + +static cvar_t *in_keyboardDebug = NULL; + +static SDL_GameController *gamepad = NULL; +static SDL_Joystick *stick = NULL; + +static bool mouseAvailable = false; +static bool mouseActive = false; + +static cvar_t *in_mouse = NULL; +static cvar_t *in_nograb; + +static cvar_t *in_joystick = NULL; +static cvar_t *in_joystickThreshold = NULL; +static cvar_t *in_joystickNo = NULL; +static cvar_t *in_joystickUseAnalog = NULL; + +static int vidRestartTime = 0; +static int in_eventTime = 0; + +static SDL_Window *SDL_window = NULL; + +#define CTRL(a) ((a)-'a'+1) + +/* +=============== +IN_PrintKey +=============== +*/ +static void IN_PrintKey( const SDL_Keysym *keysym, keyNum_t key, bool down ) +{ + if( down ) + Com_Printf( "+ " ); + else + Com_Printf( " " ); + + Com_Printf( "Scancode: 0x%02x(%s) Sym: 0x%02x(%s)", + keysym->scancode, SDL_GetScancodeName( keysym->scancode ), + keysym->sym, SDL_GetKeyName( keysym->sym ) ); + + if( keysym->mod & KMOD_LSHIFT ) Com_Printf( " KMOD_LSHIFT" ); + if( keysym->mod & KMOD_RSHIFT ) Com_Printf( " KMOD_RSHIFT" ); + if( keysym->mod & KMOD_LCTRL ) Com_Printf( " KMOD_LCTRL" ); + if( keysym->mod & KMOD_RCTRL ) Com_Printf( " KMOD_RCTRL" ); + if( keysym->mod & KMOD_LALT ) Com_Printf( " KMOD_LALT" ); + if( keysym->mod & KMOD_RALT ) Com_Printf( " KMOD_RALT" ); + if( keysym->mod & KMOD_LGUI ) Com_Printf( " KMOD_LGUI" ); + if( keysym->mod & KMOD_RGUI ) Com_Printf( " KMOD_RGUI" ); + if( keysym->mod & KMOD_NUM ) Com_Printf( " KMOD_NUM" ); + if( keysym->mod & KMOD_CAPS ) Com_Printf( " KMOD_CAPS" ); + if( keysym->mod & KMOD_MODE ) Com_Printf( " KMOD_MODE" ); + if( keysym->mod & KMOD_RESERVED ) Com_Printf( " KMOD_RESERVED" ); + + Com_Printf( " Q:0x%02x(%s)\n", key, Key_KeynumToString( key ) ); +} + +#define MAX_CONSOLE_KEYS 16 + +/* +=============== +IN_IsConsoleKey + +TODO: If the SDL_Scancode situation improves, use it instead of + both of these methods +=============== +*/ +static bool IN_IsConsoleKey( keyNum_t key, int character ) +{ + typedef struct consoleKey_s + { + enum + { + QUAKE_KEY, + CHARACTER + } type; + + union + { + keyNum_t key; + int character; + } u; + } consoleKey_t; + + static consoleKey_t consoleKeys[ MAX_CONSOLE_KEYS ]; + static int numConsoleKeys = 0; + int i; + + // Only parse the variable when it changes + if( cl_consoleKeys->modified ) + { + char *text_p, *token; + + cl_consoleKeys->modified = qfalse; + text_p = cl_consoleKeys->string; + numConsoleKeys = 0; + + while( numConsoleKeys < MAX_CONSOLE_KEYS ) + { + consoleKey_t *c = &consoleKeys[ numConsoleKeys ]; + int charCode = 0; + + token = COM_Parse( &text_p ); + if( !token[ 0 ] ) + break; + + if( strlen( token ) == 4 ) + charCode = Com_HexStrToInt( token ); + + if( charCode > 0 ) + { + c->type = consoleKey_s::CHARACTER; + c->u.character = charCode; + } + else + { + c->type = consoleKey_s::QUAKE_KEY; + c->u.key = (keyNum_t)Key_StringToKeynum( token ); + + // 0 isn't a key + if( c->u.key <= 0 ) + continue; + } + + numConsoleKeys++; + } + } + + // If the character is the same as the key, prefer the character + if( key == character ) + key = (keyNum_t)0; + + for( i = 0; i < numConsoleKeys; i++ ) + { + consoleKey_t *c = &consoleKeys[ i ]; + + switch( c->type ) + { + case consoleKey_s::QUAKE_KEY: + if( key && c->u.key == key ) + return true; + break; + + case consoleKey_s::CHARACTER: + if( c->u.character == character ) + return true; + break; + } + } + + return false; +} + +/* +=============== +IN_TranslateSDLToQ3Key +=============== +*/ +static keyNum_t IN_TranslateSDLToQ3Key( SDL_Keysym *keysym, bool down ) +{ + keyNum_t key = (keyNum_t)0; + + if( keysym->scancode >= SDL_SCANCODE_1 && keysym->scancode <= SDL_SCANCODE_0 ) + { + // Always map the number keys as such even if they actually map + // to other characters (eg, "1" is "&" on an AZERTY keyboard). + // This is required for SDL before 2.0.6, except on Windows + // which already had this behavior. + if( keysym->scancode == SDL_SCANCODE_0 ) + key = static_cast<keyNum_t>('0'); + else + key = static_cast<keyNum_t>('1' + keysym->scancode - SDL_SCANCODE_1); + } + else if( keysym->sym >= SDLK_SPACE && keysym->sym < SDLK_DELETE ) + { + // These happen to match the ASCII chars + key = (keyNum_t)keysym->sym; + } + else + { + switch( keysym->sym ) + { + case SDLK_PAGEUP: key = K_PGUP; break; + case SDLK_KP_9: key = K_KP_PGUP; break; + case SDLK_PAGEDOWN: key = K_PGDN; break; + case SDLK_KP_3: key = K_KP_PGDN; break; + case SDLK_KP_7: key = K_KP_HOME; break; + case SDLK_HOME: key = K_HOME; break; + case SDLK_KP_1: key = K_KP_END; break; + case SDLK_END: key = K_END; break; + case SDLK_KP_4: key = K_KP_LEFTARROW; break; + case SDLK_LEFT: key = K_LEFTARROW; break; + case SDLK_KP_6: key = K_KP_RIGHTARROW; break; + case SDLK_RIGHT: key = K_RIGHTARROW; break; + case SDLK_KP_2: key = K_KP_DOWNARROW; break; + case SDLK_DOWN: key = K_DOWNARROW; break; + case SDLK_KP_8: key = K_KP_UPARROW; break; + case SDLK_UP: key = K_UPARROW; break; + case SDLK_ESCAPE: key = K_ESCAPE; break; + case SDLK_KP_ENTER: key = K_KP_ENTER; break; + case SDLK_RETURN: key = K_ENTER; break; + case SDLK_TAB: key = K_TAB; break; + case SDLK_F1: key = K_F1; break; + case SDLK_F2: key = K_F2; break; + case SDLK_F3: key = K_F3; break; + case SDLK_F4: key = K_F4; break; + case SDLK_F5: key = K_F5; break; + case SDLK_F6: key = K_F6; break; + case SDLK_F7: key = K_F7; break; + case SDLK_F8: key = K_F8; break; + case SDLK_F9: key = K_F9; break; + case SDLK_F10: key = K_F10; break; + case SDLK_F11: key = K_F11; break; + case SDLK_F12: key = K_F12; break; + case SDLK_F13: key = K_F13; break; + case SDLK_F14: key = K_F14; break; + case SDLK_F15: key = K_F15; break; + + case SDLK_BACKSPACE: key = K_BACKSPACE; break; + case SDLK_KP_PERIOD: key = K_KP_DEL; break; + case SDLK_DELETE: key = K_DEL; break; + case SDLK_PAUSE: key = K_PAUSE; break; + + case SDLK_LSHIFT: + case SDLK_RSHIFT: key = K_SHIFT; break; + + case SDLK_LCTRL: + case SDLK_RCTRL: key = K_CTRL; break; + +#ifdef __APPLE__ + case SDLK_RGUI: + case SDLK_LGUI: key = K_COMMAND; break; +#else + case SDLK_RGUI: + case SDLK_LGUI: key = K_SUPER; break; +#endif + + case SDLK_RALT: + case SDLK_LALT: key = K_ALT; break; + + case SDLK_KP_5: key = K_KP_5; break; + case SDLK_INSERT: key = K_INS; break; + case SDLK_KP_0: key = K_KP_INS; break; + case SDLK_KP_MULTIPLY: key = K_KP_STAR; break; + case SDLK_KP_PLUS: key = K_KP_PLUS; break; + case SDLK_KP_MINUS: key = K_KP_MINUS; break; + case SDLK_KP_DIVIDE: key = K_KP_SLASH; break; + + case SDLK_MODE: key = K_MODE; break; + case SDLK_HELP: key = K_HELP; break; + case SDLK_PRINTSCREEN: key = K_PRINT; break; + case SDLK_SYSREQ: key = K_SYSREQ; break; + case SDLK_MENU: key = K_MENU; break; + case SDLK_APPLICATION: key = K_MENU; break; + case SDLK_POWER: key = K_POWER; break; + case SDLK_UNDO: key = K_UNDO; break; + case SDLK_SCROLLLOCK: key = K_SCROLLOCK; break; + case SDLK_NUMLOCKCLEAR: key = K_KP_NUMLOCK; break; + case SDLK_CAPSLOCK: key = K_CAPSLOCK; break; + + default: + if( !( keysym->sym & SDLK_SCANCODE_MASK ) && keysym->scancode <= 95 ) + { + // Map Unicode characters to 95 world keys using the key's scan code. + // FIXME: There aren't enough world keys to cover all the scancodes. + // Maybe create a map of scancode to quake key at start up and on + // key map change; allocate world key numbers as needed similar + // to SDL 1.2. + key = static_cast<keyNum_t>(K_WORLD_0 + (int)keysym->scancode); + } + break; + } + } + + if( in_keyboardDebug->integer ) + IN_PrintKey( keysym, key, down ); + + if( IN_IsConsoleKey( key, 0 ) ) + { + // Console keys can't be bound or generate characters + key = K_CONSOLE; + } + + return key; +} + +/* +=============== +IN_GobbleMotionEvents +=============== +*/ +static void IN_GobbleMotionEvents( void ) +{ + SDL_Event dummy[ 1 ]; + int val = 0; + + // Gobble any mouse motion events + SDL_PumpEvents( ); + while( ( val = SDL_PeepEvents( dummy, 1, SDL_GETEVENT, + SDL_MOUSEMOTION, SDL_MOUSEMOTION ) ) > 0 ) { } + + if ( val < 0 ) + Com_Printf( "IN_GobbleMotionEvents failed: %s\n", SDL_GetError( ) ); +} + +/* +=============== +IN_GetUIMousePosition +=============== +*/ +static void IN_GetUIMousePosition( int *x, int *y ) +{ + if( cls.ui ) + { + int pos = VM_Call( cls.ui, UI_MOUSE_POSITION ); + *x = pos & 0xFFFF; + *y = ( pos >> 16 ) & 0xFFFF; + + *x = cls.glconfig.vidWidth * *x / 640; + *y = cls.glconfig.vidHeight * *y / 480; + } + else + { + *x = cls.glconfig.vidWidth / 2; + *y = cls.glconfig.vidHeight / 2; + } +} + +/* +=============== +IN_SetUIMousePosition +=============== +*/ +static void IN_SetUIMousePosition( int x, int y ) +{ + if( cls.ui ) + { + x = x * 640 / cls.glconfig.vidWidth; + y = y * 480 / cls.glconfig.vidHeight; + VM_Call( cls.ui, UI_SET_MOUSE_POSITION, x, y ); + } +} + +/* +=============== +IN_ActivateMouse +=============== +*/ +static void IN_ActivateMouse( void ) +{ + if (!mouseAvailable || !SDL_WasInit( SDL_INIT_VIDEO ) ) + return; + + if( !mouseActive ) + { + SDL_SetRelativeMouseMode( SDL_TRUE ); + SDL_SetWindowGrab( SDL_window, SDL_TRUE ); + + IN_GobbleMotionEvents( ); + } + + // in_nograb makes no sense in fullscreen mode + if( !cls.glconfig.isFullscreen ) + { + if( in_nograb->modified || !mouseActive ) + { + if( in_nograb->integer ) + { + SDL_SetRelativeMouseMode( SDL_FALSE ); + SDL_SetWindowGrab( SDL_window, SDL_FALSE ); + } + else + { + SDL_SetRelativeMouseMode( SDL_TRUE ); + SDL_SetWindowGrab( SDL_window, SDL_TRUE ); + } + in_nograb->modified = qfalse; + } + } + + mouseActive = true; +} + +/* +=============== +IN_DeactivateMouse +=============== +*/ +static void IN_DeactivateMouse( void ) +{ + if( !SDL_WasInit( SDL_INIT_VIDEO ) ) + return; + + // Always show the cursor when the mouse is disabled, + // but not when fullscreen + if( !cls.glconfig.isFullscreen ) + { + if( ( Key_GetCatcher( ) == KEYCATCH_UI ) && + SDL_GetWindowFlags( SDL_window ) & SDL_WINDOW_MOUSE_FOCUS ) + SDL_ShowCursor( 0 ); + else + SDL_ShowCursor( 1 ); + } + + if( !mouseAvailable ) + return; + + if( mouseActive ) + { + IN_GobbleMotionEvents( ); + + SDL_SetWindowGrab( SDL_window, SDL_FALSE ); + SDL_SetRelativeMouseMode( SDL_FALSE ); + + // Don't warp the mouse unless the cursor is within the window + if( SDL_GetWindowFlags( SDL_window ) & SDL_WINDOW_MOUSE_FOCUS && cls.uiInterface != 2 ) + { + int x, y; + IN_GetUIMousePosition( &x, &y ); + SDL_WarpMouseInWindow( SDL_window, x, y ); + } + + mouseActive = false; + } +} + +// We translate axes movement into keypresses +static int joy_keys[16] = { + K_LEFTARROW, K_RIGHTARROW, + K_UPARROW, K_DOWNARROW, + K_JOY17, K_JOY18, + K_JOY19, K_JOY20, + K_JOY21, K_JOY22, + K_JOY23, K_JOY24, + K_JOY25, K_JOY26, + K_JOY27, K_JOY28 +}; + +// translate hat events into keypresses +// the 4 highest buttons are used for the first hat ... +static int hat_keys[16] = { + K_JOY29, K_JOY30, + K_JOY31, K_JOY32, + K_JOY25, K_JOY26, + K_JOY27, K_JOY28, + K_JOY21, K_JOY22, + K_JOY23, K_JOY24, + K_JOY17, K_JOY18, + K_JOY19, K_JOY20 +}; + + +struct +{ + bool buttons[SDL_CONTROLLER_BUTTON_MAX + 1]; // +1 because old max was 16, current SDL_CONTROLLER_BUTTON_MAX is 15 + unsigned int oldaxes; + int oldaaxes[MAX_JOYSTICK_AXIS]; + unsigned int oldhats; +} stick_state; + + +/* +=============== +IN_InitJoystick +=============== +*/ +static void IN_InitJoystick( void ) +{ + int i = 0; + int total = 0; + char buf[16384] = ""; + + if (gamepad) + SDL_GameControllerClose(gamepad); + + if (stick != NULL) + SDL_JoystickClose(stick); + + stick = NULL; + gamepad = NULL; + memset(&stick_state, '\0', sizeof (stick_state)); + + // SDL 2.0.4 requires SDL_INIT_JOYSTICK to be initialized separately from + // SDL_INIT_GAMECONTROLLER for SDL_JoystickOpen() to work correctly, + // despite https://wiki.libsdl.org/SDL_Init (retrieved 2016-08-16) + // indicating SDL_INIT_JOYSTICK should be initialized automatically. + if (!SDL_WasInit(SDL_INIT_JOYSTICK)) + { + Com_DPrintf("Calling SDL_Init(SDL_INIT_JOYSTICK)...\n"); + if (SDL_Init(SDL_INIT_JOYSTICK) != 0) + { + Com_DPrintf("SDL_Init(SDL_INIT_JOYSTICK) failed: %s\n", SDL_GetError()); + return; + } + Com_DPrintf("SDL_Init(SDL_INIT_JOYSTICK) passed.\n"); + } + + if (!SDL_WasInit(SDL_INIT_GAMECONTROLLER)) + { + Com_DPrintf("Calling SDL_Init(SDL_INIT_GAMECONTROLLER)...\n"); + if (SDL_Init(SDL_INIT_GAMECONTROLLER) != 0) + { + Com_DPrintf("SDL_Init(SDL_INIT_GAMECONTROLLER) failed: %s\n", SDL_GetError()); + return; + } + Com_DPrintf("SDL_Init(SDL_INIT_GAMECONTROLLER) passed.\n"); + } + + total = SDL_NumJoysticks(); + Com_DPrintf("%d possible joysticks\n", total); + + // Print list and build cvar to allow ui to select joystick. + for (i = 0; i < total; i++) + { + Q_strcat(buf, sizeof(buf), SDL_JoystickNameForIndex(i)); + Q_strcat(buf, sizeof(buf), "\n"); + } + + Cvar_Get( "in_availableJoysticks", buf, CVAR_ROM ); + + if( !in_joystick->integer ) { + Com_DPrintf( "Joystick is not active.\n" ); + SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER); + return; + } + + in_joystickNo = Cvar_Get( "in_joystickNo", "0", CVAR_ARCHIVE ); + if( in_joystickNo->integer < 0 || in_joystickNo->integer >= total ) + Cvar_Set( "in_joystickNo", "0" ); + + in_joystickUseAnalog = Cvar_Get( "in_joystickUseAnalog", "0", CVAR_ARCHIVE ); + + stick = SDL_JoystickOpen( in_joystickNo->integer ); + + if (stick == NULL) { + Com_DPrintf( "No joystick opened: %s\n", SDL_GetError() ); + return; + } + + if (SDL_IsGameController(in_joystickNo->integer)) + gamepad = SDL_GameControllerOpen(in_joystickNo->integer); + + Com_DPrintf( "Joystick %d opened\n", in_joystickNo->integer ); + Com_DPrintf( "Name: %s\n", SDL_JoystickNameForIndex(in_joystickNo->integer) ); + Com_DPrintf( "Axes: %d\n", SDL_JoystickNumAxes(stick) ); + Com_DPrintf( "Hats: %d\n", SDL_JoystickNumHats(stick) ); + Com_DPrintf( "Buttons: %d\n", SDL_JoystickNumButtons(stick) ); + Com_DPrintf( "Balls: %d\n", SDL_JoystickNumBalls(stick) ); + Com_DPrintf( "Use Analog: %s\n", in_joystickUseAnalog->integer ? "Yes" : "No" ); + Com_DPrintf( "Is gamepad: %s\n", gamepad ? "Yes" : "No" ); + + SDL_JoystickEventState(SDL_QUERY); + SDL_GameControllerEventState(SDL_QUERY); +} + +/* +=============== +IN_ShutdownJoystick +=============== +*/ +static void IN_ShutdownJoystick( void ) +{ + if ( !SDL_WasInit( SDL_INIT_GAMECONTROLLER ) ) + return; + + if ( !SDL_WasInit( SDL_INIT_JOYSTICK ) ) + return; + + if (gamepad) + { + SDL_GameControllerClose(gamepad); + gamepad = NULL; + } + + if (stick) + { + SDL_JoystickClose(stick); + stick = NULL; + } + + SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER); + SDL_QuitSubSystem(SDL_INIT_JOYSTICK); +} + + +static bool KeyToAxisAndSign(int keynum, int *outAxis, int *outSign) +{ + if (!keynum) + return false; + + const char* bind = Key_GetBinding(keynum); + + if (!bind || *bind != '+') + return false; + + *outSign = 0; + + if (Q_stricmp(bind, "+forward") == 0) + { + *outAxis = j_forward_axis->integer; + *outSign = j_forward->value > 0.0f ? 1 : -1; + } + else if (Q_stricmp(bind, "+back") == 0) + { + *outAxis = j_forward_axis->integer; + *outSign = j_forward->value > 0.0f ? -1 : 1; + } + else if (Q_stricmp(bind, "+moveleft") == 0) + { + *outAxis = j_side_axis->integer; + *outSign = j_side->value > 0.0f ? -1 : 1; + } + else if (Q_stricmp(bind, "+moveright") == 0) + { + *outAxis = j_side_axis->integer; + *outSign = j_side->value > 0.0f ? 1 : -1; + } + else if (Q_stricmp(bind, "+lookup") == 0) + { + *outAxis = j_pitch_axis->integer; + *outSign = j_pitch->value > 0.0f ? -1 : 1; + } + else if (Q_stricmp(bind, "+lookdown") == 0) + { + *outAxis = j_pitch_axis->integer; + *outSign = j_pitch->value > 0.0f ? 1 : -1; + } + else if (Q_stricmp(bind, "+left") == 0) + { + *outAxis = j_yaw_axis->integer; + *outSign = j_yaw->value > 0.0f ? 1 : -1; + } + else if (Q_stricmp(bind, "+right") == 0) + { + *outAxis = j_yaw_axis->integer; + *outSign = j_yaw->value > 0.0f ? -1 : 1; + } + else if (Q_stricmp(bind, "+moveup") == 0) + { + *outAxis = j_up_axis->integer; + *outSign = j_up->value > 0.0f ? 1 : -1; + } + else if (Q_stricmp(bind, "+movedown") == 0) + { + *outAxis = j_up_axis->integer; + *outSign = j_up->value > 0.0f ? -1 : 1; + } + + return *outSign != 0; +} + +/* +=============== +IN_GamepadMove +=============== +*/ +static void IN_GamepadMove( void ) +{ + int i; + int translatedAxes[MAX_JOYSTICK_AXIS]; + bool translatedAxesSet[MAX_JOYSTICK_AXIS]; + + SDL_GameControllerUpdate(); + + // check buttons + for (i = 0; i < SDL_CONTROLLER_BUTTON_MAX; i++) + { + bool pressed = SDL_GameControllerGetButton(gamepad, (SDL_GameControllerButton)(SDL_CONTROLLER_BUTTON_A + i)); + if (pressed != stick_state.buttons[i]) + { + Com_QueueEvent(in_eventTime, SE_KEY, K_PAD0_A + i, pressed, 0, NULL); + stick_state.buttons[i] = pressed; + } + } + + // must defer translated axes until all real axes are processed + // must be done this way to prevent a later mapped axis from zeroing out a previous one + if (in_joystickUseAnalog->integer) + { + for (i = 0; i < MAX_JOYSTICK_AXIS; i++) + { + translatedAxes[i] = 0; + translatedAxesSet[i] = false; + } + } + + // check axes + for (i = 0; i < SDL_CONTROLLER_AXIS_MAX; i++) + { + int axis = SDL_GameControllerGetAxis(gamepad, (SDL_GameControllerAxis)(SDL_CONTROLLER_AXIS_LEFTX + i)); + int oldAxis = stick_state.oldaaxes[i]; + + // Smoothly ramp from dead zone to maximum value + float f = ((float)abs(axis) / 32767.0f - in_joystickThreshold->value) / (1.0f - in_joystickThreshold->value); + + if (f < 0.0f) + f = 0.0f; + + axis = (int)(32767 * ((axis < 0) ? -f : f)); + + if (axis != oldAxis) + { + const int negMap[SDL_CONTROLLER_AXIS_MAX] = { K_PAD0_LEFTSTICK_LEFT, K_PAD0_LEFTSTICK_UP, K_PAD0_RIGHTSTICK_LEFT, K_PAD0_RIGHTSTICK_UP, 0, 0 }; + const int posMap[SDL_CONTROLLER_AXIS_MAX] = { K_PAD0_LEFTSTICK_RIGHT, K_PAD0_LEFTSTICK_DOWN, K_PAD0_RIGHTSTICK_RIGHT, K_PAD0_RIGHTSTICK_DOWN, K_PAD0_LEFTTRIGGER, K_PAD0_RIGHTTRIGGER }; + + bool posAnalog = false, negAnalog = false; + int negKey = negMap[i]; + int posKey = posMap[i]; + + if (in_joystickUseAnalog->integer) + { + int posAxis = 0, posSign = 0, negAxis = 0, negSign = 0; + + // get axes and axes signs for keys if available + posAnalog = KeyToAxisAndSign(posKey, &posAxis, &posSign); + negAnalog = KeyToAxisAndSign(negKey, &negAxis, &negSign); + + // positive to negative/neutral -> keyup if axis hasn't yet been set + if (posAnalog && !translatedAxesSet[posAxis] && oldAxis > 0 && axis <= 0) + { + translatedAxes[posAxis] = 0; + translatedAxesSet[posAxis] = true; + } + + // negative to positive/neutral -> keyup if axis hasn't yet been set + if (negAnalog && !translatedAxesSet[negAxis] && oldAxis < 0 && axis >= 0) + { + translatedAxes[negAxis] = 0; + translatedAxesSet[negAxis] = true; + } + + // negative/neutral to positive -> keydown + if (posAnalog && axis > 0) + { + translatedAxes[posAxis] = axis * posSign; + translatedAxesSet[posAxis] = true; + } + + // positive/neutral to negative -> keydown + if (negAnalog && axis < 0) + { + translatedAxes[negAxis] = -axis * negSign; + translatedAxesSet[negAxis] = true; + } + } + + // keyups first so they get overridden by keydowns later + + // positive to negative/neutral -> keyup + if (!posAnalog && posKey && oldAxis > 0 && axis <= 0) + Com_QueueEvent(in_eventTime, SE_KEY, posKey, false, 0, NULL); + + // negative to positive/neutral -> keyup + if (!negAnalog && negKey && oldAxis < 0 && axis >= 0) + Com_QueueEvent(in_eventTime, SE_KEY, negKey, false, 0, NULL); + + // negative/neutral to positive -> keydown + if (!posAnalog && posKey && oldAxis <= 0 && axis > 0) + Com_QueueEvent(in_eventTime, SE_KEY, posKey, true, 0, NULL); + + // positive/neutral to negative -> keydown + if (!negAnalog && negKey && oldAxis >= 0 && axis < 0) + Com_QueueEvent(in_eventTime, SE_KEY, negKey, true, 0, NULL); + + stick_state.oldaaxes[i] = axis; + } + } + + // set translated axes + if (in_joystickUseAnalog->integer) + { + for (i = 0; i < MAX_JOYSTICK_AXIS; i++) + { + if (translatedAxesSet[i]) + Com_QueueEvent(in_eventTime, SE_JOYSTICK_AXIS, i, translatedAxes[i], 0, NULL); + } + } +} + + +/* +=============== +IN_JoyMove +=============== +*/ +static void IN_JoyMove( void ) +{ + unsigned int axes = 0; + unsigned int hats = 0; + int total = 0; + int i = 0; + + if (gamepad) + { + IN_GamepadMove(); + return; + } + + if (!stick) + return; + + SDL_JoystickUpdate(); + + // update the ball state. + total = SDL_JoystickNumBalls(stick); + if (total > 0) + { + int balldx = 0; + int balldy = 0; + for (i = 0; i < total; i++) + { + int dx = 0; + int dy = 0; + SDL_JoystickGetBall(stick, i, &dx, &dy); + balldx += dx; + balldy += dy; + } + if (balldx || balldy) + { + // !!! FIXME: is this good for stick balls, or just mice? + // Scale like the mouse input... + if (abs(balldx) > 1) + balldx *= 2; + if (abs(balldy) > 1) + balldy *= 2; + Com_QueueEvent(in_eventTime, SE_MOUSE, balldx, balldy, 0, NULL); + } + } + + // now query the stick buttons... + total = SDL_JoystickNumButtons(stick); + if (total > 0) + { + if (total > ARRAY_LEN(stick_state.buttons)) + total = ARRAY_LEN(stick_state.buttons); + for (i = 0; i < total; i++) + { + bool pressed = (SDL_JoystickGetButton(stick, i) != 0); + if (pressed != stick_state.buttons[i]) + { + Com_QueueEvent(in_eventTime, SE_KEY, K_JOY1 + i, pressed, 0, NULL ); + stick_state.buttons[i] = pressed; + } + } + } + + // look at the hats... + total = SDL_JoystickNumHats(stick); + if (total > 0) + { + if (total > 4) total = 4; + for (i = 0; i < total; i++) + { + ((Uint8 *)&hats)[i] = SDL_JoystickGetHat(stick, i); + } + } + + // update hat state + if (hats != stick_state.oldhats) + { + for( i = 0; i < 4; i++ ) { + if( ((Uint8 *)&hats)[i] != ((Uint8 *)&stick_state.oldhats)[i] ) { + // release event + switch( ((Uint8 *)&stick_state.oldhats)[i] ) { + case SDL_HAT_UP: + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 0], false, 0, NULL ); + break; + case SDL_HAT_RIGHT: + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 1], false, 0, NULL ); + break; + case SDL_HAT_DOWN: + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 2], false, 0, NULL ); + break; + case SDL_HAT_LEFT: + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 3], false, 0, NULL ); + break; + case SDL_HAT_RIGHTUP: + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 0], false, 0, NULL ); + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 1], false, 0, NULL ); + break; + case SDL_HAT_RIGHTDOWN: + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 2], false, 0, NULL ); + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 1], false, 0, NULL ); + break; + case SDL_HAT_LEFTUP: + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 0], false, 0, NULL ); + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 3], false, 0, NULL ); + break; + case SDL_HAT_LEFTDOWN: + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 2], false, 0, NULL ); + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 3], false, 0, NULL ); + break; + default: + break; + } + // press event + switch( ((Uint8 *)&hats)[i] ) { + case SDL_HAT_UP: + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 0], true, 0, NULL ); + break; + case SDL_HAT_RIGHT: + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 1], true, 0, NULL ); + break; + case SDL_HAT_DOWN: + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 2], true, 0, NULL ); + break; + case SDL_HAT_LEFT: + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 3], true, 0, NULL ); + break; + case SDL_HAT_RIGHTUP: + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 0], true, 0, NULL ); + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 1], true, 0, NULL ); + break; + case SDL_HAT_RIGHTDOWN: + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 2], true, 0, NULL ); + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 1], true, 0, NULL ); + break; + case SDL_HAT_LEFTUP: + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 0], true, 0, NULL ); + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 3], true, 0, NULL ); + break; + case SDL_HAT_LEFTDOWN: + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 2], true, 0, NULL ); + Com_QueueEvent(in_eventTime, SE_KEY, hat_keys[4*i + 3], true, 0, NULL ); + break; + default: + break; + } + } + } + } + + // save hat state + stick_state.oldhats = hats; + + // finally, look at the axes... + total = SDL_JoystickNumAxes(stick); + if (total > 0) + { + if (in_joystickUseAnalog->integer) + { + if (total > MAX_JOYSTICK_AXIS) total = MAX_JOYSTICK_AXIS; + for (i = 0; i < total; i++) + { + Sint16 axis = SDL_JoystickGetAxis(stick, i); + float f = ( (float) abs(axis) ) / 32767.0f; + + if( f < in_joystickThreshold->value ) axis = 0; + + if ( axis != stick_state.oldaaxes[i] ) + { + Com_QueueEvent(in_eventTime, SE_JOYSTICK_AXIS, i, axis, 0, NULL ); + stick_state.oldaaxes[i] = axis; + } + } + } + else + { + if (total > 16) total = 16; + for (i = 0; i < total; i++) + { + Sint16 axis = SDL_JoystickGetAxis(stick, i); + float f = ( (float) axis ) / 32767.0f; + if( f < -in_joystickThreshold->value ) { + axes |= ( 1 << ( i * 2 ) ); + } else if( f > in_joystickThreshold->value ) { + axes |= ( 1 << ( ( i * 2 ) + 1 ) ); + } + } + } + } + + /* Time to update axes state based on old vs. new. */ + if (axes != stick_state.oldaxes) + { + for( i = 0; i < 16; i++ ) { + if( ( axes & ( 1 << i ) ) && !( stick_state.oldaxes & ( 1 << i ) ) ) { + Com_QueueEvent(in_eventTime, SE_KEY, joy_keys[i], true, 0, NULL ); + } + + if( !( axes & ( 1 << i ) ) && ( stick_state.oldaxes & ( 1 << i ) ) ) { + Com_QueueEvent(in_eventTime, SE_KEY, joy_keys[i], false, 0, NULL ); + } + } + } + + /* Save for future generations. */ + stick_state.oldaxes = axes; +} + +/* +=============== +IN_ProcessEvents +=============== +*/ +static void IN_ProcessEvents( void ) +{ + SDL_Event e; + keyNum_t key = (keyNum_t)0; + static keyNum_t lastKeyDown = (keyNum_t)0; + + if( !SDL_WasInit( SDL_INIT_VIDEO ) ) + return; + + while( SDL_PollEvent( &e ) ) + { + switch( e.type ) + { + case SDL_KEYDOWN: + if ( e.key.repeat && Key_GetCatcher( ) == 0 ) + break; + + if( ( key = IN_TranslateSDLToQ3Key( &e.key.keysym, true ) ) ) + Com_QueueEvent(in_eventTime, SE_KEY, key, true, 0, NULL ); + + if( key == K_BACKSPACE ) + Com_QueueEvent(in_eventTime, SE_CHAR, CTRL('h'), 0, 0, NULL ); + else if( keys[K_CTRL].down && key >= 'a' && key <= 'z' ) + Com_QueueEvent(in_eventTime, SE_CHAR, CTRL(key), 0, 0, NULL ); + + lastKeyDown = key; + break; + + case SDL_KEYUP: + if( ( key = IN_TranslateSDLToQ3Key( &e.key.keysym, false ) ) ) + Com_QueueEvent(in_eventTime, SE_KEY, key, false, 0, NULL ); + + lastKeyDown = (keyNum_t)0; + break; + + case SDL_TEXTINPUT: + if( lastKeyDown != K_CONSOLE ) + { + char *c = e.text.text; + + // Quick and dirty UTF-8 to UTF-32 conversion + while( *c ) + { + int utf32 = 0; + + if( ( *c & 0x80 ) == 0 ) + utf32 = *c++; + else if( ( *c & 0xE0 ) == 0xC0 ) // 110x xxxx + { + utf32 |= ( *c++ & 0x1F ) << 6; + utf32 |= ( *c++ & 0x3F ); + } + else if( ( *c & 0xF0 ) == 0xE0 ) // 1110 xxxx + { + utf32 |= ( *c++ & 0x0F ) << 12; + utf32 |= ( *c++ & 0x3F ) << 6; + utf32 |= ( *c++ & 0x3F ); + } + else if( ( *c & 0xF8 ) == 0xF0 ) // 1111 0xxx + { + utf32 |= ( *c++ & 0x07 ) << 18; + utf32 |= ( *c++ & 0x3F ) << 12; + utf32 |= ( *c++ & 0x3F ) << 6; + utf32 |= ( *c++ & 0x3F ); + } + else + { + Com_DPrintf( "Unrecognised UTF-8 lead byte: 0x%x\n", (unsigned int)*c ); + c++; + } + + if( utf32 != 0 ) + { + if( IN_IsConsoleKey( (keyNum_t)0, utf32 ) ) + { + Com_QueueEvent(in_eventTime, SE_KEY, K_CONSOLE, true, 0, NULL ); + Com_QueueEvent(in_eventTime, SE_KEY, K_CONSOLE, false, 0, NULL ); + } + else + Com_QueueEvent(in_eventTime, SE_CHAR, utf32, 0, 0, NULL ); + } + } + } + break; + + case SDL_MOUSEMOTION: + if( mouseActive ) + { + if( !e.motion.xrel && !e.motion.yrel ) + break; + Com_QueueEvent(in_eventTime, SE_MOUSE, e.motion.xrel, e.motion.yrel, 0, NULL ); + } + break; + + case SDL_MOUSEBUTTONDOWN: + case SDL_MOUSEBUTTONUP: + { + int b; + switch( e.button.button ) + { + case 1: b = K_MOUSE1; break; + case 2: b = K_MOUSE3; break; + case 3: b = K_MOUSE2; break; + case 4: b = K_MOUSE4; break; + case 5: b = K_MOUSE5; break; + default: b = K_AUX1 + ( e.button.button - 8 ) % 16; break; + } + Com_QueueEvent(in_eventTime, SE_KEY, b, + ( e.type == SDL_MOUSEBUTTONDOWN ? true : false ), 0, NULL ); + } + break; + + case SDL_MOUSEWHEEL: + if( e.wheel.y > 0 ) + { + Com_QueueEvent(in_eventTime, SE_KEY, K_MWHEELUP, true, 0, NULL ); + Com_QueueEvent(in_eventTime, SE_KEY, K_MWHEELUP, false, 0, NULL ); + } + else if( e.wheel.y < 0 ) + { + Com_QueueEvent(in_eventTime, SE_KEY, K_MWHEELDOWN, true, 0, NULL ); + Com_QueueEvent(in_eventTime, SE_KEY, K_MWHEELDOWN, false, 0, NULL ); + } + break; + + case SDL_CONTROLLERDEVICEADDED: + case SDL_CONTROLLERDEVICEREMOVED: + if (in_joystick->integer) + IN_InitJoystick(); + break; + + case SDL_QUIT: + Cbuf_ExecuteText(EXEC_NOW, "quit \"Closed window\"\n"); + break; + + case SDL_WINDOWEVENT: + switch( e.window.event ) + { + case SDL_WINDOWEVENT_RESIZED: + { + int width, height; + + width = e.window.data1; + height = e.window.data2; + + // ignore this event on fullscreen + if ( cls.glconfig.isFullscreen ) + break; + + // check if size actually changed + if( cls.glconfig.vidWidth == width && cls.glconfig.vidHeight == height ) + { + break; + } + + Cvar_SetValue( "r_width", width ); + Cvar_SetValue( "r_height", height ); + + // Wait until user stops dragging for 1 second, so + // we aren't constantly recreating the GL context while + // he tries to drag... + vidRestartTime = Sys_Milliseconds( ) + 1000; + } + break; + + case SDL_WINDOWEVENT_MINIMIZED: Cvar_SetValue( "com_minimized", 1 ); break; + case SDL_WINDOWEVENT_RESTORED: + case SDL_WINDOWEVENT_MAXIMIZED: Cvar_SetValue( "com_minimized", 0 ); break; + case SDL_WINDOWEVENT_FOCUS_LOST: Cvar_SetValue( "com_unfocused", 1 ); break; + case SDL_WINDOWEVENT_FOCUS_GAINED: Cvar_SetValue( "com_unfocused", 0 ); break; + } + break; + + default: + break; + } + } +} + +/* +=============== +IN_Frame +=============== +*/ +void IN_Frame( void ) +{ + bool loading; + bool cursorShowing; + int x, y; + + IN_JoyMove( ); + + // If not DISCONNECTED (main menu) or ACTIVE (in game), we're loading + loading = ( clc.state != CA_DISCONNECTED && clc.state != CA_ACTIVE ); + cursorShowing = Key_GetCatcher( ) & KEYCATCH_UI; + + if( !cls.glconfig.isFullscreen && ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) ) + { + // Console is down in windowed mode + IN_DeactivateMouse( ); + } + else if( !cls.glconfig.isFullscreen && loading ) + { + // Loading in windowed mode + IN_DeactivateMouse( ); + } + else if( !cls.glconfig.isFullscreen && cursorShowing && cls.uiInterface != 2 ) + { + // Use WM cursor when not fullscreen + IN_DeactivateMouse( ); + } + else if( !( SDL_GetWindowFlags( SDL_window ) & SDL_WINDOW_INPUT_FOCUS ) ) + { + // Window not got focus + IN_DeactivateMouse( ); + } + else + IN_ActivateMouse( ); + + if( !mouseActive && cls.uiInterface != 2 ) + { + SDL_GetMouseState( &x, &y ); + IN_SetUIMousePosition( x, y ); + } + + IN_ProcessEvents( ); + + // Set event time for next frame to earliest possible time an event could happen + in_eventTime = Sys_Milliseconds(); + + // In case we had to delay actual restart of video system + if( ( vidRestartTime != 0 ) && ( vidRestartTime < Sys_Milliseconds( ) ) ) + { + vidRestartTime = 0; + Cbuf_AddText( "vid_restart\n" ); + } +} + +/* +=============== +IN_Init +=============== +*/ +void IN_Init( void *windowData ) +{ + int appState; + + if( !SDL_WasInit( SDL_INIT_VIDEO ) ) + { + Com_Error( ERR_FATAL, "IN_Init called before SDL_Init( SDL_INIT_VIDEO )" ); + return; + } + + SDL_window = (SDL_Window *)windowData; + + Com_DPrintf( "\n------- Input Initialization -------\n" ); + + in_keyboardDebug = Cvar_Get( "in_keyboardDebug", "0", CVAR_ARCHIVE ); + + // mouse variables + in_mouse = Cvar_Get( "in_mouse", "1", CVAR_ARCHIVE ); + in_nograb = Cvar_Get( "in_nograb", "0", CVAR_ARCHIVE ); + + in_joystick = Cvar_Get( "in_joystick", "0", CVAR_ARCHIVE|CVAR_LATCH ); + in_joystickThreshold = Cvar_Get( "joy_threshold", "0.15", CVAR_ARCHIVE ); + + SDL_StartTextInput( ); + + mouseAvailable = ( in_mouse->value != 0 ); + IN_DeactivateMouse( ); + + appState = SDL_GetWindowFlags( SDL_window ); + Cvar_SetValue( "com_unfocused", !( appState & SDL_WINDOW_INPUT_FOCUS ) ); + Cvar_SetValue( "com_minimized", appState & SDL_WINDOW_MINIMIZED ); + + IN_InitJoystick( ); + Com_DPrintf( "------------------------------------\n" ); +} + +/* +=============== +IN_Shutdown +=============== +*/ +void IN_Shutdown( void ) +{ + SDL_StopTextInput( ); + + IN_DeactivateMouse( ); + mouseAvailable = false; + + IN_ShutdownJoystick( ); + + SDL_window = NULL; +} + +/* +=============== +IN_Restart +=============== +*/ +void IN_Restart( void ) +{ + IN_ShutdownJoystick( ); + IN_Init( SDL_window ); +} diff --git a/src/sdl/sdl_snd.cpp b/src/sdl/sdl_snd.cpp new file mode 100644 index 0000000..4689cc5 --- /dev/null +++ b/src/sdl/sdl_snd.cpp @@ -0,0 +1,298 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. +Copyright (C) 2000-2013 Darklegion Development +Copyright (C) 2015-2019 GrangerHub + +This file is part of Tremulous. + +Tremulous is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 3 of the License, +or (at your option) any later version. + +Tremulous is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Tremulous; if not, see <https://www.gnu.org/licenses/> + +=========================================================================== +*/ + +#include <cstdlib> +#include <cstdio> + +#ifdef USE_LOCAL_HEADERS +# include "SDL.h" +#else +# include <SDL.h> +#endif + +#include "client/snd_local.h" +#include "qcommon/cvar.h" +#include "qcommon/q_shared.h" + +bool snd_inited = false; + +cvar_t *s_sdlBits; +cvar_t *s_sdlSpeed; +cvar_t *s_sdlChannels; +cvar_t *s_sdlDevSamps; +cvar_t *s_sdlMixSamps; + +/* The audio callback. All the magic happens here. */ +static int dmapos = 0; +static int dmasize = 0; + +/* +=============== +SNDDMA_AudioCallback +=============== +*/ +static void SNDDMA_AudioCallback(void *userdata, Uint8 *stream, int len) +{ + int pos = (dmapos * (dma.samplebits/8)); + if (pos >= dmasize) + dmapos = pos = 0; + + if (!snd_inited) /* shouldn't happen, but just in case... */ + { + memset(stream, '\0', len); + return; + } + else + { + int tobufend = dmasize - pos; /* bytes to buffer's end. */ + int len1 = len; + int len2 = 0; + + if (len1 > tobufend) + { + len1 = tobufend; + len2 = len - len1; + } + memcpy(stream, dma.buffer + pos, len1); + if (len2 <= 0) + dmapos += (len1 / (dma.samplebits/8)); + else /* wraparound? */ + { + memcpy(stream+len1, dma.buffer, len2); + dmapos = (len2 / (dma.samplebits/8)); + } + } + + if (dmapos >= dmasize) + dmapos = 0; +} + +static struct +{ + Uint16 enumFormat; + const char* stringFormat; +} formatToStringTable[ ] = +{ + { AUDIO_U8, "AUDIO_U8" }, + { AUDIO_S8, "AUDIO_S8" }, + { AUDIO_U16LSB, "AUDIO_U16LSB" }, + { AUDIO_S16LSB, "AUDIO_S16LSB" }, + { AUDIO_U16MSB, "AUDIO_U16MSB" }, + { AUDIO_S16MSB, "AUDIO_S16MSB" } +}; + +static int formatToStringTableSize = ARRAY_LEN( formatToStringTable ); + +/* +=============== +SNDDMA_PrintAudiospec +=============== +*/ +static void SNDDMA_PrintAudiospec(const char *str, const SDL_AudioSpec *spec) +{ + int i; + const char *fmt = NULL; + + Com_Printf("%s:\n", str); + + for( i = 0; i < formatToStringTableSize; i++ ) { + if( spec->format == formatToStringTable[ i ].enumFormat ) { + fmt = formatToStringTable[ i ].stringFormat; + } + } + + if( fmt ) { + Com_Printf( " Format: %s\n", fmt ); + } else { + Com_Printf( " Format: " S_COLOR_RED "UNKNOWN\n"); + } + + Com_Printf( " Freq: %d\n", (int) spec->freq ); + Com_Printf( " Samples: %d\n", (int) spec->samples ); + Com_Printf( " Channels: %d\n", (int) spec->channels ); +} + +/* +=============== +SNDDMA_Init +=============== +*/ +bool SNDDMA_Init(void) +{ + SDL_AudioSpec desired; + SDL_AudioSpec obtained; + int tmp; + + if (snd_inited) + return true; + + if (!s_sdlBits) { + s_sdlBits = Cvar_Get("s_sdlBits", "16", CVAR_ARCHIVE); + s_sdlSpeed = Cvar_Get("s_sdlSpeed", "0", CVAR_ARCHIVE); + s_sdlChannels = Cvar_Get("s_sdlChannels", "2", CVAR_ARCHIVE); + s_sdlDevSamps = Cvar_Get("s_sdlDevSamps", "0", CVAR_ARCHIVE); + s_sdlMixSamps = Cvar_Get("s_sdlMixSamps", "0", CVAR_ARCHIVE); + } + + Com_Printf( "SDL_Init( SDL_INIT_AUDIO )... " ); + + if (!SDL_WasInit(SDL_INIT_AUDIO)) + { + if (SDL_Init(SDL_INIT_AUDIO) != 0) + { + Com_Printf( "FAILED (%s)\n", SDL_GetError( ) ); + return false; + } + } + + Com_Printf( "OK\n" ); + + Com_Printf( "SDL audio driver is \"%s\".\n", SDL_GetCurrentAudioDriver( ) ); + + memset(&desired, '\0', sizeof (desired)); + memset(&obtained, '\0', sizeof (obtained)); + + tmp = ((int) s_sdlBits->value); + if ((tmp != 16) && (tmp != 8)) + tmp = 16; + + desired.freq = (int) s_sdlSpeed->value; + if(!desired.freq) desired.freq = 22050; + desired.format = ((tmp == 16) ? AUDIO_S16SYS : AUDIO_U8); + + // I dunno if this is the best idea, but I'll give it a try... + // should probably check a cvar for this... + if (s_sdlDevSamps->value) + desired.samples = s_sdlDevSamps->value; + else + { + // just pick a sane default. + if (desired.freq <= 11025) + desired.samples = 256; + else if (desired.freq <= 22050) + desired.samples = 512; + else if (desired.freq <= 44100) + desired.samples = 1024; + else + desired.samples = 2048; // (*shrug*) + } + + desired.channels = (int) s_sdlChannels->value; + desired.callback = SNDDMA_AudioCallback; + + if (SDL_OpenAudio(&desired, &obtained) == -1) + { + Com_Printf("SDL_OpenAudio() failed: %s\n", SDL_GetError()); + SDL_QuitSubSystem(SDL_INIT_AUDIO); + return false; + } + + SNDDMA_PrintAudiospec("SDL_AudioSpec", &obtained); + + // dma.samples needs to be big, or id's mixer will just refuse to + // work at all; we need to keep it significantly bigger than the + // amount of SDL callback samples, and just copy a little each time + // the callback runs. + // 32768 is what the OSS driver filled in here on my system. I don't + // know if it's a good value overall, but at least we know it's + // reasonable...this is why I let the user override. + tmp = s_sdlMixSamps->value; + if (!tmp) + tmp = (obtained.samples * obtained.channels) * 10; + + if (tmp & (tmp - 1)) // not a power of two? Seems to confuse something. + { + int val = 1; + while (val < tmp) + val <<= 1; + + tmp = val; + } + + dmapos = 0; + dma.samplebits = obtained.format & 0xFF; // first byte of format is bits. + dma.channels = obtained.channels; + dma.samples = tmp; + dma.submission_chunk = 1; + dma.speed = obtained.freq; + dmasize = (dma.samples * (dma.samplebits/8)); + dma.buffer = (byte*)calloc(1, dmasize); + + Com_Printf("Starting SDL audio callback...\n"); + SDL_PauseAudio(0); // start callback. + + Com_Printf("SDL audio initialized.\n"); + snd_inited = true; + return true; +} + +/* +=============== +SNDDMA_GetDMAPos +=============== +*/ +int SNDDMA_GetDMAPos(void) +{ + return dmapos; +} + +/* +=============== +SNDDMA_Shutdown +=============== +*/ +void SNDDMA_Shutdown(void) +{ + Com_Printf("Closing SDL audio device...\n"); + SDL_PauseAudio(1); + SDL_CloseAudio(); + SDL_QuitSubSystem(SDL_INIT_AUDIO); + free(dma.buffer); + dma.buffer = NULL; + dmapos = dmasize = 0; + snd_inited = false; + Com_Printf("SDL audio device shut down.\n"); +} + +/* +=============== +SNDDMA_Submit + +Send sound to device if buffer isn't really the dma buffer +=============== +*/ +void SNDDMA_Submit(void) +{ + SDL_UnlockAudio(); +} + +/* +=============== +SNDDMA_BeginPainting +=============== +*/ +void SNDDMA_BeginPainting (void) +{ + SDL_LockAudio(); +} |