merge sdl2transition changes
authorsheepluva
Sun, 15 Nov 2015 13:35:23 +0100
changeset 11383 d3b603323b2b
parent 11381 437a60995fe1 (current diff)
parent 11382 43ad1122a368 (diff)
child 11384 95d5badcb44f
merge sdl2transition changes
CMakeLists.txt
cmake_modules/FindSDL1or2.cmake
hedgewars/sdlmain/CMakeLists.txt
hedgewars/sdlmain/SDLMain.h
hedgewars/sdlmain/SDLMain.m
misc/winutils/include/GL/glut.h
--- a/.travis.yml	Sat Nov 14 22:19:05 2015 +0300
+++ b/.travis.yml	Sun Nov 15 13:35:23 2015 +0100
@@ -16,7 +16,7 @@
     # Failures we expect here
 before_install:
   - sudo apt-get update -qq
-  - sudo apt-get install debhelper cmake dpkg-dev libqt4-dev qt4-qmake libphysfs-dev libsdl1.2-dev libsdl-ttf2.0-dev libsdl-mixer1.2-dev libsdl-image1.2-dev libsdl-net1.2-dev bzip2 ghc libghc-mtl-dev libghc-parsec3-dev libghc-bytestring-show-dev libghc-vector-dev libghc-zlib-dev libghc-random-dev libghc-stm-dev libghc-network-dev libghc-dataenc-dev libghc-hslogger-dev libghc-utf8-string-dev libghc-sha-dev libghc-entropy-dev liblua5.1-0-dev imagemagick fpc fp-compiler fp-units-misc libpng-dev fp-units-gfx libavcodec-dev libavformat-dev freeglut3-dev libglew1.6-dev
+  - sudo apt-get install debhelper cmake dpkg-dev libqt4-dev qt4-qmake libphysfs-dev libsdl2-dev libsdl2-ttf-dev libsdl2-mixer-dev libsdl2-image-dev libsdl2-net-dev bzip2 ghc libghc-mtl-dev libghc-parsec3-dev libghc-bytestring-show-dev libghc-vector-dev libghc-zlib-dev libghc-random-dev libghc-stm-dev libghc-network-dev libghc-dataenc-dev libghc-hslogger-dev libghc-utf8-string-dev libghc-sha-dev libghc-entropy-dev liblua5.1-0-dev imagemagick fpc fp-compiler fp-units-misc libpng-dev fp-units-gfx libavcodec-dev libavformat-dev
 script: 
   - mkdir build && cd build && cmake $BUILD_ARGS .. && make VERBOSE=1 && make test_verbose
 notifications:
--- a/CMakeLists.txt	Sat Nov 14 22:19:05 2015 +0300
+++ b/CMakeLists.txt	Sun Nov 15 13:35:23 2015 +0100
@@ -65,6 +65,8 @@
 
 message(STATUS "Building ${HEDGEWARS_VERSION}-r${HEDGEWARS_REVISION} (${HEDGEWARS_HASH})")
 
+#io library paths
+include(${CMAKE_MODULE_PATH}/paths.cmake)
 #general utilities
 include(${CMAKE_MODULE_PATH}/utils.cmake)
 #paths initialization
--- a/INSTALL	Sat Nov 14 22:19:05 2015 +0300
+++ b/INSTALL	Sun Nov 15 13:35:23 2015 +0100
@@ -2,10 +2,10 @@
  - CMake >= 2.6.0
  - FreePascal >= 2.2.4
  - Qt >= 4.7.0
- - SDL >= 1.2.5
- - SDL_net >= 1.2.5
- - SDL_mixer >= 1.2
- - SDL_image >= 1.2
+ - SDL >= 2.0
+ - SDL_net >= 2.0
+ - SDL_mixer >= 2.0
+ - SDL_image >= 2.0
  - SDL_ttf >= 2.0
  - Lua = 5.1.0
  - Physfs >= 2.0.0
@@ -16,7 +16,6 @@
  - hslogger package
 For videorecording:
  - FFmpeg or LibAV
- - GLUT (when SDL < 2)
 For compressed screenshots:
  - libpng
 
--- a/QTfrontend/CMakeLists.txt	Sat Nov 14 22:19:05 2015 +0300
+++ b/QTfrontend/CMakeLists.txt	Sun Nov 15 13:35:23 2015 +0100
@@ -20,8 +20,10 @@
    message(FATAL_ERROR "This version of Qt is known *not* to work, please update or use a lower version")
 endif()
 
-find_package(SDL1or2)            #video in SDLInteraction
-find_package(SDL_mixer REQUIRED) #audio in SDLInteraction
+find_package(SDL2 REQUIRED)
+find_package(SDL2_mixer REQUIRED) #audio in SDLInteraction
+include_directories(${SDL2_INCLUDE_DIR})
+include_directories(${SDL2MIXER_INCLUDE_DIR})
 
 if(LIBAV_FOUND)
     add_definitions(-DVIDEOREC -D__STDC_CONSTANT_MACROS)
@@ -60,8 +62,6 @@
 include_directories(${CMAKE_CURRENT_SOURCE_DIR}/ui/widget)
 include_directories(${CMAKE_CURRENT_SOURCE_DIR}/util)
 include_directories(${CMAKE_CURRENT_SOURCE_DIR}/util/platform)
-include_directories(${SDL_INCLUDE_DIR})
-include_directories(${SDLMIXER_INCLUDE_DIR})
 include_directories(BEFORE ${PHYSFS_INCLUDE_DIR})
 include_directories(BEFORE ${PHYSLAYER_INCLUDE_DIR})
 include_directories(${LUA_INCLUDE_DIR}) #brought by physlayer hwpacksmounter.h
@@ -204,13 +204,16 @@
 list(APPEND HW_LINK_LIBS
     physfs physlayer
     ${QT_LIBRARIES}
-    ${SDL_LIBRARY}
-    ${SDLMIXER_LIBRARY}
+    )
+
+list(APPEND HW_LINK_LIBS
+    ${SDL2_LIBRARY}
+    ${SDL2MIXER_LIBRARY}
     )
     
 if(WIN32 AND NOT UNIX)
-    if(NOT SDL_LIBRARY)
-        list(APPEND HW_LINK_LIBS SDL)
+    if(NOT SDL2_LIBRARY)
+        list(APPEND HW_LINK_LIBS SDL2)
     endif()
 
     list(APPEND HW_LINK_LIBS
--- a/QTfrontend/game.cpp	Sat Nov 14 22:19:05 2015 +0300
+++ b/QTfrontend/game.cpp	Sun Nov 15 13:35:23 2015 +0100
@@ -17,7 +17,6 @@
  */
 
 #include <QApplication>
-#include <QClipboard>
 
 #include <QString>
 #include <QCheckBox>
@@ -261,18 +260,6 @@
                 .arg(QString::fromUtf8(msg.mid(2).left(size - 4))));
             return;
         }
-        case 'y':
-        {
-            // copy string to clipboard
-            QApplication::clipboard()->setText(QString::fromUtf8(msg.mid(2)));
-            break;
-        }
-        case 'Y':
-        {
-            // paste clipboard to game
-            SendIPC(QString("Y").toAscii() + QApplication::clipboard()->text().toUtf8().left(250).replace('\n', ' '));
-            break;
-        }
         case 'i':
         {
             emit GameStats(msg.at(2), QString::fromUtf8(msg.mid(3)));
--- a/QTfrontend/gameuiconfig.cpp	Sat Nov 14 22:19:05 2015 +0300
+++ b/QTfrontend/gameuiconfig.cpp	Sun Nov 15 13:35:23 2015 +0100
@@ -86,10 +86,11 @@
     else Form->ui.pageOptions->CBResolution->setCurrentIndex(t);
 
     // Default the windowed resolution to 5/6 of the screen size
-    int screenWidth = SDL_GetVideoInfo()->current_w * 5 / 6;
-    int screenHeight = SDL_GetVideoInfo()->current_h * 5 / 6;
-    QString widthStr; widthStr.setNum(screenWidth);
-    QString heightStr; heightStr.setNum(screenHeight);
+    QSize screenSize = SDLInteraction::instance().getCurrentResolution();
+    screenSize *= 5.0 / 6;
+
+    QString widthStr = QString::number(screenSize.width());
+    QString heightStr = QString::number(screenSize.height());
     QString wWidth = value("video/windowedWidth", widthStr).toString();
     QString wHeight = value("video/windowedHeight", heightStr).toString();
     // If left blank reset the resolution to the default
--- a/QTfrontend/main.cpp	Sat Nov 14 22:19:05 2015 +0300
+++ b/QTfrontend/main.cpp	Sun Nov 15 13:35:23 2015 +0100
@@ -37,6 +37,8 @@
 #include "FileEngine.h"
 #include "MessageDialog.h"
 
+#include "SDLInteraction.h"
+
 #ifdef _WIN32
 #include <Shlobj.h>
 #elif defined __APPLE__
@@ -154,6 +156,8 @@
     cocoaInit = new CocoaInitializer(); // Creates the autoreleasepool preventing cocoa object leaks on OS X.
 #endif
 
+    SDLInteraction::instance();
+
     HWApplication app(argc, argv);
     app.setAttribute(Qt::AA_DontShowIconsInMenus,false);
 
--- a/QTfrontend/ui/widget/about.cpp	Sat Nov 14 22:19:05 2015 +0300
+++ b/QTfrontend/ui/widget/about.cpp	Sun Nov 15 13:35:23 2015 +0100
@@ -101,7 +101,14 @@
     libinfo.append(QString(tr("Unknown Compiler")).arg(__VERSION__) + QString("<br>"));
 #endif
 
-    const SDL_version *sdl_ver = SDL_Linked_Version();
+    const SDL_version *sdl_ver;
+    SDL_version sdl_version;
+#if SDL_MAJOR_VERSION == 2
+    SDL_GetVersion(&sdl_version);
+    sdl_ver = &sdl_version;
+#else
+    sdl_ver = SDL_Linked_Version();
+#endif
     libinfo.append(QString("<a href=\"http://www.libsdl.org/\">SDL</a> version: %1.%2.%3<br>")
         .arg(sdl_ver->major)
         .arg(sdl_ver->minor)
--- a/QTfrontend/util/SDLInteraction.cpp	Sat Nov 14 22:19:05 2015 +0300
+++ b/QTfrontend/util/SDLInteraction.cpp	Sun Nov 15 13:35:23 2015 +0100
@@ -85,19 +85,15 @@
 {
     QStringList result;
 
-    SDL_Rect **modes;
+    int modesNumber = SDL_GetNumDisplayModes(0);
+    SDL_DisplayMode mode;
 
-    modes = SDL_ListModes(NULL, SDL_FULLSCREEN);
-
-    if((modes == (SDL_Rect **)0) || (modes == (SDL_Rect **)-1))
+    for(int i = 0; i < modesNumber; ++i)
     {
-        result << "640x480";
-    }
-    else
-    {
-        for(int i = 0; modes[i]; ++i)
-            if ((modes[i]->w >= 640) && (modes[i]->h >= 480))
-                result << QString("%1x%2").arg(modes[i]->w).arg(modes[i]->h);
+        SDL_GetDisplayMode(0, i, &mode);
+
+        if ((mode.w >= 640) && (mode.h >= 480))
+            result << QString("%1x%2").arg(mode.w).arg(mode.h);
     }
 
     return result;
@@ -108,6 +104,9 @@
 {
     QStringList result;
 
+#if SDL_VERSION_ATLEAST(2, 0, 0)
+// TODO or not TODO?
+#else
     int i = 0;
     while(i < 1024 && sdlkeys[i][1][0] != '\0')
         i++;
@@ -181,7 +180,8 @@
 
     // Terminate the list
     sdlkeys[i][0][0] = '\0';
-    sdlkeys[i][1][0] = '\0';
+    sdlkeys[i][1][0] = '\0';   
+#endif
 }
 
 
@@ -243,7 +243,7 @@
     if (!m_audioInitialized) return;
 
     if (m_music == NULL)
-        m_music = Mix_LoadMUS_RW(PHYSFSRWOPS_openRead(m_musicTrack.toLocal8Bit().constData()));
+        m_music = Mix_LoadMUS_RW(PHYSFSRWOPS_openRead(m_musicTrack.toLocal8Bit().constData()), 0);
 
     Mix_VolumeMusic(MIX_MAX_VOLUME/4);
     Mix_FadeInMusic(m_music, -1, 1750);
@@ -264,3 +264,12 @@
     m_isPlayingMusic = false;
 }
 
+
+QSize SDLInteraction::getCurrentResolution()
+{
+    SDL_DisplayMode mode;
+
+    SDL_GetDesktopDisplayMode(0, &mode);
+
+    return QSize(mode.w, mode.h);
+}
--- a/QTfrontend/util/SDLInteraction.h	Sat Nov 14 22:19:05 2015 +0300
+++ b/QTfrontend/util/SDLInteraction.h	Sun Nov 15 13:35:23 2015 +0100
@@ -27,7 +27,15 @@
 
 #include <QMap>
 #include <QStringList>
+#include <QSize>
 
+// workaround some strange Qt and SLD2 interaction
+#ifdef Q_OS_MAC
+#  ifdef MAC_OS_X_VERSION_MIN_REQUIRED
+#    undef MAC_OS_X_VERSION_MIN_REQUIRED
+#    define MAC_OS_X_VERSION_MIN_REQUIRED MAC_OS_X_VERSION_10_6
+#  endif
+#endif
 #include "SDL_mixer.h"
 
 /**
@@ -103,6 +111,8 @@
 
         /// Fades out and stops the background music (if playing).
         void stopMusic();
+
+        QSize getCurrentResolution();
 };
 
 
--- a/cmake_modules/FindSDL1or2.cmake	Sat Nov 14 22:19:05 2015 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,24 +0,0 @@
-find_package(SDL QUIET)
-
-if(NOT SDL_FOUND)
-    find_package(SDL2 REQUIRED)
-    set(SDL_INCLUDE_DIR ${SDL2_INCLUDE_DIR})
-    set(SDL_LIBRARY ${SDL2_LIBRARY})
-endif()
-
-if(NOT SDL_VERSION)
-    #find which version of SDL we have
-    find_file(sdlversion_h SDL_version.h ${SDL_INCLUDE_DIR})
-    if(sdlversion_h)
-        file(STRINGS ${sdlversion_h} sdl_majorversion_tmp REGEX "SDL_MAJOR_VERSION[\t' ']+[0-9]+")
-        file(STRINGS ${sdlversion_h} sdl_minorversion_tmp REGEX "SDL_MINOR_VERSION[\t' ']+[0-9]+")
-        file(STRINGS ${sdlversion_h} sdl_patchversion_tmp REGEX "SDL_PATCHLEVEL[\t' ']+[0-9]+")
-        string(REGEX MATCH "([0-9]+)" sdl_majorversion "${sdl_majorversion_tmp}")
-        string(REGEX MATCH "([0-9]+)" sdl_minorversion "${sdl_minorversion_tmp}")
-        string(REGEX MATCH "([0-9]+)" sdl_patchversion "${sdl_patchversion_tmp}")
-        set(SDL_VERSION "${sdl_majorversion}.${sdl_minorversion}.${sdl_patchversion}")
-    endif()
-endif()
-
-mark_as_advanced(sdlversion_h sdl_majorversion sdl_minorversion sdl_patchversion)
-
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cmake_modules/FindSDL2_image.cmake	Sun Nov 15 13:35:23 2015 +0100
@@ -0,0 +1,88 @@
+# - Locate SDL2_image library
+# This module defines:
+#  SDL2_IMAGE_LIBRARIES, the name of the library to link against
+#  SDL2_IMAGE_INCLUDE_DIRS, where to find the headers
+#  SDL2_IMAGE_FOUND, if false, do not try to link against
+#  SDL2_IMAGE_VERSION_STRING - human-readable string containing the version of SDL2_image
+#
+# For backward compatiblity the following variables are also set:
+#  SDL2IMAGE_LIBRARY (same value as SDL2_IMAGE_LIBRARIES)
+#  SDL2IMAGE_INCLUDE_DIR (same value as SDL2_IMAGE_INCLUDE_DIRS)
+#  SDL2IMAGE_FOUND (same value as SDL2_IMAGE_FOUND)
+#
+# $SDL2DIR is an environment variable that would
+# correspond to the ./configure --prefix=$SDL2DIR
+# used in building SDL2.
+#
+# Created by Eric Wing. This was influenced by the FindSDL2.cmake
+# module, but with modifications to recognize OS X frameworks and
+# additional Unix paths (FreeBSD, etc).
+
+#=============================================================================
+# Copyright 2005-2009 Kitware, Inc.
+# Copyright 2012 Benjamin Eikel
+#
+# Distributed under the OSI-approved BSD License (the "License");
+# see accompanying file Copyright.txt for details.
+#
+# This software is distributed WITHOUT ANY WARRANTY; without even the
+# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the License for more information.
+#=============================================================================
+# (To distribute this file outside of CMake, substitute the full
+#  License text for the above reference.)
+
+if(NOT SDL2_IMAGE_INCLUDE_DIR AND SDL2IMAGE_INCLUDE_DIR)
+  set(SDL2_IMAGE_INCLUDE_DIR ${SDL2IMAGE_INCLUDE_DIR} CACHE PATH "directory cache
+entry initialized from old variable name")
+endif()
+find_path(SDL2_IMAGE_INCLUDE_DIR SDL_image.h
+  HINTS
+    ENV SDL2IMAGEDIR
+    ENV SDL2DIR
+  PATH_SUFFIXES include/SDL2 include
+)
+
+if(NOT SDL2_IMAGE_LIBRARY AND SDL2IMAGE_LIBRARY)
+  set(SDL2_IMAGE_LIBRARY ${SDL2IMAGE_LIBRARY} CACHE FILEPATH "file cache entry
+initialized from old variable name")
+endif()
+find_library(SDL2_IMAGE_LIBRARY
+  NAMES SDL2_image
+  HINTS
+    ENV SDL2IMAGEDIR
+    ENV SDL2DIR
+  PATH_SUFFIXES lib
+)
+
+if(SDL2_IMAGE_INCLUDE_DIR AND EXISTS "${SDL2_IMAGE_INCLUDE_DIR}/SDL2_image.h")
+  file(STRINGS "${SDL2_IMAGE_INCLUDE_DIR}/SDL2_image.h" SDL2_IMAGE_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL2_IMAGE_MAJOR_VERSION[ \t]+[0-9]+$")
+  file(STRINGS "${SDL2_IMAGE_INCLUDE_DIR}/SDL2_image.h" SDL2_IMAGE_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL2_IMAGE_MINOR_VERSION[ \t]+[0-9]+$")
+  file(STRINGS "${SDL2_IMAGE_INCLUDE_DIR}/SDL2_image.h" SDL2_IMAGE_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL2_IMAGE_PATCHLEVEL[ \t]+[0-9]+$")
+  string(REGEX REPLACE "^#define[ \t]+SDL2_IMAGE_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_IMAGE_VERSION_MAJOR "${SDL2_IMAGE_VERSION_MAJOR_LINE}")
+  string(REGEX REPLACE "^#define[ \t]+SDL2_IMAGE_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_IMAGE_VERSION_MINOR "${SDL2_IMAGE_VERSION_MINOR_LINE}")
+  string(REGEX REPLACE "^#define[ \t]+SDL2_IMAGE_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_IMAGE_VERSION_PATCH "${SDL2_IMAGE_VERSION_PATCH_LINE}")
+  set(SDL2_IMAGE_VERSION_STRING ${SDL2_IMAGE_VERSION_MAJOR}.${SDL2_IMAGE_VERSION_MINOR}.${SDL2_IMAGE_VERSION_PATCH})
+  unset(SDL2_IMAGE_VERSION_MAJOR_LINE)
+  unset(SDL2_IMAGE_VERSION_MINOR_LINE)
+  unset(SDL2_IMAGE_VERSION_PATCH_LINE)
+  unset(SDL2_IMAGE_VERSION_MAJOR)
+  unset(SDL2_IMAGE_VERSION_MINOR)
+  unset(SDL2_IMAGE_VERSION_PATCH)
+endif()
+
+set(SDL2_IMAGE_LIBRARIES ${SDL2_IMAGE_LIBRARY})
+set(SDL2_IMAGE_INCLUDE_DIRS ${SDL2_IMAGE_INCLUDE_DIR})
+
+include(FindPackageHandleStandardArgs)
+
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_image
+                                  REQUIRED_VARS SDL2_IMAGE_LIBRARIES SDL2_IMAGE_INCLUDE_DIRS
+                                  VERSION_VAR SDL2_IMAGE_VERSION_STRING)
+
+# for backward compatiblity
+set(SDL2IMAGE_LIBRARY ${SDL2_IMAGE_LIBRARIES})
+set(SDL2IMAGE_INCLUDE_DIR ${SDL2_IMAGE_INCLUDE_DIRS})
+set(SDL2IMAGE_FOUND ${SDL2_IMAGE_FOUND})
+
+mark_as_advanced(SDL2_IMAGE_LIBRARY SDL2_IMAGE_INCLUDE_DIR)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cmake_modules/FindSDL2_mixer.cmake	Sun Nov 15 13:35:23 2015 +0100
@@ -0,0 +1,88 @@
+# - Locate SDL2_mixer library
+# This module defines:
+#  SDL2_MIXER_LIBRARIES, the name of the library to link against
+#  SDL2_MIXER_INCLUDE_DIRS, where to find the headers
+#  SDL2_MIXER_FOUND, if false, do not try to link against
+#  SDL2_MIXER_VERSION_STRING - human-readable string containing the version of SDL2_mixer
+#
+# For backward compatiblity the following variables are also set:
+#  SDL2MIXER_LIBRARY (same value as SDL2_MIXER_LIBRARIES)
+#  SDL2MIXER_INCLUDE_DIR (same value as SDL2_MIXER_INCLUDE_DIRS)
+#  SDL2MIXER_FOUND (same value as SDL2_MIXER_FOUND)
+#
+# $SDL2DIR is an environment variable that would
+# correspond to the ./configure --prefix=$SDL2DIR
+# used in building SDL2.
+#
+# Created by Eric Wing. This was influenced by the FindSDL2.cmake
+# module, but with modifications to recognize OS X frameworks and
+# additional Unix paths (FreeBSD, etc).
+
+#=============================================================================
+# Copyright 2005-2009 Kitware, Inc.
+# Copyright 2012 Benjamin Eikel
+#
+# Distributed under the OSI-approved BSD License (the "License");
+# see accompanying file Copyright.txt for details.
+#
+# This software is distributed WITHOUT ANY WARRANTY; without even the
+# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the License for more information.
+#=============================================================================
+# (To distribute this file outside of CMake, substitute the full
+#  License text for the above reference.)
+
+if(NOT SDL2_MIXER_INCLUDE_DIR AND SDL2MIXER_INCLUDE_DIR)
+  set(SDL2_MIXER_INCLUDE_DIR ${SDL2MIXER_INCLUDE_DIR} CACHE PATH "directory cache
+entry initialized from old variable name")
+endif()
+find_path(SDL2_MIXER_INCLUDE_DIR SDL_mixer.h
+  HINTS
+    ENV SDL2MIXERDIR
+    ENV SDL2DIR
+  PATH_SUFFIXES include/SDL2 include
+)
+
+if(NOT SDL2_MIXER_LIBRARY AND SDL2MIXER_LIBRARY)
+  set(SDL2_MIXER_LIBRARY ${SDL2MIXER_LIBRARY} CACHE FILEPATH "file cache entry
+initialized from old variable name")
+endif()
+find_library(SDL2_MIXER_LIBRARY
+  NAMES SDL2_mixer
+  HINTS
+    ENV SDL2MIXERDIR
+    ENV SDL2DIR
+  PATH_SUFFIXES lib
+)
+
+if(SDL2_MIXER_INCLUDE_DIR AND EXISTS "${SDL2_MIXER_INCLUDE_DIR}/SDL2_mixer.h")
+  file(STRINGS "${SDL2_MIXER_INCLUDE_DIR}/SDL2_mixer.h" SDL2_MIXER_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL2_MIXER_MAJOR_VERSION[ \t]+[0-9]+$")
+  file(STRINGS "${SDL2_MIXER_INCLUDE_DIR}/SDL2_mixer.h" SDL2_MIXER_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL2_MIXER_MINOR_VERSION[ \t]+[0-9]+$")
+  file(STRINGS "${SDL2_MIXER_INCLUDE_DIR}/SDL2_mixer.h" SDL2_MIXER_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL2_MIXER_PATCHLEVEL[ \t]+[0-9]+$")
+  string(REGEX REPLACE "^#define[ \t]+SDL2_MIXER_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_MIXER_VERSION_MAJOR "${SDL2_MIXER_VERSION_MAJOR_LINE}")
+  string(REGEX REPLACE "^#define[ \t]+SDL2_MIXER_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_MIXER_VERSION_MINOR "${SDL2_MIXER_VERSION_MINOR_LINE}")
+  string(REGEX REPLACE "^#define[ \t]+SDL2_MIXER_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_MIXER_VERSION_PATCH "${SDL2_MIXER_VERSION_PATCH_LINE}")
+  set(SDL2_MIXER_VERSION_STRING ${SDL2_MIXER_VERSION_MAJOR}.${SDL2_MIXER_VERSION_MINOR}.${SDL2_MIXER_VERSION_PATCH})
+  unset(SDL2_MIXER_VERSION_MAJOR_LINE)
+  unset(SDL2_MIXER_VERSION_MINOR_LINE)
+  unset(SDL2_MIXER_VERSION_PATCH_LINE)
+  unset(SDL2_MIXER_VERSION_MAJOR)
+  unset(SDL2_MIXER_VERSION_MINOR)
+  unset(SDL2_MIXER_VERSION_PATCH)
+endif()
+
+set(SDL2_MIXER_LIBRARIES ${SDL2_MIXER_LIBRARY})
+set(SDL2_MIXER_INCLUDE_DIRS ${SDL2_MIXER_INCLUDE_DIR})
+
+include(FindPackageHandleStandardArgs)
+
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_mixer
+                                  REQUIRED_VARS SDL2_MIXER_LIBRARIES SDL2_MIXER_INCLUDE_DIRS
+                                  VERSION_VAR SDL2_MIXER_VERSION_STRING)
+
+# for backward compatiblity
+set(SDL2MIXER_LIBRARY ${SDL2_MIXER_LIBRARIES})
+set(SDL2MIXER_INCLUDE_DIR ${SDL2_MIXER_INCLUDE_DIRS})
+set(SDL2MIXER_FOUND ${SDL2_MIXER_FOUND})
+
+mark_as_advanced(SDL2_MIXER_LIBRARY SDL2_MIXER_INCLUDE_DIR)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cmake_modules/FindSDL2_net.cmake	Sun Nov 15 13:35:23 2015 +0100
@@ -0,0 +1,88 @@
+# - Locate SDL2_net library
+# This module defines:
+#  SDL2_NET_LIBRARIES, the name of the library to link against
+#  SDL2_NET_INCLUDE_DIRS, where to find the headers
+#  SDL2_NET_FOUND, if false, do not try to link against
+#  SDL2_NET_VERSION_STRING - human-readable string containing the version of SDL2_net
+#
+# For backward compatiblity the following variables are also set:
+#  SDL2NET_LIBRARY (same value as SDL2_NET_LIBRARIES)
+#  SDL2NET_INCLUDE_DIR (same value as SDL2_NET_INCLUDE_DIRS)
+#  SDL2NET_FOUND (same value as SDL2_NET_FOUND)
+#
+# $SDL2DIR is an environment variable that would
+# correspond to the ./configure --prefix=$SDL2DIR
+# used in building SDL2.
+#
+# Created by Eric Wing. This was influenced by the FindSDL2.cmake
+# module, but with modifications to recognize OS X frameworks and
+# additional Unix paths (FreeBSD, etc).
+
+#=============================================================================
+# Copyright 2005-2009 Kitware, Inc.
+# Copyright 2012 Benjamin Eikel
+#
+# Distributed under the OSI-approved BSD License (the "License");
+# see accompanying file Copyright.txt for details.
+#
+# This software is distributed WITHOUT ANY WARRANTY; without even the
+# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the License for more information.
+#=============================================================================
+# (To distribute this file outside of CMake, substitute the full
+#  License text for the above reference.)
+
+if(NOT SDL2_NET_INCLUDE_DIR AND SDL2NET_INCLUDE_DIR)
+  set(SDL2_NET_INCLUDE_DIR ${SDL2NET_INCLUDE_DIR} CACHE PATH "directory cache
+entry initialized from old variable name")
+endif()
+find_path(SDL2_NET_INCLUDE_DIR SDL_net.h
+  HINTS
+    ENV SDL2NETDIR
+    ENV SDL2DIR
+  PATH_SUFFIXES include/SDL2 include
+)
+
+if(NOT SDL2_NET_LIBRARY AND SDL2NET_LIBRARY)
+  set(SDL2_NET_LIBRARY ${SDL2NET_LIBRARY} CACHE FILEPATH "file cache entry
+initialized from old variable name")
+endif()
+find_library(SDL2_NET_LIBRARY
+  NAMES SDL2_net
+  HINTS
+    ENV SDL2NETDIR
+    ENV SDL2DIR
+  PATH_SUFFIXES lib
+)
+
+if(SDL2_NET_INCLUDE_DIR AND EXISTS "${SDL2_NET_INCLUDE_DIR}/SDL2_net.h")
+  file(STRINGS "${SDL2_NET_INCLUDE_DIR}/SDL2_net.h" SDL2_NET_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL2_NET_MAJOR_VERSION[ \t]+[0-9]+$")
+  file(STRINGS "${SDL2_NET_INCLUDE_DIR}/SDL2_net.h" SDL2_NET_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL2_NET_MINOR_VERSION[ \t]+[0-9]+$")
+  file(STRINGS "${SDL2_NET_INCLUDE_DIR}/SDL2_net.h" SDL2_NET_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL2_NET_PATCHLEVEL[ \t]+[0-9]+$")
+  string(REGEX REPLACE "^#define[ \t]+SDL2_NET_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_NET_VERSION_MAJOR "${SDL2_NET_VERSION_MAJOR_LINE}")
+  string(REGEX REPLACE "^#define[ \t]+SDL2_NET_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_NET_VERSION_MINOR "${SDL2_NET_VERSION_MINOR_LINE}")
+  string(REGEX REPLACE "^#define[ \t]+SDL2_NET_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_NET_VERSION_PATCH "${SDL2_NET_VERSION_PATCH_LINE}")
+  set(SDL2_NET_VERSION_STRING ${SDL2_NET_VERSION_MAJOR}.${SDL2_NET_VERSION_MINOR}.${SDL2_NET_VERSION_PATCH})
+  unset(SDL2_NET_VERSION_MAJOR_LINE)
+  unset(SDL2_NET_VERSION_MINOR_LINE)
+  unset(SDL2_NET_VERSION_PATCH_LINE)
+  unset(SDL2_NET_VERSION_MAJOR)
+  unset(SDL2_NET_VERSION_MINOR)
+  unset(SDL2_NET_VERSION_PATCH)
+endif()
+
+set(SDL2_NET_LIBRARIES ${SDL2_NET_LIBRARY})
+set(SDL2_NET_INCLUDE_DIRS ${SDL2_NET_INCLUDE_DIR})
+
+include(FindPackageHandleStandardArgs)
+
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_net
+                                  REQUIRED_VARS SDL2_NET_LIBRARIES SDL2_NET_INCLUDE_DIRS
+                                  VERSION_VAR SDL2_NET_VERSION_STRING)
+
+# for backward compatiblity
+set(SDL2NET_LIBRARY ${SDL2_NET_LIBRARIES})
+set(SDL2NET_INCLUDE_DIR ${SDL2_NET_INCLUDE_DIRS})
+set(SDL2NET_FOUND ${SDL2_NET_FOUND})
+
+mark_as_advanced(SDL2_NET_LIBRARY SDL2_NET_INCLUDE_DIR)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cmake_modules/FindSDL2_ttf.cmake	Sun Nov 15 13:35:23 2015 +0100
@@ -0,0 +1,88 @@
+# - Locate SDL2_ttf library
+# This module defines:
+#  SDL2_TTF_LIBRARIES, the name of the library to link against
+#  SDL2_TTF_INCLUDE_DIRS, where to find the headers
+#  SDL2_TTF_FOUND, if false, do not try to link against
+#  SDL2_TTF_VERSION_STRING - human-readable string containing the version of SDL2_ttf
+#
+# For backward compatiblity the following variables are also set:
+#  SDL2TTF_LIBRARY (same value as SDL2_TTF_LIBRARIES)
+#  SDL2TTF_INCLUDE_DIR (same value as SDL2_TTF_INCLUDE_DIRS)
+#  SDL2TTF_FOUND (same value as SDL2_TTF_FOUND)
+#
+# $SDL2DIR is an environment variable that would
+# correspond to the ./configure --prefix=$SDL2DIR
+# used in building SDL2.
+#
+# Created by Eric Wing. This was influenced by the FindSDL2.cmake
+# module, but with modifications to recognize OS X frameworks and
+# additional Unix paths (FreeBSD, etc).
+
+#=============================================================================
+# Copyright 2005-2009 Kitware, Inc.
+# Copyright 2012 Benjamin Eikel
+#
+# Distributed under the OSI-approved BSD License (the "License");
+# see accompanying file Copyright.txt for details.
+#
+# This software is distributed WITHOUT ANY WARRANTY; without even the
+# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the License for more information.
+#=============================================================================
+# (To distribute this file outside of CMake, substitute the full
+#  License text for the above reference.)
+
+if(NOT SDL2_TTF_INCLUDE_DIR AND SDL2TTF_INCLUDE_DIR)
+  set(SDL2_TTF_INCLUDE_DIR ${SDL2TTF_INCLUDE_DIR} CACHE PATH "directory cache
+entry initialized from old variable name")
+endif()
+find_path(SDL2_TTF_INCLUDE_DIR SDL_ttf.h
+  HINTS
+    ENV SDL2TTFDIR
+    ENV SDL2DIR
+  PATH_SUFFIXES include/SDL2 include
+)
+
+if(NOT SDL2_TTF_LIBRARY AND SDL2TTF_LIBRARY)
+  set(SDL2_TTF_LIBRARY ${SDL2TTF_LIBRARY} CACHE FILEPATH "file cache entry
+initialized from old variable name")
+endif()
+find_library(SDL2_TTF_LIBRARY
+  NAMES SDL2_ttf
+  HINTS
+    ENV SDL2TTFDIR
+    ENV SDL2DIR
+  PATH_SUFFIXES lib
+)
+
+if(SDL2_TTF_INCLUDE_DIR AND EXISTS "${SDL2_TTF_INCLUDE_DIR}/SDL2_ttf.h")
+  file(STRINGS "${SDL2_TTF_INCLUDE_DIR}/SDL2_ttf.h" SDL2_TTF_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL2_TTF_MAJOR_VERSION[ \t]+[0-9]+$")
+  file(STRINGS "${SDL2_TTF_INCLUDE_DIR}/SDL2_ttf.h" SDL2_TTF_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL2_TTF_MINOR_VERSION[ \t]+[0-9]+$")
+  file(STRINGS "${SDL2_TTF_INCLUDE_DIR}/SDL2_ttf.h" SDL2_TTF_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL2_TTF_PATCHLEVEL[ \t]+[0-9]+$")
+  string(REGEX REPLACE "^#define[ \t]+SDL2_TTF_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_TTF_VERSION_MAJOR "${SDL2_TTF_VERSION_MAJOR_LINE}")
+  string(REGEX REPLACE "^#define[ \t]+SDL2_TTF_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_TTF_VERSION_MINOR "${SDL2_TTF_VERSION_MINOR_LINE}")
+  string(REGEX REPLACE "^#define[ \t]+SDL2_TTF_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_TTF_VERSION_PATCH "${SDL2_TTF_VERSION_PATCH_LINE}")
+  set(SDL2_TTF_VERSION_STRING ${SDL2_TTF_VERSION_MAJOR}.${SDL2_TTF_VERSION_MINOR}.${SDL2_TTF_VERSION_PATCH})
+  unset(SDL2_TTF_VERSION_MAJOR_LINE)
+  unset(SDL2_TTF_VERSION_MINOR_LINE)
+  unset(SDL2_TTF_VERSION_PATCH_LINE)
+  unset(SDL2_TTF_VERSION_MAJOR)
+  unset(SDL2_TTF_VERSION_MINOR)
+  unset(SDL2_TTF_VERSION_PATCH)
+endif()
+
+set(SDL2_TTF_LIBRARIES ${SDL2_TTF_LIBRARY})
+set(SDL2_TTF_INCLUDE_DIRS ${SDL2_TTF_INCLUDE_DIR})
+
+include(FindPackageHandleStandardArgs)
+
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_ttf
+                                  REQUIRED_VARS SDL2_TTF_LIBRARIES SDL2_TTF_INCLUDE_DIRS
+                                  VERSION_VAR SDL2_TTF_VERSION_STRING)
+
+# for backward compatiblity
+set(SDL2TTF_LIBRARY ${SDL2_TTF_LIBRARIES})
+set(SDL2TTF_INCLUDE_DIR ${SDL2_TTF_INCLUDE_DIRS})
+set(SDL2TTF_FOUND ${SDL2_TTF_FOUND})
+
+mark_as_advanced(SDL2_TTF_LIBRARY SDL2_TTF_INCLUDE_DIR)
--- a/hedgewars/CMakeLists.txt	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/CMakeLists.txt	Sun Nov 15 13:35:23 2015 +0100
@@ -1,8 +1,10 @@
-find_package(SDL1or2)
-find_package(SDL_image)
-find_package(SDL_net)
-find_package(SDL_ttf)
-find_package(SDL_mixer)
+enable_language(Pascal)
+
+find_package(SDL2 REQUIRED)
+find_package(SDL2_image REQUIRED)
+find_package(SDL2_net REQUIRED)
+find_package(SDL2_ttf REQUIRED)
+find_package(SDL2_mixer REQUIRED)
 
 include(CheckLibraryExists)
 include(${CMAKE_MODULE_PATH}/utils.cmake)
@@ -122,22 +124,16 @@
 
 #DEPENDECIES AND EXECUTABLES SECTION
 if(APPLE AND (NOT BUILD_ENGINE_LIBRARY))
-    #on OSX we need to provide the SDL_main() function when building as
-    #executable and the entry point too
-    add_subdirectory(sdlmain)
-    list(APPEND HW_LINK_LIBS SDLmain)
-    add_flag_append(CMAKE_Pascal_FLAGS "-k-lsdlmain")
-    add_flag_append(CMAKE_Pascal_FLAGS "-XMSDL_main")
     #OpenGL deps
     add_flag_append(CMAKE_Pascal_FLAGS "-k-framework -kCocoa")
     add_flag_append(CMAKE_Pascal_FLAGS "-k-framework -kOpenGL")
 
     #set the correct library or framework style depending on the main SDL
-    string(FIND "${SDL_LIBRARY}" "dylib" sdl_framework)
+    string(FIND "${SDL2_LIBRARY}" "dylib" sdl_framework)
     if(${sdl_framework} GREATER -1)
-        add_flag_append(CMAKE_Pascal_FLAGS "-k-lsdl -k-lsdl_image -k-lsdl_mixer -k-lsdl_ttf -k-lsdl_net")
+        add_flag_append(CMAKE_Pascal_FLAGS "-k-lsdl2 -k-lsdl2_image -k-lsdl2_mixer -k-lsdl2_ttf -k-lsdl2_net")
     else()
-        add_flag_append(CMAKE_Pascal_FLAGS "-k-framework -kSDL -k-framework -kSDL_image -k-framework -kSDL_mixer -k-framework -kSDL_net -k-framework -kSDL_net -k-framework -kSDL_ttf")
+        add_flag_append(CMAKE_Pascal_FLAGS "-k-framework -kSDL2 -k-framework -kSDL2_image -k-framework -kSDL2_mixer -k-framework -kSDL2_net -k-framework -kSDL2_net -k-framework -kSDL2_ttf")
     endif()
 endif()
 
@@ -145,8 +141,6 @@
     add_subdirectory(avwrapper)
     list(APPEND HW_LINK_LIBS avwrapper)
     add_definitions(-dUSE_VIDEO_RECORDING)
-    #only for SDL < 2, linking carried out by fpc
-    find_package_or_disable_msg(GLUT NOVIDEOREC "Video recording will not be built")
 endif()
 
 find_package_or_disable_msg(PNG NOPNG "Screenshots will be saved in BMP")
@@ -185,21 +179,17 @@
 
 
 #Mix_Init/Mix_Quit from SDL_mixer 1.2.10
-check_library_exists(${SDLMIXER_LIBRARY} Mix_Init "" HAVE_MIXINIT)
+check_library_exists(${SDL2MIXER_LIBRARY} Mix_Init "" HAVE_MIXINIT)
 if(HAVE_MIXINIT)
     add_definitions(-dSDL_MIXER_NEWER)
 endif(HAVE_MIXINIT)
 
 #IMG_Init/IMG_Quit from SDL_image 1.2.8
-check_library_exists(${SDLIMAGE_LIBRARY} IMG_Init "" HAVE_IMGINIT)
+check_library_exists(${SDL2IMAGE_LIBRARY} IMG_Init "" HAVE_IMGINIT)
 if(HAVE_IMGINIT)
     add_definitions(-dSDL_IMAGE_NEWER)
 endif(HAVE_IMGINIT)
 
-if(${SDL_VERSION} VERSION_GREATER 1.3)
-    add_definitions(-dSDL2)
-endif()
-
 #opengl 2
 IF(GL2)
     add_definitions(-dGL2)
--- a/hedgewars/SDLh.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/SDLh.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -57,25 +57,17 @@
 (*  SDL  *)
 const
 {$IFDEF WIN32}
-    SDLLibName = 'SDL.dll';
-    SDL_TTFLibName = 'SDL_ttf.dll';
-    SDL_MixerLibName = 'SDL_mixer.dll';
-    SDL_ImageLibName = 'SDL_image.dll';
-    SDL_NetLibName = 'SDL_net.dll';
+    SDLLibName = 'SDL2.dll';
+    SDL_TTFLibName = 'SDL2_ttf.dll';
+    SDL_MixerLibName = 'SDL2_mixer.dll';
+    SDL_ImageLibName = 'SDL2_image.dll';
+    SDL_NetLibName = 'SDL2_net.dll';
 {$ELSE}
-    {$IFDEF SDL2}
-        SDLLibName = 'libSDL2';
-        SDL_TTFLibName = 'libSDL2_ttf';
-        SDL_MixerLibName = 'libSDL2_mixer';
-        SDL_ImageLibName = 'libSDL2_image';
-        SDL_NetLibName = 'libSDL2_net';
-    {$ELSE}
-        SDLLibName = 'libSDL';
-        SDL_TTFLibName = 'libSDL_ttf';
-        SDL_MixerLibName = 'libSDL_mixer';
-        SDL_ImageLibName = 'libSDL_image';
-        SDL_NetLibName = 'libSDL_net';
-    {$ENDIF}
+    SDLLibName = 'libSDL2';
+    SDL_TTFLibName = 'libSDL2_ttf';
+    SDL_MixerLibName = 'libSDL2_mixer';
+    SDL_ImageLibName = 'libSDL2_image';
+    SDL_NetLibName = 'libSDL2_net';
 {$ENDIF}
 
 /////////////////////////////////////////////////////////////////
@@ -87,14 +79,9 @@
     SDL_INIT_AUDIO          = $00000010;
     SDL_INIT_VIDEO          = $00000020; // implies SDL_INIT_EVENTS (sdl2)
     SDL_INIT_JOYSTICK       = $00000200; // implies SDL_INIT_EVENTS (sdl2)
-{$IFDEF SDL2}
     SDL_INIT_HAPTIC         = $00001000;
     SDL_INIT_GAMECONTROLLER = $00002000; // implies SDL_INIT_JOYSTICK
     SDL_INIT_EVENTS         = $00004000;
-{$ELSE}
-    SDL_INIT_CDROM          = $00000100;
-    SDL_INIT_EVENTTHREAD    = $01000000;
-{$ENDIF}
     SDL_INIT_NOPARACHUTE    = $00100000;
     //SDL_INIT_EVERYTHING                // unsafe, init subsystems one at a time
 
@@ -108,7 +95,9 @@
     SDL_BUTTON_WHEELDOWN = 5;
 
 
-{$IFDEF SDL2}
+    SDL_TEXTEDITINGEVENT_TEXT_SIZE = 32;
+    SDL_TEXTINPUTEVENT_TEXT_SIZE   = 32;
+
     // SDL_Event types
     // pascal does not support unions as is, so we list here every possible event
     // and later associate a struct type each
@@ -201,39 +190,6 @@
     SDL_WINDOWEVENT_FOCUS_GAINED = 12;   //*< Window has gained keyboard focus
     SDL_WINDOWEVENT_FOCUS_LOST   = 13;   //*< Window has lost keyboard focus
     SDL_WINDOWEVENT_CLOSE        = 14;   //*< The window manager requests that the window be closed */
-{$ELSE}
-    // SDL_Event types
-    SDL_NOEVENT         = 0;
-    SDL_ACTIVEEVENT     = 1;
-    SDL_KEYDOWN         = 2;
-    SDL_KEYUP           = 3;
-    SDL_MOUSEMOTION     = 4;
-    SDL_MOUSEBUTTONDOWN = 5;
-    SDL_MOUSEBUTTONUP   = 6;
-    SDL_JOYAXISMOTION   = 7;
-    SDL_JOYBALLMOTION   = 8;
-    SDL_JOYHATMOTION    = 9;
-    SDL_JOYBUTTONDOWN   = 10;
-    SDL_JOYBUTTONUP     = 11;
-    SDL_QUITEV          = 12;
-    SDL_VIDEORESIZE     = 16;
-
-    // SDL_Surface flags
-    SDL_SWSURFACE   = $00000000;
-    SDL_HWSURFACE   = $00000001;
-    SDL_OPENGL      = $00000002;
-    SDL_ASYNCBLIT   = $00000004;
-    SDL_RESIZABLE   = $00000010;
-    SDL_NOFRAME     = $00000020;
-    SDL_HWACCEL     = $00000100;
-    SDL_SRCCOLORKEY = $00001000;
-    SDL_RLEACCEL    = $00004000;
-    SDL_SRCALPHA    = $00010000;
-    SDL_ANYFORMAT   = $00100000;
-    SDL_HWPALETTE   = $20000000;
-    SDL_DOUBLEBUF   = $40000000;
-    SDL_FULLSCREEN  = $80000000;
-{$ENDIF}
 
 {$IFDEF ENDIAN_LITTLE}
     RMask = $000000FF;
@@ -269,11 +225,13 @@
     KMOD_MODE   = $4000;
 
     {* SDL_mixer *}
-    MIX_MAX_VOLUME = 128;
-    MIX_INIT_FLAC  = $00000001;
-    MIX_INIT_MOD   = $00000002;
-    MIX_INIT_MP3   = $00000004;
-    MIX_INIT_OGG   = $00000008;
+    MIX_MAX_VOLUME      = 128;
+    MIX_INIT_FLAC       = $00000001;
+    MIX_INIT_MOD        = $00000002;
+    MIX_INIT_MODPLUG    = $00000004;
+    MIX_INIT_MP3        = $00000008;
+    MIX_INIT_OGG        = $00000010;
+    MIX_INIT_FLUIDSYNTH = $00000020;
 
     {* SDL_TTF *}
     TTF_STYLE_NORMAL = 0;
@@ -296,7 +254,8 @@
     IMG_INIT_PNG = $00000002;
     IMG_INIT_TIF = $00000004;
 
-    {* SDL_keysym *}
+    {* SDL_keycode *}
+    SDLK_UNKNOWN = 0;
     SDLK_BACKSPACE = 8;
     SDLK_RETURN    = 13;
     SDLK_ESCAPE    = 27;
@@ -317,6 +276,250 @@
     SDLK_PAGEUP    = 280;
     SDLK_PAGEDOWN  = 281;
 
+    // special keycodes (for modifier keys etc. will have this bit set)
+    SDLK_SCANCODE_MASK = (1 shl 30);
+
+    SDL_SCANCODE_UNKNOWN = 0;
+    SDL_SCANCODE_A = 4;
+    SDL_SCANCODE_B = 5;
+    SDL_SCANCODE_C = 6;
+    SDL_SCANCODE_D = 7;
+    SDL_SCANCODE_E = 8;
+    SDL_SCANCODE_F = 9;
+    SDL_SCANCODE_G = 10;
+    SDL_SCANCODE_H = 11;
+    SDL_SCANCODE_I = 12;
+    SDL_SCANCODE_J = 13;
+    SDL_SCANCODE_K = 14;
+    SDL_SCANCODE_L = 15;
+    SDL_SCANCODE_M = 16;
+    SDL_SCANCODE_N = 17;
+    SDL_SCANCODE_O = 18;
+    SDL_SCANCODE_P = 19;
+    SDL_SCANCODE_Q = 20;
+    SDL_SCANCODE_R = 21;
+    SDL_SCANCODE_S = 22;
+    SDL_SCANCODE_T = 23;
+    SDL_SCANCODE_U = 24;
+    SDL_SCANCODE_V = 25;
+    SDL_SCANCODE_W = 26;
+    SDL_SCANCODE_X = 27;
+    SDL_SCANCODE_Y = 28;
+    SDL_SCANCODE_Z = 29;
+    SDL_SCANCODE_1 = 30;
+    SDL_SCANCODE_2 = 31;
+    SDL_SCANCODE_3 = 32;
+    SDL_SCANCODE_4 = 33;
+    SDL_SCANCODE_5 = 34;
+    SDL_SCANCODE_6 = 35;
+    SDL_SCANCODE_7 = 36;
+    SDL_SCANCODE_8 = 37;
+    SDL_SCANCODE_9 = 38;
+    SDL_SCANCODE_0 = 39;
+    SDL_SCANCODE_RETURN = 40;
+    SDL_SCANCODE_ESCAPE = 41;
+    SDL_SCANCODE_BACKSPACE = 42;
+    SDL_SCANCODE_TAB = 43;
+    SDL_SCANCODE_SPACE = 44;
+    SDL_SCANCODE_MINUS = 45;
+    SDL_SCANCODE_EQUALS = 46;
+    SDL_SCANCODE_LEFTBRACKET = 47;
+    SDL_SCANCODE_RIGHTBRACKET = 48;
+    SDL_SCANCODE_BACKSLASH = 49;
+    SDL_SCANCODE_NONUSHASH = 50;
+    SDL_SCANCODE_SEMICOLON = 51;
+    SDL_SCANCODE_APOSTROPHE = 52;
+    SDL_SCANCODE_GRAVE = 53;
+    SDL_SCANCODE_COMMA = 54;
+    SDL_SCANCODE_PERIOD = 55;
+    SDL_SCANCODE_SLASH = 56;
+    SDL_SCANCODE_CAPSLOCK = 57;
+    SDL_SCANCODE_F1 = 58;
+    SDL_SCANCODE_F2 = 59;
+    SDL_SCANCODE_F3 = 60;
+    SDL_SCANCODE_F4 = 61;
+    SDL_SCANCODE_F5 = 62;
+    SDL_SCANCODE_F6 = 63;
+    SDL_SCANCODE_F7 = 64;
+    SDL_SCANCODE_F8 = 65;
+    SDL_SCANCODE_F9 = 66;
+    SDL_SCANCODE_F10 = 67;
+    SDL_SCANCODE_F11 = 68;
+    SDL_SCANCODE_F12 = 69;
+    SDL_SCANCODE_PRINTSCREEN = 70;
+    SDL_SCANCODE_SCROLLLOCK = 71;
+    SDL_SCANCODE_PAUSE = 72;
+    SDL_SCANCODE_INSERT = 73;
+    SDL_SCANCODE_HOME = 74;
+    SDL_SCANCODE_PAGEUP = 75;
+    SDL_SCANCODE_DELETE = 76;
+    SDL_SCANCODE_END = 77;
+    SDL_SCANCODE_PAGEDOWN = 78;
+    SDL_SCANCODE_RIGHT = 79;
+    SDL_SCANCODE_LEFT = 80;
+    SDL_SCANCODE_DOWN = 81;
+    SDL_SCANCODE_UP = 82;
+    SDL_SCANCODE_NUMLOCKCLEAR = 83;
+    SDL_SCANCODE_KP_DIVIDE = 84;
+    SDL_SCANCODE_KP_MULTIPLY = 85;
+    SDL_SCANCODE_KP_MINUS = 86;
+    SDL_SCANCODE_KP_PLUS = 87;
+    SDL_SCANCODE_KP_ENTER = 88;
+    SDL_SCANCODE_KP_1 = 89;
+    SDL_SCANCODE_KP_2 = 90;
+    SDL_SCANCODE_KP_3 = 91;
+    SDL_SCANCODE_KP_4 = 92;
+    SDL_SCANCODE_KP_5 = 93;
+    SDL_SCANCODE_KP_6 = 94;
+    SDL_SCANCODE_KP_7 = 95;
+    SDL_SCANCODE_KP_8 = 96;
+    SDL_SCANCODE_KP_9 = 97;
+    SDL_SCANCODE_KP_0 = 98;
+    SDL_SCANCODE_KP_PERIOD = 99;
+    SDL_SCANCODE_NONUSBACKSLASH = 100;
+    SDL_SCANCODE_APPLICATION = 101;
+    SDL_SCANCODE_POWER = 102;
+    SDL_SCANCODE_KP_EQUALS = 103;
+    SDL_SCANCODE_F13 = 104;
+    SDL_SCANCODE_F14 = 105;
+    SDL_SCANCODE_F15 = 106;
+    SDL_SCANCODE_F16 = 107;
+    SDL_SCANCODE_F17 = 108;
+    SDL_SCANCODE_F18 = 109;
+    SDL_SCANCODE_F19 = 110;
+    SDL_SCANCODE_F20 = 111;
+    SDL_SCANCODE_F21 = 112;
+    SDL_SCANCODE_F22 = 113;
+    SDL_SCANCODE_F23 = 114;
+    SDL_SCANCODE_F24 = 115;
+    SDL_SCANCODE_EXECUTE = 116;
+    SDL_SCANCODE_HELP = 117;
+    SDL_SCANCODE_MENU = 118;
+    SDL_SCANCODE_SELECT = 119;
+    SDL_SCANCODE_STOP = 120;
+    SDL_SCANCODE_AGAIN = 121;
+    SDL_SCANCODE_UNDO = 122;
+    SDL_SCANCODE_CUT = 123;
+    SDL_SCANCODE_COPY = 124;
+    SDL_SCANCODE_PASTE = 125;
+    SDL_SCANCODE_FIND = 126;
+    SDL_SCANCODE_MUTE = 127;
+    SDL_SCANCODE_VOLUMEUP = 128;
+    SDL_SCANCODE_VOLUMEDOWN = 129;
+    SDL_SCANCODE_KP_COMMA = 133;
+    SDL_SCANCODE_KP_EQUALSAS400 = 134;
+    SDL_SCANCODE_INTERNATIONAL1 = 135;
+    SDL_SCANCODE_INTERNATIONAL2 = 136;
+    SDL_SCANCODE_INTERNATIONAL3 = 137;
+    SDL_SCANCODE_INTERNATIONAL4 = 138;
+    SDL_SCANCODE_INTERNATIONAL5 = 139;
+    SDL_SCANCODE_INTERNATIONAL6 = 140;
+    SDL_SCANCODE_INTERNATIONAL7 = 141;
+    SDL_SCANCODE_INTERNATIONAL8 = 142;
+    SDL_SCANCODE_INTERNATIONAL9 = 143;
+    SDL_SCANCODE_LANG1 = 144; (*< Hangul/English toggle *)
+    SDL_SCANCODE_LANG2 = 145; (*< Hanja conversion *)
+    SDL_SCANCODE_LANG3 = 146; (*< Katakana *)
+    SDL_SCANCODE_LANG4 = 147; (*< Hiragana *)
+    SDL_SCANCODE_LANG5 = 148; (*< Zenkaku/Hankaku *)
+    SDL_SCANCODE_LANG6 = 149; (*< reserved *)
+    SDL_SCANCODE_LANG7 = 150; (*< reserved *)
+    SDL_SCANCODE_LANG8 = 151; (*< reserved *)
+    SDL_SCANCODE_LANG9 = 152; (*< reserved *)
+    SDL_SCANCODE_ALTERASE = 153;
+    SDL_SCANCODE_SYSREQ = 154;
+    SDL_SCANCODE_CANCEL = 155;
+    SDL_SCANCODE_CLEAR = 156;
+    SDL_SCANCODE_PRIOR = 157;
+    SDL_SCANCODE_RETURN2 = 158;
+    SDL_SCANCODE_SEPARATOR = 159;
+    SDL_SCANCODE_OUT = 160;
+    SDL_SCANCODE_OPER = 161;
+    SDL_SCANCODE_CLEARAGAIN = 162;
+    SDL_SCANCODE_CRSEL = 163;
+    SDL_SCANCODE_EXSEL = 164;
+    SDL_SCANCODE_KP_00 = 176;
+    SDL_SCANCODE_KP_000 = 177;
+    SDL_SCANCODE_THOUSANDSSEPARATOR = 178;
+    SDL_SCANCODE_DECIMALSEPARATOR = 179;
+    SDL_SCANCODE_CURRENCYUNIT = 180;
+    SDL_SCANCODE_CURRENCYSUBUNIT = 181;
+    SDL_SCANCODE_KP_LEFTPAREN = 182;
+    SDL_SCANCODE_KP_RIGHTPAREN = 183;
+    SDL_SCANCODE_KP_LEFTBRACE = 184;
+    SDL_SCANCODE_KP_RIGHTBRACE = 185;
+    SDL_SCANCODE_KP_TAB = 186;
+    SDL_SCANCODE_KP_BACKSPACE = 187;
+    SDL_SCANCODE_KP_A = 188;
+    SDL_SCANCODE_KP_B = 189;
+    SDL_SCANCODE_KP_C = 190;
+    SDL_SCANCODE_KP_D = 191;
+    SDL_SCANCODE_KP_E = 192;
+    SDL_SCANCODE_KP_F = 193;
+    SDL_SCANCODE_KP_XOR = 194;
+    SDL_SCANCODE_KP_POWER = 195;
+    SDL_SCANCODE_KP_PERCENT = 196;
+    SDL_SCANCODE_KP_LESS = 197;
+    SDL_SCANCODE_KP_GREATER = 198;
+    SDL_SCANCODE_KP_AMPERSAND = 199;
+    SDL_SCANCODE_KP_DBLAMPERSAND = 200;
+    SDL_SCANCODE_KP_VERTICALBAR = 201;
+    SDL_SCANCODE_KP_DBLVERTICALBAR = 202;
+    SDL_SCANCODE_KP_COLON = 203;
+    SDL_SCANCODE_KP_HASH = 204;
+    SDL_SCANCODE_KP_SPACE = 205;
+    SDL_SCANCODE_KP_AT = 206;
+    SDL_SCANCODE_KP_EXCLAM = 207;
+    SDL_SCANCODE_KP_MEMSTORE = 208;
+    SDL_SCANCODE_KP_MEMRECALL = 209;
+    SDL_SCANCODE_KP_MEMCLEAR = 210;
+    SDL_SCANCODE_KP_MEMADD = 211;
+    SDL_SCANCODE_KP_MEMSUBTRACT = 212;
+    SDL_SCANCODE_KP_MEMMULTIPLY = 213;
+    SDL_SCANCODE_KP_MEMDIVIDE = 214;
+    SDL_SCANCODE_KP_PLUSMINUS = 215;
+    SDL_SCANCODE_KP_CLEAR = 216;
+    SDL_SCANCODE_KP_CLEARENTRY = 217;
+    SDL_SCANCODE_KP_BINARY = 218;
+    SDL_SCANCODE_KP_OCTAL = 219;
+    SDL_SCANCODE_KP_DECIMAL = 220;
+    SDL_SCANCODE_KP_HEXADECIMAL = 221;
+    SDL_SCANCODE_LCTRL = 224;
+    SDL_SCANCODE_LSHIFT = 225;
+    SDL_SCANCODE_LALT = 226;
+    SDL_SCANCODE_LGUI = 227;
+    SDL_SCANCODE_RCTRL = 228;
+    SDL_SCANCODE_RSHIFT = 229;
+    SDL_SCANCODE_RALT = 230;
+    SDL_SCANCODE_RGUI = 231;
+    SDL_SCANCODE_MODE = 257;
+    SDL_SCANCODE_AUDIONEXT = 258;
+    SDL_SCANCODE_AUDIOPREV = 259;
+    SDL_SCANCODE_AUDIOSTOP = 260;
+    SDL_SCANCODE_AUDIOPLAY = 261;
+    SDL_SCANCODE_AUDIOMUTE = 262;
+    SDL_SCANCODE_MEDIASELECT = 263;
+    SDL_SCANCODE_WWW = 264;
+    SDL_SCANCODE_MAIL = 265;
+    SDL_SCANCODE_CALCULATOR = 266;
+    SDL_SCANCODE_COMPUTER = 267;
+    SDL_SCANCODE_AC_SEARCH = 268;
+    SDL_SCANCODE_AC_HOME = 269;
+    SDL_SCANCODE_AC_BACK = 270;
+    SDL_SCANCODE_AC_FORWARD = 271;
+    SDL_SCANCODE_AC_STOP = 272;
+    SDL_SCANCODE_AC_REFRESH = 273;
+    SDL_SCANCODE_AC_BOOKMARKS = 274;
+    SDL_SCANCODE_BRIGHTNESSDOWN = 275;
+    SDL_SCANCODE_BRIGHTNESSUP = 276;
+    SDL_SCANCODE_DISPLAYSWITCH = 277;
+    SDL_SCANCODE_KBDILLUMTOGGLE = 278;
+    SDL_SCANCODE_KBDILLUMDOWN = 279;
+    SDL_SCANCODE_KBDILLUMUP = 280;
+    SDL_SCANCODE_EJECT = 281;
+    SDL_SCANCODE_SLEEP = 282;
+    SDL_SCANCODE_APP1 = 283;
+    SDL_SCANCODE_APP2 = 284;
 
 /////////////////////////////////////////////////////////////////
 ///////////////////////  TYPE DEFINITIONS ///////////////////////
@@ -327,25 +530,20 @@
 // http://www.freepascal.org/docs-html/prog/progsu144.html
 
 type
-{$IFDEF SDL2}
     PSDL_Window   = Pointer;
     PSDL_Renderer = Pointer;
     PSDL_Texture  = Pointer;
     PSDL_GLContext= Pointer;
     TSDL_TouchId  = Int64;
-{$ENDIF}
     TSDL_FingerId = Int64;
+    TSDL_Keycode = LongInt;
+    TSDL_Scancode = LongInt;
 
     TSDL_eventaction = (SDL_ADDEVENT, SDL_PEEPEVENT, SDL_GETEVENT);
 
     PSDL_Rect = ^TSDL_Rect;
     TSDL_Rect = record
-{$IFDEF SDL2}
         x, y, w, h: LongInt;
-{$ELSE}
-        x, y: SmallInt;
-        w, h: Word;
-{$ENDIF}
         end;
 
     TPoint = record
@@ -354,7 +552,6 @@
 
     PSDL_PixelFormat = ^TSDL_PixelFormat;
     TSDL_PixelFormat = record
-{$IFDEF SDL2}
         format: LongWord;
         palette: Pointer;
         BitsPerPixel : Byte;
@@ -374,25 +571,6 @@
         Ashift: Byte;
         refcount: LongInt;
         next: PSDL_PixelFormat;
-{$ELSE}
-        palette: Pointer;
-        BitsPerPixel : Byte;
-        BytesPerPixel: Byte;
-        Rloss : Byte;
-        Gloss : Byte;
-        Bloss : Byte;
-        Aloss : Byte;
-        Rshift: Byte;
-        Gshift: Byte;
-        Bshift: Byte;
-        Ashift: Byte;
-        RMask : LongWord;
-        GMask : LongWord;
-        BMask : LongWord;
-        AMask : LongWord;
-        colorkey: LongWord;
-        alpha: Byte;
-{$ENDIF}
         end;
 
     PSDL_Surface = ^TSDL_Surface;
@@ -400,7 +578,7 @@
         flags : LongWord;
         format: PSDL_PixelFormat;
         w, h  : LongInt;
-        pitch : {$IFDEF SDL2}LongInt{$ELSE}Word{$ENDIF};
+        pitch : LongInt;
         pixels: Pointer;
 {$IFDEF PAS2C}
         hwdata   : Pointer;
@@ -412,16 +590,12 @@
         refcount : LongInt;
         offset   : LongInt;
 {$ELSE}
-{$IFDEF SDL2}
         userdata  : Pointer;
         locked    : LongInt;
         lock_data : Pointer;
         clip_rect : TSDL_Rect;
         map       : Pointer;
         refcount  : LongInt;
-{$ELSE}
-        offset : LongInt;
-{$ENDIF}
 {$ENDIF}
         end;
 
@@ -437,18 +611,14 @@
 
     (* SDL_RWops and friends *)
     PSDL_RWops = ^TSDL_RWops;
-{$IFDEF SDL2}
     TSize  = function( context: PSDL_RWops): Int64; cdecl;
     TSeek  = function( context: PSDL_RWops; offset: Int64; whence: LongInt ): Int64; cdecl;
-{$ELSE}
-    TSeek  = function( context: PSDL_RWops; offset: LongInt; whence: LongInt ): LongInt; cdecl;
-{$ENDIF}
     TRead  = function( context: PSDL_RWops; Ptr: Pointer; size: LongInt; maxnum : LongInt ): LongInt;  cdecl;
     TWrite = function( context: PSDL_RWops; Ptr: Pointer; size: LongInt; num: LongInt ): LongInt; cdecl;
     TClose = function( context: PSDL_RWops ): LongInt; cdecl;
 
     TStdio = record
-        autoclose: {$IFDEF SDL2}Boolean{$ELSE}LongInt{$ENDIF};
+        autoclose: Boolean;
         fp: Pointer;
         end;
 
@@ -460,9 +630,7 @@
 
     TUnknown = record
         data1: Pointer;
-{$IFDEF SDL2}
         data2: Pointer;
-{$ENDIF}
         end;
 
 {$IFDEF ANDROID}
@@ -479,7 +647,7 @@
         size, left: LongInt;
         end;
     TWindowsio = record
-        append : {$IFDEF SDL2}Boolean{$ELSE}LongInt{$ENDIF};
+        append : Boolean;
         h : Pointer;
         buffer : TWinbuffer;
         end;
@@ -487,9 +655,7 @@
 {$ENDIF}
 
     TSDL_RWops = record
-{$IFDEF SDL2}
         size: TSize;
-{$ENDIF}
         seek: TSeek;
         read: TRead;
         write: TWrite;
@@ -511,10 +677,9 @@
 
 {* SDL_Event type definition *}
 
-{$IFDEF SDL2}
     TSDL_Keysym = record
-        scancode: LongInt;
-        sym: LongInt;
+        scancode: TSDL_Scancode;
+        sym: TSDL_Keycode;
         modifier: Word;
         unused: LongWord;
         end;
@@ -528,21 +693,20 @@
         data1, data2: LongInt;
         end;
 
-    // available in sdl12 but not exposed
     TSDL_TextEditingEvent = record
-        type_: LongWord;
-        timestamp: LongWord;
-        windowID: LongWord;
-        text: array[0..31] of Byte;
-        start, lenght: LongInt;
+        type_: Longword;
+        timestamp: Longword;
+        windowID: Longword;
+        text: array [0..SDL_TEXTEDITINGEVENT_TEXT_SIZE - 1] of char;
+        start: LongInt;
+        length: LongInt;
         end;
 
-    // available in sdl12 but not exposed
     TSDL_TextInputEvent = record
-        type_: LongWord;
-        timestamp: LongWord;
-        windowID: LongWord;
-        text: array[0..31] of Byte;
+        type_: Longword;
+        timestamp: Longword;
+        windowID: Longword;
+        text: array [0..SDL_TEXTINPUTEVENT_TEXT_SIZE - 1] of char;
         end;
 
     TSDL_TouchFingerEvent = record
@@ -613,167 +777,92 @@
         end;
 
     TSDL_OSEvent = TSDL_CommonEvent;
-{$ELSE}
-    TSDL_KeySym = record
-        scancode: Byte;
-        sym: LongWord;
-        modifier: LongWord;
-        unicode: Word;
-        end;
-
-    TSDL_ActiveEvent = record
-        type_: Byte;
-        gain: Byte;
-        state: Byte;
-        end;
-
-    TSDL_ResizeEvent = record
-        type_: Byte;
-        w, h: LongInt;
-        end;
-{$ENDIF}
 
     TSDL_KeyboardEvent = record
-{$IFDEF SDL2}
         type_: LongWord;
         timestamp: LongWord;
         windowID: LongWord;
         state, repeat_, padding2, padding3: Byte;
-{$ELSE}
-        type_, which, state: Byte;
-{$ENDIF}
         keysym: TSDL_Keysym;
         end;
 
     TSDL_MouseMotionEvent = record
-{$IFDEF SDL2}
         type_: LongWord;
         timestamp: LongWord;
         windowID: LongWord;
         which, state: LongWord;
         x, y, xrel, yrel: LongInt;
-{$ELSE}
-        type_, which, state: Byte;
-        x, y, xrel, yrel: Word;
-{$ENDIF}
         end;
 
     TSDL_MouseButtonEvent = record
-{$IFDEF SDL2}
         type_: LongWord;
         timestamp: LongWord;
         windowID: LongWord;
         which: LongWord;
         button, state, padding1, padding2: Byte;
         x, y: LongInt;
-{$ELSE}
-        type_, which, button, state: Byte;
-        x, y: Word;
-{$ENDIF}
         end;
 
     TSDL_MouseWheelEvent = record
         type_: LongWord;
-{$IFDEF SDL2}
         timestamp: LongWord;
         windowID: LongWord;
         which: LongWord;
-{$ELSE}
-        which: Byte;
-{$ENDIF}
         x, y: LongInt;
         end;
 
     TSDL_JoyAxisEvent = record
-{$IFDEF SDL2}
         type_: LongWord;
         timestamp: LongWord;
         which: LongWord;
-{$ELSE}
-        type_: Byte;
-        which: Byte;
-{$ENDIF}
         axis: Byte;
-{$IFDEF SDL2}
         padding1, padding2, padding3: Byte;
         value: LongInt;
         padding4: Word;
-{$ELSE}
-        value: SmallInt;
-{$ENDIF}
         end;
 
     TSDL_JoyBallEvent = record
-{$IFDEF SDL2}
         type_: LongWord;
         timestamp: LongWord;
         which: LongWord;
-{$ELSE}
-        type_: Byte;
-        which: Byte;
-{$ENDIF}
         ball: Byte;
-{$IFDEF SDL2}
         padding1, padding2, padding3: Byte;
-{$ENDIF}
         xrel, yrel: SmallInt;
         end;
 
     TSDL_JoyHatEvent = record
-{$IFDEF SDL2}
         type_: LongWord;
         timestamp: LongWord;
         which: LongWord;
-{$ELSE}
-        type_: Byte;
-        which: Byte;
-{$ENDIF}
         hat: Byte;
         value: Byte;
-{$IFDEF SDL2}
         padding1, padding2: Byte;
-{$ENDIF}
         end;
 
     TSDL_JoyButtonEvent = record
-{$IFDEF SDL2}
         type_: LongWord;
         timestamp: LongWord;
-{$ELSE}
-        type_: Byte;
-{$ENDIF}
         which: Byte;
         button: Byte;
         state: Byte;
-{$IFDEF SDL2}
         padding1: Byte;
-{$ENDIF}
         end;
 
     TSDL_QuitEvent = record
-{$IFDEF SDL2}
         type_: LongWord;
         timestamp: LongWord;
-{$ELSE}
-        type_: Byte;
-{$ENDIF}
         end;
 
     TSDL_UserEvent = record
-{$IFDEF SDL2}
         type_: LongWord;
         timestamp: LongWord;
         windowID: LongWord;
-{$ELSE}
-        type_: Byte;
-{$ENDIF}
         code: LongInt;
         data1, data2: Pointer;
         end;
 
     PSDL_Event = ^TSDL_Event;
     TSDL_Event = record
-{$IFDEF SDL2}
         case LongInt of
             SDL_FIRSTEVENT: (type_: LongWord);
             SDL_COMMONDEVENT: (common: TSDL_CommonEvent);
@@ -781,7 +870,7 @@
             SDL_KEYDOWN,
             SDL_KEYUP: (key: TSDL_KeyboardEvent);
             SDL_TEXTEDITING: (edit: TSDL_TextEditingEvent);
-            SDL_TEXTINPUT: (tedit: TSDL_TextInputEvent);
+            SDL_TEXTINPUT: (text: TSDL_TextInputEvent);
             SDL_MOUSEMOTION: (motion: TSDL_MouseMotionEvent);
             SDL_MOUSEBUTTONDOWN,
             SDL_MOUSEBUTTONUP: (button: TSDL_MouseButtonEvent);
@@ -809,25 +898,6 @@
             SDL_DOLLARGESTURE: (dgesture: TSDL_DollarGestureEvent);
             SDL_DROPFILE: (drop: TSDL_DropEvent);
             SDL_ALLEVENTS: (foo: shortstring);
-{$ELSE}
-        case Byte of
-            SDL_NOEVENT: (type_: Byte);
-            SDL_ACTIVEEVENT: (active: TSDL_ActiveEvent);
-            SDL_KEYDOWN,
-            SDL_KEYUP: (key: TSDL_KeyboardEvent);
-            SDL_MOUSEMOTION: (motion: TSDL_MouseMotionEvent);
-            SDL_MOUSEBUTTONDOWN,
-            SDL_MOUSEBUTTONUP: (button: TSDL_MouseButtonEvent);
-            SDL_JOYAXISMOTION: (jaxis: TSDL_JoyAxisEvent);
-            SDL_JOYHATMOTION: (jhat: TSDL_JoyHatEvent);
-            SDL_JOYBALLMOTION: (jball: TSDL_JoyBallEvent);
-            SDL_JOYBUTTONDOWN,
-            SDL_JOYBUTTONUP: (jbutton: TSDL_JoyButtonEvent);
-            SDL_QUITEV: (quit: TSDL_QuitEvent);
-            //SDL_SYSWMEVENT,SDL_EVENT_RESERVEDA,SDL_EVENT_RESERVEDB
-            SDL_VIDEORESIZE: (resize: TSDL_ResizeEvent);
-            SDL_ALLEVENTS: (foo: shortstring);
-{$ENDIF}
         end;
 
     TSDL_EventFilter = function( event : PSDL_Event ): Integer; cdecl;
@@ -858,7 +928,6 @@
         SDL_GL_MULTISAMPLEBUFFERS,
         SDL_GL_MULTISAMPLESAMPLES,
         SDL_GL_ACCELERATED_VISUAL,
-{$IFDEF SDL2}
         SDL_GL_RETAINED_BACKING,
         SDL_GL_CONTEXT_MAJOR_VERSION,
         SDL_GL_CONTEXT_MINOR_VERSION,
@@ -866,12 +935,8 @@
         SDL_GL_CONTEXT_FLAGS,
         SDL_GL_CONTEXT_PROFILE_MASK,
         SDL_GL_SHARE_WITH_CURRENT_CONTEXT
-{$ELSE}
-        SDL_GL_SWAP_CONTROL
-{$ENDIF}
         );
 
-{$IFDEF SDL2}
     TSDL_ArrayByteOrder = (  // array component order, low Byte -> high Byte
         SDL_ARRAYORDER_NONE,
         SDL_ARRAYORDER_RGB,
@@ -881,7 +946,6 @@
         SDL_ARRAYORDER_BGRA,
         SDL_ARRAYORDER_ABGR
         );
-{$ENDIF}
 
     // Joystick/Controller support
     PSDL_Joystick = ^TSDL_Joystick;
@@ -953,6 +1017,8 @@
 function  SDL_InitSubSystem(flags: LongWord): LongInt; cdecl; external SDLLibName;
 procedure SDL_Quit; cdecl; external SDLLibName;
 
+procedure SDL_free(mem: Pointer); cdecl; external SDLLibName;
+
 procedure SDL_Delay(msec: LongWord); cdecl; external SDLLibName;
 function  SDL_GetTicks: LongWord; cdecl; external SDLLibName;
 
@@ -986,8 +1052,9 @@
 function  SDL_RWFromFile(filename, mode: PChar): PSDL_RWops; cdecl; external SDLLibName;
 function  SDL_SaveBMP_RW(surface: PSDL_Surface; dst: PSDL_RWops; freedst: LongInt): LongInt; cdecl; external SDLLibName;
 
-{$IFDEF SDL2}
 function  SDL_CreateWindow(title: PChar; x,y,w,h: LongInt; flags: LongWord): PSDL_Window; cdecl; external SDLLibName;
+procedure SDL_SetWindowIcon(window: PSDL_Window; icon: PSDL_Surface); cdecl; external SDLLibName;
+
 function  SDL_CreateRenderer(window: PSDL_Window; index: LongInt; flags: LongWord): PSDL_Renderer; cdecl; external SDLLibName;
 function  SDL_DestroyWindow(window: PSDL_Window): LongInt; cdecl; external SDLLibName;
 function  SDL_DestroyRenderer(renderer: PSDL_Renderer): LongInt; cdecl; external SDLLibName;
@@ -996,7 +1063,7 @@
 
 function  SDL_GL_CreateContext(window: PSDL_Window): PSDL_GLContext; cdecl; external SDLLibName;
 procedure SDL_GL_DeleteContext(context: PSDL_GLContext); cdecl; external SDLLibName;
-function  SDL_GL_SwapWindow(window: PSDL_Window): LongInt; cdecl; external SDLLibName;
+procedure SDL_GL_SwapWindow(window: PSDL_Window); cdecl; external SDLLibName;
 function  SDL_GL_SetSwapInterval(interval: LongInt): LongInt; cdecl; external SDLLibName;
 
 procedure SDL_VideoQuit; cdecl; external SDLLibName;
@@ -1017,25 +1084,19 @@
 procedure SDL_WarpMouseInWindow(window: PSDL_Window; x, y: LongInt); cdecl; external SDLLibName;
 function  SDL_SetHint(name, value: PChar): Boolean; cdecl; external SDLLibName;
 procedure SDL_StartTextInput; cdecl; external SDLLibName;
+procedure SDL_StopTextInput; cdecl; external SDLLibName;
 
 function  SDL_PeepEvents(event: PSDL_Event; numevents: LongInt; action: TSDL_eventaction; minType, maxType: LongWord): LongInt; cdecl; external SDLLibName;
 
 function  SDL_AllocFormat(format: LongWord): PSDL_PixelFormat; cdecl; external SDLLibName;
 procedure SDL_FreeFormat(pixelformat: PSDL_PixelFormat); cdecl; external SDLLibName;
-{$ELSE}
-function  SDL_PeepEvents(event: PSDL_Event; numevents: LongInt; action: TSDL_eventaction; mask: LongWord): LongInt; cdecl; external SDLLibName;
-
-function  SDL_EnableUNICODE(enable: LongInt): LongInt; cdecl; external SDLLibName;
-function  SDL_EnableKeyRepeat(timedelay, interval: LongInt): LongInt; cdecl; external SDLLibName;
-function  SDL_VideoDriverName(namebuf: PChar; maxlen: LongInt): PChar; cdecl; external SDLLibName;
-{$ENDIF}
 
 
 function  SDL_GetMouseState(x, y: PLongInt): Byte; cdecl; external SDLLibName;
-function  SDL_GetKeyName(key: LongWord): PChar; cdecl; external SDLLibName;
-function  SDL_GetScancodeName(key: LongWord): PChar; cdecl; external SDLLibName;
-function  SDL_GetKeyFromScancode(key: LongWord): LongInt; cdecl; external SDLLibName;
-
+function  SDL_GetKeyName(key: TSDL_Keycode): PChar; cdecl; external SDLLibName;
+function  SDL_GetScancodeName(key: TSDL_Scancode): PChar; cdecl; external SDLLibName;
+function  SDL_GetKeyFromScancode(key: TSDL_Scancode): TSDL_Keycode; cdecl; external SDLLibName;
+// SDL2 functions has some additional functions (not listed here) for keycode/scancode translation
 
 procedure SDL_PumpEvents; cdecl; external SDLLibName;
 function  SDL_PollEvent(event: PSDL_Event): LongInt; cdecl; external SDLLibName;
@@ -1043,8 +1104,9 @@
 procedure SDL_SetEventFilter(filter: TSDL_EventFilter); cdecl; external SDLLibName;
 
 function  SDL_ShowCursor(toggle: LongInt): LongInt; cdecl; external SDLLibName;
-procedure SDL_WarpMouse(x, y: Word); {$IFDEF SDL2}inline{$ELSE}cdecl; external SDLLibName{$ENDIF};
-function  SDL_GetKeyState(numkeys: PLongInt): PByteArray; cdecl; external SDLLibName {$IFDEF SDL2} name 'SDL_GetKeyboardState'{$ENDIF};
+procedure SDL_WarpMouse(x, y: Word); inline;
+
+function  SDL_GetKeyboardState(numkeys: PLongInt): PByteArray; cdecl; external SDLLibName;
 
 procedure SDL_WM_SetIcon(icon: PSDL_Surface; mask : Byte); cdecl; external SDLLibName;
 procedure SDL_WM_SetCaption(title: PChar; icon: PChar); cdecl; external SDLLibName;
@@ -1053,14 +1115,14 @@
 
 (* remember to mark the threaded functions as 'cdecl; export;'
    (or have fun debugging nil arguments) *)
-function  SDL_CreateThread(fn: Pointer; {$IFDEF SDL2}name: PChar;{$ENDIF} data: Pointer): PSDL_Thread; cdecl; external SDLLibName;
+function  SDL_CreateThread(fn: Pointer; name: PChar; data: Pointer): PSDL_Thread; cdecl; external SDLLibName;
 procedure SDL_WaitThread(thread: PSDL_Thread; status: PLongInt); cdecl; external SDLLibName;
 procedure SDL_KillThread(thread: PSDL_Thread); cdecl; external SDLLibName;
 
 function  SDL_CreateMutex: PSDL_mutex; cdecl; external SDLLibName;
 procedure SDL_DestroyMutex(mutex: PSDL_mutex); cdecl; external SDLLibName;
-function  SDL_LockMutex(mutex: PSDL_mutex): LongInt; cdecl; external SDLLibName {$IFNDEF SDL2}name 'SDL_mutexP'{$ENDIF};
-function  SDL_UnlockMutex(mutex: PSDL_mutex): LongInt; cdecl; external SDLLibName {$IFNDEF SDL2}name 'SDL_mutexV'{$ENDIF};
+function  SDL_LockMutex(mutex: PSDL_mutex): LongInt; cdecl; external SDLLibName;
+function  SDL_UnlockMutex(mutex: PSDL_mutex): LongInt; cdecl; external SDLLibName;
 
 function  SDL_GL_SetAttribute(attr: TSDL_GLattr; value: LongInt): LongInt; cdecl; external SDLLibName;
 procedure SDL_GL_SwapBuffers; cdecl; external SDLLibName;
@@ -1165,6 +1227,12 @@
 function  SDLNet_AddSocket(_set: PSDLNet_SocketSet; sock: PTCPSocket): LongInt; cdecl; external SDL_NetLibName;
 function  SDLNet_CheckSockets(_set: PSDLNet_SocketSet; timeout: LongInt): LongInt; cdecl; external SDL_NetLibName;
 
+// SDL 2 clipboard functions
+function SDL_HasClipboardText(): Boolean; cdecl; external SDLLibName;
+// returns nil if memory for clipboard contents copy couldn't be allocated
+function SDL_GetClipboardText(): PChar; cdecl; external SDLLibName;
+// returns 0 on success or negative error number on failure
+function SDL_SetClipboardText(const text: PChar): LongInt; cdecl; external SDLLibName;
 
 procedure SDLNet_Write16(value: Word; buf: Pointer);
 procedure SDLNet_Write32(value: LongWord; buf: Pointer);
@@ -1172,7 +1240,6 @@
 function  SDLNet_Read32(buf: Pointer): LongWord;
 
 implementation
-{$IFDEF SDL2}
 uses uStore;
 
 // for sdl1.2 we directly call SDL_WarpMouse()
@@ -1183,16 +1250,11 @@
 begin
     WarpMouse(x, y);
 end;
-{$ENDIF}
 
 function SDL_MustLock(Surface: PSDL_Surface): Boolean;
 begin
     SDL_MustLock:=
-{$IFDEF SDL2}
         ((surface^.flags and SDL_RLEACCEL) <> 0)
-{$ELSE}
-        ( surface^.offset <> 0 ) or (( surface^.flags and (SDL_HWSURFACE or SDL_ASYNCBLIT or SDL_RLEACCEL)) <> 0)
-{$ENDIF}
 end;
 
 {$IFNDEF SDL_MIXER_NEWER}
@@ -1245,5 +1307,6 @@
                   (PByteArray(buf)^[0] shl 24)
 end;
 
+
 end.
 
--- a/hedgewars/avwrapper/CMakeLists.txt	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/avwrapper/CMakeLists.txt	Sun Nov 15 13:35:23 2015 +0100
@@ -1,9 +1,5 @@
 #libraries have already been searched in main CMakeLists.txt
 
-# TODO: this check is only for SDL < 2
-# fpc will take care of linking but we need to have this library installed
-find_package(GLUT REQUIRED)
-
 include_directories(${LIBAV_INCLUDE_DIR})
 
 add_library(avwrapper avwrapper.c)
--- a/hedgewars/hwengine.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/hwengine.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -154,11 +154,7 @@
 var event: TSDL_Event;
     PrevTime, CurrTime: LongWord;
     isTerminated: boolean;
-{$IFDEF SDL2}
     previousGameState: TGameState;
-{$ELSE}
-    prevFocusState: boolean;
-{$ENDIF}
 begin
     isTerminated:= false;
     PrevTime:= SDL_GetTicks;
@@ -166,15 +162,14 @@
     begin
         SDL_PumpEvents();
 
-        while SDL_PeepEvents(@event, 1, SDL_GETEVENT, {$IFDEF SDL2}SDL_FIRSTEVENT, SDL_LASTEVENT{$ELSE}SDL_ALLEVENTS{$ENDIF}) > 0 do
+        while SDL_PeepEvents(@event, 1, SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT) > 0 do
         begin
             case event.type_ of
-{$IFDEF SDL2}
                 SDL_KEYDOWN:
                     if GameState = gsChat then
                         begin
                     // sdl on iphone supports only ashii keyboards and the unicode field is deprecated in sdl 1.3
-                        KeyPressChat(SDL_GetKeyFromScancode(event.key.keysym.sym), event.key.keysym.sym, event.key.keysym.modifier);
+                        KeyPressChat(event.key.keysym);
                         end
                     else
                         if GameState >= gsGame then ProcessKey(event.key);
@@ -182,6 +177,20 @@
                     if (GameState <> gsChat) and (GameState >= gsGame) then
                         ProcessKey(event.key);
 
+                SDL_MOUSEBUTTONDOWN:
+                    if GameState = gsConfirm then
+                        ParseCommand('quit', true)
+                    else
+                        if (GameState >= gsGame) then ProcessMouse(event.button, true);
+
+                SDL_MOUSEBUTTONUP:
+                    if (GameState >= gsGame) then ProcessMouse(event.button, false);
+
+                SDL_MOUSEWHEEL:
+                    ProcessMouseWheel(event.wheel.x, event.wheel.y);
+
+                SDL_TEXTINPUT: uChat.TextInput(event.text);
+
                 SDL_WINDOWEVENT:
                     if event.window.event = SDL_WINDOWEVENT_SHOWN then
                     begin
@@ -217,45 +226,6 @@
                 SDL_FINGERUP:
                     onTouchUp(event.tfinger.x, event.tfinger.y, event.tfinger.fingerId);
 {$ENDIF}
-{$ELSE}
-                SDL_KEYDOWN:
-                    if GameState = gsChat then
-                        KeyPressChat(event.key.keysym.unicode, event.key.keysym.sym, event.key.keysym.modifier)
-                    else
-                        if GameState >= gsGame then ProcessKey(event.key);
-                SDL_KEYUP:
-                    if (GameState <> gsChat) and (GameState >= gsGame) then
-                        ProcessKey(event.key);
-
-                SDL_MOUSEBUTTONDOWN:
-                    if GameState = gsConfirm then
-                        ParseCommand('quit', true)
-                    else
-                        if (GameState >= gsGame) then ProcessMouse(event.button, true);
-
-                SDL_MOUSEBUTTONUP:
-                    if (GameState >= gsGame) then ProcessMouse(event.button, false);
-
-                SDL_ACTIVEEVENT:
-                    if (event.active.state and SDL_APPINPUTFOCUS) <> 0 then
-                    begin
-                        prevFocusState:= cHasFocus;
-                        cHasFocus:= event.active.gain = 1;
-                        if prevFocusState xor cHasFocus then
-                            onFocusStateChanged()
-                    end;
-
-                SDL_VIDEORESIZE:
-                begin
-                    // using lower values than cMinScreenWidth or cMinScreenHeight causes widget overlap and off-screen widget parts
-                    // Change by sheepluva:
-                    // Let's only use even numbers for custom width/height since I ran into scaling issues with odd width values.
-                    // Maybe just fixes the symptom not the actual cause(?), I'm too tired to find out :P
-                    cNewScreenWidth:= max(2 * (event.resize.w div 2), cMinScreenWidth);
-                    cNewScreenHeight:= max(2 * (event.resize.h div 2), cMinScreenHeight);
-                    cScreenResizeDelay:= RealTicks+500;
-                end;
-{$ENDIF}
                 SDL_JOYAXISMOTION:
                     ControllerAxisEvent(event.jaxis.which, event.jaxis.axis, event.jaxis.value);
                 SDL_JOYHATMOTION:
@@ -351,20 +321,16 @@
         AddFileLog(inttostr(i) + ': ' + ParamStr(i));
 
     WriteToConsole('Init SDL... ');
-    if not cOnlyStats then SDLTry(SDL_Init(SDL_INIT_VIDEO or SDL_INIT_NOPARACHUTE) >= 0, true);
+    if not cOnlyStats then SDLTry(SDL_Init(SDL_INIT_VIDEO or SDL_INIT_NOPARACHUTE) >= 0, 'SDL_Init', true);
     WriteLnToConsole(msgOK);
 
-{$IFDEF SDL2}
-    SDL_StartTextInput();
-{$ELSE}
-    SDL_EnableUNICODE(1);
-{$ENDIF}
+    //SDL_StartTextInput();
     SDL_ShowCursor(0);
 
     if not cOnlyStats then
         begin
         WriteToConsole('Init SDL_ttf... ');
-        SDLTry(TTF_Init() <> -1, true);
+        SDLTry(TTF_Init() <> -1, 'TTF_Init', true);
         WriteLnToConsole(msgOK);
         end;
 
--- a/hedgewars/options.inc	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/options.inc	Sun Nov 15 13:35:23 2015 +0100
@@ -60,10 +60,6 @@
     {$ENDIF}
 {$ENDIF}
 
-{$IFDEF USE_TOUCH_INTERFACE}
-    {$DEFINE SDL2}
-{$ENDIF}
-
 {$DEFINE _S:=}
 {$DEFINE _P:=}
 
--- a/hedgewars/sdlmain/CMakeLists.txt	Sat Nov 14 22:19:05 2015 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,7 +0,0 @@
-find_package(SDL REQUIRED)
-
-include_directories(${SDL_INCLUDE_DIR})
-
-add_library (SDLmain STATIC SDLMain.m)
-
-
--- a/hedgewars/sdlmain/SDLMain.h	Sat Nov 14 22:19:05 2015 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,16 +0,0 @@
-/*   SDLMain.m - main entry point for our Cocoa-ized SDL app
-       Initial Version: Darrell Walisser <dwaliss1@purdue.edu>
-       Non-NIB-Code & other changes: Max Horn <max@quendi.de>
-
-    Feel free to customize this file to suit your needs
-*/
-
-#ifndef _SDLMain_h_
-#define _SDLMain_h_
-
-#import <Cocoa/Cocoa.h>
-
-@interface SDLMain : NSObject
-@end
-
-#endif /* _SDLMain_h_ */
--- a/hedgewars/sdlmain/SDLMain.m	Sat Nov 14 22:19:05 2015 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,385 +0,0 @@
-/*   SDLMain.m - main entry point for our Cocoa-ized SDL app
-       Initial Version: Darrell Walisser <dwaliss1@purdue.edu>
-       Non-NIB-Code & other changes: Max Horn <max@quendi.de>
-
-    Feel free to customize this file to suit your needs
-*/
-
-#include "SDL.h"
-#include "SDLMain.h"
-#include <sys/param.h> /* for MAXPATHLEN */
-#include <unistd.h>
-
-/* For some reaon, Apple removed setAppleMenu from the headers in 10.4,
- but the method still is there and works. To avoid warnings, we declare
- it ourselves here. */
-@interface NSApplication(SDL_Missing_Methods)
-- (void)setAppleMenu:(NSMenu *)menu;
-@end
-
-/* Use this flag to determine whether we use SDLMain.nib or not */
-#define     SDL_USE_NIB_FILE    0
-
-/* Use this flag to determine whether we use CPS (docking) or not */
-#define     SDL_USE_CPS     1
-#ifdef SDL_USE_CPS
-/* Portions of CPS.h */
-typedef struct CPSProcessSerNum
-{
-    UInt32      lo;
-    UInt32      hi;
-} CPSProcessSerNum;
-
-extern OSErr    CPSGetCurrentProcess( CPSProcessSerNum *psn);
-extern OSErr    CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
-extern OSErr    CPSSetFrontProcess( CPSProcessSerNum *psn);
-
-#endif /* SDL_USE_CPS */
-
-static int    gArgc;
-static char  **gArgv;
-static BOOL   gFinderLaunch;
-static BOOL   gCalledAppMainline = FALSE;
-
-static NSString *getApplicationName(void)
-{
-    const NSDictionary *dict;
-    NSString *appName = 0;
-
-    /* Determine the application name */
-    dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());
-    if (dict)
-        appName = [dict objectForKey: @"CFBundleName"];
-
-    if (![appName length])
-        appName = [[NSProcessInfo processInfo] processName];
-
-    return appName;
-}
-
-#if SDL_USE_NIB_FILE
-/* A helper category for NSString */
-@interface NSString (ReplaceSubString)
-- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString;
-@end
-#endif
-
-@interface SDLApplication : NSApplication
-@end
-
-@implementation SDLApplication
-/* Invoked from the Quit menu item */
-- (void)terminate:(id)sender
-{
-    /* Post a SDL_QUIT event */
-    SDL_Event event;
-    event.type = SDL_QUIT;
-    SDL_PushEvent(&event);
-}
-@end
-
-/* The main class of the application, the application's delegate */
-@implementation SDLMain
-
-/* Set the working directory to the .app's parent directory */
-- (void) setupWorkingDirectory:(BOOL)shouldChdir
-{
-    if (shouldChdir)
-    {
-        char parentdir[MAXPATHLEN];
-        CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());
-        CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url);
-        if (CFURLGetFileSystemRepresentation(url2, 1, (UInt8 *)parentdir, MAXPATHLEN)) {
-            chdir(parentdir);   /* chdir to the binary app's parent */
-        }
-        CFRelease(url);
-        CFRelease(url2);
-    }
-}
-
-#if SDL_USE_NIB_FILE
-
-/* Fix menu to contain the real app name instead of "SDL App" */
-- (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName
-{
-    NSRange aRange;
-    NSEnumerator *enumerator;
-    NSMenuItem *menuItem;
-
-    aRange = [[aMenu title] rangeOfString:@"SDL App"];
-    if (aRange.length != 0)
-        [aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]];
-
-    enumerator = [[aMenu itemArray] objectEnumerator];
-    while ((menuItem = [enumerator nextObject]))
-    {
-        aRange = [[menuItem title] rangeOfString:@"SDL App"];
-        if (aRange.length != 0)
-            [menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]];
-        if ([menuItem hasSubmenu])
-            [self fixMenu:[menuItem submenu] withAppName:appName];
-    }
-    [ aMenu sizeToFit ];
-}
-
-#else
-
-static void setApplicationMenu(void)
-{
-    /* warning: this code is very odd */
-    NSMenu *appleMenu;
-    NSMenuItem *menuItem;
-    NSString *title;
-    NSString *appName;
-
-    appName = getApplicationName();
-    appleMenu = [[NSMenu alloc] initWithTitle:@""];
-
-    /* Add menu items */
-    title = [@"About " stringByAppendingString:appName];
-    [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
-
-    [appleMenu addItem:[NSMenuItem separatorItem]];
-
-    title = [@"Hide " stringByAppendingString:appName];
-    [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
-
-    menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
-    [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
-
-    [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
-
-    [appleMenu addItem:[NSMenuItem separatorItem]];
-
-    title = [@"Quit " stringByAppendingString:appName];
-    [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
-
-
-    /* Put menu into the menubar */
-    menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
-    [menuItem setSubmenu:appleMenu];
-    [[NSApp mainMenu] addItem:menuItem];
-
-    /* Tell the application object that this is now the application menu */
-    [NSApp setAppleMenu:appleMenu];
-
-    /* Finally give up our references to the objects */
-    [appleMenu release];
-    [menuItem release];
-}
-
-/* Create a window menu */
-static void setupWindowMenu(void)
-{
-    NSMenu      *windowMenu;
-    NSMenuItem  *windowMenuItem;
-    NSMenuItem  *menuItem;
-
-    windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
-
-    /* "Minimize" item */
-    menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
-    [windowMenu addItem:menuItem];
-    [menuItem release];
-
-    /* Put menu into the menubar */
-    windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
-    [windowMenuItem setSubmenu:windowMenu];
-    [[NSApp mainMenu] addItem:windowMenuItem];
-
-    /* Tell the application object that this is now the window menu */
-    [NSApp setWindowsMenu:windowMenu];
-
-    /* Finally give up our references to the objects */
-    [windowMenu release];
-    [windowMenuItem release];
-}
-
-/* Replacement for NSApplicationMain */
-static void CustomApplicationMain (int argc, char **argv)
-{
-    NSAutoreleasePool   *pool = [[NSAutoreleasePool alloc] init];
-    SDLMain             *sdlMain;
-
-    /* Ensure the application object is initialised */
-    [SDLApplication sharedApplication];
-
-#ifdef SDL_USE_CPS
-    {
-        CPSProcessSerNum PSN;
-        /* Tell the dock about us */
-        if (!CPSGetCurrentProcess(&PSN))
-            if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103))
-                if (!CPSSetFrontProcess(&PSN))
-                    [SDLApplication sharedApplication];
-    }
-#endif /* SDL_USE_CPS */
-
-    /* Set up the menubar */
-    NSMenu *menu = [[NSMenu alloc] init];
-    [NSApp setMainMenu:menu];
-    setApplicationMenu();
-    setupWindowMenu();
-    [menu release];
-
-    /* Create SDLMain and make it the app delegate */
-    sdlMain = [[SDLMain alloc] init];
-    [NSApp setDelegate:sdlMain];
-
-    /* Start the main event loop */
-    [NSApp run];
-
-    [sdlMain release];
-    [pool release];
-}
-
-#endif
-
-
-/*
- * Catch document open requests...this lets us notice files when the app
- *  was launched by double-clicking a document, or when a document was
- *  dragged/dropped on the app's icon. You need to have a
- *  CFBundleDocumentsType section in your Info.plist to get this message,
- *  apparently.
- *
- * Files are added to gArgv, so to the app, they'll look like command line
- *  arguments. Previously, apps launched from the finder had nothing but
- *  an argv[0].
- *
- * This message may be received multiple times to open several docs on launch.
- *
- * This message is ignored once the app's mainline has been called.
- */
-- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
-{
-    const char *temparg;
-    size_t arglen;
-    char *arg;
-    char **newargv;
-
-    if (!gFinderLaunch)  /* MacOS is passing command line args. */
-        return FALSE;
-
-    if (gCalledAppMainline)  /* app has started, ignore this document. */
-        return FALSE;
-
-    temparg = [filename UTF8String];
-    arglen = SDL_strlen(temparg) + 1;
-    arg = (char *) SDL_malloc(arglen);
-    if (arg == NULL)
-        return FALSE;
-
-    newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2));
-    if (newargv == NULL)
-    {
-        SDL_free(arg);
-        return FALSE;
-    }
-    gArgv = newargv;
-
-    SDL_strlcpy(arg, temparg, arglen);
-    gArgv[gArgc++] = arg;
-    gArgv[gArgc] = NULL;
-    return TRUE;
-}
-
-
-/* Called when the internal event loop has just started running */
-- (void) applicationDidFinishLaunching: (NSNotification *) note
-{
-    int status;
-
-    /* Set the working directory to the .app's parent directory */
-    [self setupWorkingDirectory:gFinderLaunch];
-
-#if SDL_USE_NIB_FILE
-    /* Set the main menu to contain the real app name instead of "SDL App" */
-    [self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()];
-#endif
-
-    /* Hand off to main application code */
-    gCalledAppMainline = TRUE;
-    status = SDL_main (gArgc, gArgv);
-
-    /* We're done, thank you for playing */
-    exit(status);
-}
-@end
-
-
-@implementation NSString (ReplaceSubString)
-
-- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString
-{
-    unsigned int bufferSize;
-    unsigned int selfLen = [self length];
-    unsigned int aStringLen = [aString length];
-    unichar *buffer;
-    NSRange localRange;
-    NSString *result;
-
-    bufferSize = selfLen + aStringLen - aRange.length;
-    buffer = (unichar *)NSAllocateMemoryPages(bufferSize*sizeof(unichar));
-
-    /* Get first part into buffer */
-    localRange.location = 0;
-    localRange.length = aRange.location;
-    [self getCharacters:buffer range:localRange];
-
-    /* Get middle part into buffer */
-    localRange.location = 0;
-    localRange.length = aStringLen;
-    [aString getCharacters:(buffer+aRange.location) range:localRange];
-
-    /* Get last part into buffer */
-    localRange.location = aRange.location + aRange.length;
-    localRange.length = selfLen - localRange.location;
-    [self getCharacters:(buffer+aRange.location+aStringLen) range:localRange];
-
-    /* Build output string */
-    result = [NSString stringWithCharacters:buffer length:bufferSize];
-
-    NSDeallocateMemoryPages(buffer, bufferSize);
-
-    return result;
-}
-
-@end
-
-
-
-#ifdef main
-#  undef main
-#endif
-
-
-/* Main entry point to executable - should *not* be SDL_main! */
-int main (int argc, char **argv)
-{
-    /* Copy the arguments into a global variable */
-    /* This is passed if we are launched by double-clicking */
-    if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) {
-        gArgv = (char **) SDL_malloc(sizeof (char *) * 2);
-        gArgv[0] = argv[0];
-        gArgv[1] = NULL;
-        gArgc = 1;
-        gFinderLaunch = YES;
-    } else {
-        int i;
-        gArgc = argc;
-        gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1));
-        for (i = 0; i <= argc; i++)
-            gArgv[i] = argv[i];
-        gFinderLaunch = NO;
-    }
-
-#if SDL_USE_NIB_FILE
-    [SDLApplication poseAsClass:[NSApplication class]];
-    NSApplicationMain (argc, argv);
-#else
-    CustomApplicationMain (argc, argv);
-#endif
-    return 0;
-}
-
--- a/hedgewars/uAI.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/uAI.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -530,7 +530,7 @@
 FillBonuses(((Me^.State and gstAttacked) <> 0) and (not isInMultiShoot));
 
 SDL_LockMutex(ThreadLock);
-ThinkThread:= SDL_CreateThread(@Think{$IFDEF SDL2}, 'think'{$ENDIF}, Me);
+ThinkThread:= SDL_CreateThread(@Think, PChar('think'), Me);
 SDL_UnlockMutex(ThreadLock);
 end;
 
--- a/hedgewars/uChat.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/uChat.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -21,6 +21,7 @@
 unit uChat;
 
 interface
+uses SDLh;
 
 procedure initModule;
 procedure freeModule;
@@ -28,12 +29,13 @@
 procedure CleanupInput;
 procedure AddChatString(s: shortstring);
 procedure DrawChat;
-procedure KeyPressChat(Key, Sym: Longword; Modifier: Word);
+procedure KeyPressChat(keysym: TSDL_Keysym);
 procedure SendHogSpeech(s: shortstring);
 procedure CopyToClipboard(var newContent: shortstring);
+procedure TextInput(var event: TSDL_TextInputEvent);
 
 implementation
-uses SDLh, uInputHandler, uTypes, uVariables, uCommands, uUtils, uTextures, uRender, uIO, uScript, uRenderUtils;
+uses uInputHandler, uTypes, uVariables, uCommands, uUtils, uTextures, uRender, uIO, uScript, uRenderUtils;
 
 const MaxStrIndex = 27;
       MaxInputStrLen = 200;
@@ -267,8 +269,6 @@
 inc(visibleCount)
 end;
 
-procedure CheckPasteBuffer(); forward;
-
 procedure UpdateInputLinePrefix();
 begin
 if liveLua then
@@ -302,7 +302,6 @@
 // draw chat input line first and under all other lines
 if (GameState = gsChat) and (InputStr.Tex <> nil) then
     begin
-    CheckPasteBuffer();
 
     if InputLinePrefix.Tex = nil then
         RenderChatLineTex(InputLinePrefix, InputLinePrefix.s);
@@ -571,9 +570,8 @@
 begin
     FreezeEnterKey;
     history:= 0;
-{$IFNDEF SDL2}
-    SDL_EnableKeyRepeat(0,0);
-{$ENDIF}
+    SDL_StopTextInput();
+    //SDL_EnableKeyRepeat(0,0);
     GameState:= gsGame;
     ResetKbd;
 end;
@@ -728,7 +726,8 @@
 
 procedure CopyToClipboard(var newContent: shortstring);
 begin
-    SendIPC(_S'y' + copy(newContent, 1, 253) + #0);
+    // SDL2 clipboard
+    SDL_SetClipboardText(Str2PChar(newContent));
 end;
 
 procedure CopySelectionToClipboard();
@@ -782,39 +781,41 @@
 end;
 
 procedure PasteFromClipboard();
+var clip: PChar;
 begin
-    SendIPC(_S'Y');
-end;
-
-procedure CheckPasteBuffer();
-begin
-    if Length(ChatPasteBuffer) > 0 then
+    // use SDL2 clipboard functions
+    if SDL_HasClipboardText() then
         begin
-        InsertIntoInputStr(ChatPasteBuffer);
-        ChatPasteBuffer:= '';
+        clip:= SDL_GetClipboardText();
+        // returns NULL if not enough memory for a copy of clipboard content 
+        if clip <> nil then
+            begin
+            InsertIntoInputStr(shortstring(clip));
+            SDL_free(Pointer(clip));
+            end;
         end;
 end;
 
-procedure KeyPressChat(Key, Sym: Longword; Modifier: Word);
-const firstByteMark: array[0..3] of byte = (0, $C0, $E0, $F0);
-      nonStateMask = (not (KMOD_NUM or KMOD_CAPS));
-var i, btw, index: integer;
-    utf8: shortstring;
-    action, selMode, ctrl, ctrlonly: boolean;
+procedure KeyPressChat(keysym: TSDL_Keysym);
+const nonStateMask = (not (KMOD_NUM or KMOD_CAPS));
+var i, index: integer;
+    selMode, ctrl, ctrlonly: boolean;
     skip: TCharSkip;
+    Scancode: TSDL_Scancode;
+    Modifier: Word;
 begin
+    Scancode:= keysym.scancode;
+    Modifier:= keysym.modifier;
+
     LastKeyPressTick:= RealTicks;
-    action:= true;
-
-    CheckPasteBuffer();
 
     selMode:= (modifier and (KMOD_LSHIFT or KMOD_RSHIFT)) <> 0;
     ctrl:= (modifier and (KMOD_LCTRL or KMOD_RCTRL)) <> 0;
     ctrlonly:= ctrl and ((modifier and nonStateMask and (not (KMOD_LCTRL or KMOD_RCTRL))) = 0);
     skip:= none;
 
-    case Sym of
-        SDLK_BACKSPACE:
+    case Scancode of
+        SDL_SCANCODE_BACKSPACE:
             begin
             if selectedPos < 0 then
                 begin
@@ -831,7 +832,7 @@
             DeleteSelected();
             UpdateCursorCoords();
             end;
-        SDLK_DELETE:
+        SDL_SCANCODE_DELETE:
             begin
             if selectedPos < 0 then
                 begin
@@ -848,7 +849,7 @@
             DeleteSelected();
             UpdateCursorCoords();
             end;
-        SDLK_ESCAPE:
+        SDL_SCANCODE_ESCAPE:
             begin
             if Length(InputStr.s) > 0 then
                 begin
@@ -857,7 +858,7 @@
                 end
             else CleanupInput
             end;
-        SDLK_RETURN, SDLK_KP_ENTER:
+        SDL_SCANCODE_RETURN, SDL_SCANCODE_KP_ENTER:
             begin
             if Length(InputStr.s) > 0 then
                 begin
@@ -867,10 +868,10 @@
                 end;
             CleanupInput
             end;
-        SDLK_UP, SDLK_DOWN:
+        SDL_SCANCODE_UP, SDL_SCANCODE_DOWN:
             begin
-            if (Sym = SDLK_UP) and (history < localLastStr) then inc(history);
-            if (Sym = SDLK_DOWN) and (history > 0) then dec(history);
+            if (Scancode = SDL_SCANCODE_UP) and (history < localLastStr) then inc(history);
+            if (Scancode = SDL_SCANCODE_DOWN) and (history > 0) then dec(history);
             index:= localLastStr - history + 1;
             if (index > localLastStr) then
                 begin
@@ -884,7 +885,7 @@
             ResetSelection();
             UpdateCursorCoords();
             end;
-        SDLK_HOME:
+        SDL_SCANCODE_HOME:
             begin
             if cursorPos > 0 then
                 begin
@@ -896,7 +897,7 @@
 
             UpdateCursorCoords();
             end;
-        SDLK_END:
+        SDL_SCANCODE_END:
             begin
             i:= Length(InputStr.s);
             if cursorPos < i then
@@ -909,7 +910,7 @@
 
             UpdateCursorCoords();
             end;
-        SDLK_LEFT:
+        SDL_SCANCODE_LEFT:
             begin
             if cursorPos > 0 then
                 begin
@@ -938,7 +939,7 @@
 
             UpdateCursorCoords();
             end;
-        SDLK_RIGHT:
+        SDL_SCANCODE_RIGHT:
             begin
             if cursorPos < Length(InputStr.s) then
                 begin
@@ -963,11 +964,12 @@
 
             UpdateCursorCoords();
             end;
-        SDLK_PAGEUP, SDLK_PAGEDOWN:
+        SDL_SCANCODE_PAGEUP, SDL_SCANCODE_PAGEDOWN:
             begin
             // ignore me!!!
             end;
-        SDLK_a:
+        // TODO: figure out how to determine those keys better
+        SDL_SCANCODE_a:
             begin
             // select all
             if ctrlonly then
@@ -978,18 +980,14 @@
                 cursorPos:= Length(InputStr.s);
                 UpdateCursorCoords();
                 end
-            else
-                action:= false;
             end;
-        SDLK_c:
+        SDL_SCANCODE_c:
             begin
             // copy
             if ctrlonly then
                 CopySelectionToClipboard()
-            else
-                action:= false;
             end;
-        SDLK_v:
+        SDL_SCANCODE_v:
             begin
             // paste
             if ctrlonly then
@@ -997,10 +995,8 @@
                 DeleteSelected();
                 PasteFromClipboard();
                 end
-            else
-                action:= false;
             end;
-        SDLK_x:
+        SDL_SCANCODE_x:
             begin
             // cut
             if ctrlonly then
@@ -1008,51 +1004,32 @@
                 CopySelectionToClipboard();
                 DeleteSelected();
                 end
-            else
-                action:= false;
             end;
-        else
-            action:= false;
         end;
-    if not action and (Key <> 0) then
-        begin
-        DeleteSelected();
+end;
 
-        if (Key < $80) then
-            btw:= 1
-        else if (Key < $800) then
-            btw:= 2
-        else if (Key < $10000) then
-            btw:= 3
-        else
-            btw:= 4;
-
-        utf8:= '';
+procedure TextInput(var event: TSDL_TextInputEvent);
+var s: shortstring;
+    l: byte;
+begin
+    DeleteSelected();
 
-        for i:= btw downto 2 do
-            begin
-            utf8:= char((Key or $80) and $BF) + utf8;
-            Key:= Key shr 6
-            end;
-
-        utf8:= char(Key or firstByteMark[Pred(btw)]) + utf8;
-
-        if Length(InputStr.s) + btw > MaxInputStrLen then
-            exit;
+    l:= 0;
+    while event.text[l] <> #0 do
+        begin
+        s[l + 1]:= event.text[l];
+        inc(l)
+        end;
 
-        // if speech bubble quotes are used as first input, add the closing quote and place cursor inbetween
-        if (Length(InputStr.s) = 0) and (Length(utf8) = 1) and (charIsForHogSpeech(utf8[1])) then
-            begin
-            InsertIntoInputStr(utf8);
-            InsertIntoInputStr(utf8);
-            cursorPos:= 1;
-            UpdateCursorCoords();
-            end
-        else
-            InsertIntoInputStr(utf8);
+    if l > 0 then
+        begin
+        if byte(InputStr.s[0]) + l > 240 then exit;
+        s[0]:= char(l);
+        InsertIntoInputStr(s);
         end
 end;
 
+
 procedure chChatMessage(var s: shortstring);
 begin
     AddChatString(s)
@@ -1098,9 +1075,9 @@
 begin
     s:= s; // avoid compiler hint
     GameState:= gsChat;
-{$IFNDEF SDL2}
-    SDL_EnableKeyRepeat(200,45);
-{$ENDIF}
+    SDL_StopTextInput();
+    SDL_StartTextInput();
+    //SDL_EnableKeyRepeat(200,45);
     if length(s) = 0 then
         SetLine(InputStr, '', true)
     else
@@ -1140,6 +1117,7 @@
 
     LastKeyPressTick:= 0;
     ResetCursor();
+    SDL_StopTextInput();
 end;
 
 procedure freeModule;
--- a/hedgewars/uDebug.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/uDebug.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -24,7 +24,7 @@
 
 procedure OutError(Msg: shortstring; isFatalError: boolean);
 procedure TryDo(Assert: boolean; Msg: shortstring; isFatal: boolean); inline;
-procedure SDLTry(Assert: boolean; isFatal: boolean);
+procedure SDLTry(Assert: boolean; Msg: shortstring; isFatal: boolean);
 
 implementation
 uses SDLh, uConsole, uCommands, uConsts;
@@ -47,13 +47,13 @@
     OutError(Msg, isFatal)
 end;
 
-procedure SDLTry(Assert: boolean; isFatal: boolean);
+procedure SDLTry(Assert: boolean; Msg: shortstring; isFatal: boolean);
 var s: shortstring;
 begin
 if not Assert then
     begin
     s:= SDL_GetError();
-    OutError(s, isFatal)
+    OutError(Msg + ': ' + s, isFatal)
     end
 end;
 
--- a/hedgewars/uIO.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/uIO.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -105,16 +105,16 @@
 var ipaddr: TIPAddress;
 begin
     WriteToConsole('Init SDL_Net... ');
-    SDLTry(SDLNet_Init = 0, true);
+    SDLTry(SDLNet_Init = 0, 'SDLNet_Init', true);
     fds:= SDLNet_AllocSocketSet(1);
-    SDLTry(fds <> nil, true);
+    SDLTry(fds <> nil, 'SDLNet_AllocSocketSet', true);
     WriteLnToConsole(msgOK);
     WriteToConsole('Establishing IPC connection to tcp 127.0.0.1:' + IntToStr(ipcPort) + ' ');
     {$HINTS OFF}
-    SDLTry(SDLNet_ResolveHost(ipaddr, PChar('127.0.0.1'), ipcPort) = 0, true);
+    SDLTry(SDLNet_ResolveHost(ipaddr, PChar('127.0.0.1'), ipcPort) = 0, 'SDLNet_ResolveHost', true);
     {$HINTS ON}
     IPCSock:= SDLNet_TCP_Open(ipaddr);
-    SDLTry(IPCSock <> nil, true);
+    SDLTry(IPCSock <> nil, 'SDLNet_TCP_Open', true);
     WriteLnToConsole(msgOK)
 end;
 
@@ -163,7 +163,6 @@
              ParseChatCommand('chatmsg ' + #4, s, 2)
           else
              isProcessed:= false;
-     'Y': ChatPasteBuffer:= copy(s, 2, Length(s) - 1);
      else
         isProcessed:= false;
      end;
--- a/hedgewars/uInputHandler.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/uInputHandler.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -30,6 +30,7 @@
 //procedure MaskModifier(var code: LongInt; modifier: LongWord);
 procedure MaskModifier(Modifier: shortstring; var code: LongInt);
 procedure ProcessMouse(event: TSDL_MouseButtonEvent; ButtonDown: boolean);
+procedure ProcessMouseWheel(x, y: LongInt);
 procedure ProcessKey(event: TSDL_KeyboardEvent); inline;
 procedure ProcessKey(code: LongInt; KeyDown: boolean);
 
@@ -82,8 +83,8 @@
 var code: LongInt;
 begin
     name:= LowerCase(name);
-    code:= cKeyMaxIndex;
-    while (code > 0) and (KeyNames[code] <> name) do dec(code);
+    code:= 0;
+    while (code <= cKeyMaxIndex) and (KeyNames[code] <> name) do inc(code);
 
     MaskModifier(Modifier, code);
     KeyNameToCode:= code;
@@ -168,7 +169,13 @@
 
 if CurrentBinds[code][0] <> #0 then
     begin
-    if (code > 3) and KeyDown and (not ((CurrentBinds[code] = 'put')) or (CurrentBinds[code] = 'ammomenu') or (CurrentBinds[code] = '+cur_u') or (CurrentBinds[code] = '+cur_d') or (CurrentBinds[code] = '+cur_l') or (CurrentBinds[code] = '+cur_r')) and (CurrentTeam <> nil) and (not CurrentTeam^.ExtDriven) then bShowAmmoMenu:= false;
+    if (code < cKeyMaxIndex - 2) // means not mouse buttons
+        and KeyDown
+        and (not ((CurrentBinds[code] = 'put')) or (CurrentBinds[code] = 'ammomenu') or (CurrentBinds[code] = '+cur_u') or (CurrentBinds[code] = '+cur_d') or (CurrentBinds[code] = '+cur_l') or (CurrentBinds[code] = '+cur_r')) 
+        and (CurrentTeam <> nil) 
+        and (not CurrentTeam^.ExtDriven) 
+        then bShowAmmoMenu:= false;
+
     if KeyDown then
         begin
         Trusted:= Trusted and (not isPaused); //releasing keys during pause should be allowed on the other hand
@@ -203,25 +210,36 @@
 procedure ProcessKey(event: TSDL_KeyboardEvent); inline;
 var code: LongInt;
 begin
-    code:= event.keysym.sym;
-    //MaskModifier(code, event.keysym.modifier);
+    // TODO
+    code:= LongInt(event.keysym.scancode);
+    //writelntoconsole('[KEY] '+inttostr(code)+ ' -> ''' +KeyNames[code] + ''', type = '+inttostr(event.type_));
     ProcessKey(code, event.type_ = SDL_KEYDOWN);
 end;
 
 procedure ProcessMouse(event: TSDL_MouseButtonEvent; ButtonDown: boolean);
 begin
-case event.button of
-    SDL_BUTTON_LEFT:
-        ProcessKey(KeyNameToCode('mousel'), ButtonDown);
-    SDL_BUTTON_MIDDLE:
-        ProcessKey(KeyNameToCode('mousem'), ButtonDown);
-    SDL_BUTTON_RIGHT:
-        ProcessKey(KeyNameToCode('mouser'), ButtonDown);
-    SDL_BUTTON_WHEELDOWN:
-        ProcessKey(KeyNameToCode('wheeldown'), ButtonDown);
-    SDL_BUTTON_WHEELUP:
-        ProcessKey(KeyNameToCode('wheelup'), ButtonDown);
-    end;
+    //writelntoconsole('[MOUSE] '+inttostr(event.button));
+    case event.button of
+        SDL_BUTTON_LEFT:
+            ProcessKey(KeyNameToCode('mousel'), ButtonDown);
+        SDL_BUTTON_MIDDLE:
+            ProcessKey(KeyNameToCode('mousem'), ButtonDown);
+        SDL_BUTTON_RIGHT:
+            ProcessKey(KeyNameToCode('mouser'), ButtonDown);
+        SDL_BUTTON_WHEELDOWN:
+            ProcessKey(KeyNameToCode('wheeldown'), ButtonDown);
+        SDL_BUTTON_WHEELUP:
+            ProcessKey(KeyNameToCode('wheelup'), ButtonDown);
+        end;
+end;
+
+procedure ProcessMouseWheel(x, y: LongInt);
+begin
+    //writelntoconsole('[MOUSEWHEEL] '+inttostr(x)+', '+inttostr(y));
+    if y > 0 then
+        ProcessKey(KeyNameToCode('wheelup'), true)
+    else if y < 0 then
+        ProcessKey(KeyNameToCode('wheeldown'), true);
 end;
 
 procedure ResetKbd;
@@ -232,125 +250,131 @@
         ProcessKey(t, False);
 end;
 
+
+procedure InitDefaultBinds;
+var i: Longword;
+begin
+    DefaultBinds[KeyNameToCode('escape')]:= 'quit';
+    DefaultBinds[KeyNameToCode(_S'`')]:= 'history';
+    DefaultBinds[KeyNameToCode('delete')]:= 'rotmask';
+
+    //numpad
+    //DefaultBinds[265]:= '+volup';
+    //DefaultBinds[256]:= '+voldown';
+
+    DefaultBinds[KeyNameToCode(_S'0')]:= '+volup';
+    DefaultBinds[KeyNameToCode(_S'9')]:= '+voldown';
+    DefaultBinds[KeyNameToCode(_S'8')]:= 'mute';
+    DefaultBinds[KeyNameToCode(_S'c')]:= 'capture';
+    DefaultBinds[KeyNameToCode(_S'r')]:= 'record';
+    DefaultBinds[KeyNameToCode(_S'h')]:= 'findhh';
+    DefaultBinds[KeyNameToCode(_S'p')]:= 'pause';
+    DefaultBinds[KeyNameToCode(_S's')]:= '+speedup';
+    DefaultBinds[KeyNameToCode(_S't')]:= 'chat';
+    DefaultBinds[KeyNameToCode(_S'y')]:= 'confirm';
+
+    DefaultBinds[KeyNameToCode('mousem')]:= 'zoomreset';
+    DefaultBinds[KeyNameToCode('wheelup')]:= 'zoomin';
+    DefaultBinds[KeyNameToCode('wheeldown')]:= 'zoomout';
+
+    DefaultBinds[KeyNameToCode('f12')]:= 'fullscr';
+
+
+    DefaultBinds[KeyNameToCode('mousel')]:= '/put';
+    DefaultBinds[KeyNameToCode('mouser')]:= 'ammomenu';
+    DefaultBinds[KeyNameToCode('backspace')]:= 'hjump';
+    DefaultBinds[KeyNameToCode('tab')]:= 'switch';
+    DefaultBinds[KeyNameToCode('return')]:= 'ljump';
+    DefaultBinds[KeyNameToCode('space')]:= '+attack';
+    DefaultBinds[KeyNameToCode('up')]:= '+up';
+    DefaultBinds[KeyNameToCode('down')]:= '+down';
+    DefaultBinds[KeyNameToCode('left')]:= '+left';
+    DefaultBinds[KeyNameToCode('right')]:= '+right';
+    DefaultBinds[KeyNameToCode('left_shift')]:= '+precise';
+
+
+    DefaultBinds[KeyNameToCode('j0a0u')]:= '+left';
+    DefaultBinds[KeyNameToCode('j0a0d')]:= '+right';
+    DefaultBinds[KeyNameToCode('j0a1u')]:= '+up';
+    DefaultBinds[KeyNameToCode('j0a1d')]:= '+down';
+    for i:= 1 to 10 do DefaultBinds[KeyNameToCode('f'+IntToStr(i))]:= 'slot '+IntToStr(i);
+    for i:= 1 to 5  do DefaultBinds[KeyNameToCode(IntToStr(i))]:= 'timer '+IntToStr(i);
+
+    loadBinds('dbind', cPathz[ptData] + '/settings.ini');
+end;
+
+
 procedure InitKbdKeyTable;
 var i, j, k, t: LongInt;
     s: string[15];
 begin
-//TODO in sdl13 this overrides some values (A and B) change indices to some other values at the back perhaps?
-KeyNames[1]:= 'mousel';
-KeyNames[2]:= 'mousem';
-KeyNames[3]:= 'mouser';
-KeyNames[4]:= 'wheelup';
-KeyNames[5]:= 'wheeldown';
+    KeyNames[cKeyMaxIndex    ]:= 'mousel';
+    KeyNames[cKeyMaxIndex - 1]:= 'mousem';
+    KeyNames[cKeyMaxIndex - 2]:= 'mouser';
+    KeyNames[cKeyMaxIndex - 3]:= 'wheelup';
+    KeyNames[cKeyMaxIndex - 4]:= 'wheeldown';
 
-for i:= 6 to cKeyMaxIndex do
-    begin
-    s:= shortstring(sdl_getkeyname(i));
-    //WriteLnToConsole('uInputHandler - ' + IntToStr(i) + ': ' + s + ' ' + IntToStr(cKeyMaxIndex));
-    if s = 'unknown key' then KeyNames[i]:= ''
-    else
+    for i:= 0 to cKeyMaxIndex - 5 do
         begin
+        s:= shortstring(SDL_GetScancodeName(TSDL_Scancode(i)));
+
         for t:= 1 to Length(s) do
             if s[t] = ' ' then
                 s[t]:= '_';
         KeyNames[i]:= LowerCase(s)
         end;
-    end;
 
 
-// get the size of keyboard array
-SDL_GetKeyState(@k);
+    // get the size of keyboard array
+    SDL_GetKeyboardState(@k);
 
-// Controller(s)
-for j:= 0 to Pred(ControllerNumControllers) do
-    begin
-    for i:= 0 to Pred(ControllerNumAxes[j]) do
+    // Controller(s)
+    for j:= 0 to Pred(ControllerNumControllers) do
         begin
-        keynames[k + 0]:= 'j' + IntToStr(j) + 'a' + IntToStr(i) + 'u';
-        keynames[k + 1]:= 'j' + IntToStr(j) + 'a' + IntToStr(i) + 'd';
-        inc(k, 2);
-        end;
-    for i:= 0 to Pred(ControllerNumHats[j]) do
-        begin
-        keynames[k + 0]:= 'j' + IntToStr(j) + 'h' + IntToStr(i) + 'u';
-        keynames[k + 1]:= 'j' + IntToStr(j) + 'h' + IntToStr(i) + 'r';
-        keynames[k + 2]:= 'j' + IntToStr(j) + 'h' + IntToStr(i) + 'd';
-        keynames[k + 3]:= 'j' + IntToStr(j) + 'h' + IntToStr(i) + 'l';
-        inc(k, 4);
-        end;
-    for i:= 0 to Pred(ControllerNumButtons[j]) do
-        begin
-        keynames[k]:= 'j' + IntToStr(j) + 'b' + IntToStr(i);
-        inc(k, 1);
+        for i:= 0 to Pred(ControllerNumAxes[j]) do
+            begin
+            KeyNames[k + 0]:= 'j' + IntToStr(j) + 'a' + IntToStr(i) + 'u';
+            KeyNames[k + 1]:= 'j' + IntToStr(j) + 'a' + IntToStr(i) + 'd';
+            inc(k, 2);
+            end;
+        for i:= 0 to Pred(ControllerNumHats[j]) do
+            begin
+            KeyNames[k + 0]:= 'j' + IntToStr(j) + 'h' + IntToStr(i) + 'u';
+            KeyNames[k + 1]:= 'j' + IntToStr(j) + 'h' + IntToStr(i) + 'r';
+            KeyNames[k + 2]:= 'j' + IntToStr(j) + 'h' + IntToStr(i) + 'd';
+            KeyNames[k + 3]:= 'j' + IntToStr(j) + 'h' + IntToStr(i) + 'l';
+            inc(k, 4);
+            end;
+        for i:= 0 to Pred(ControllerNumButtons[j]) do
+            begin
+            KeyNames[k]:= 'j' + IntToStr(j) + 'b' + IntToStr(i);
+            inc(k, 1);
+            end;
         end;
-    end;
 
-DefaultBinds[KeyNameToCode('escape')]:= 'quit';
-DefaultBinds[KeyNameToCode(_S'`')]:= 'history';
-DefaultBinds[KeyNameToCode('delete')]:= 'rotmask';
-
-//numpad
-//DefaultBinds[265]:= '+volup';
-//DefaultBinds[256]:= '+voldown';
-
-DefaultBinds[KeyNameToCode(_S'0')]:= '+volup';
-DefaultBinds[KeyNameToCode(_S'9')]:= '+voldown';
-DefaultBinds[KeyNameToCode(_S'8')]:= 'mute';
-DefaultBinds[KeyNameToCode(_S'c')]:= 'capture';
-DefaultBinds[KeyNameToCode(_S'r')]:= 'record';
-DefaultBinds[KeyNameToCode(_S'h')]:= 'findhh';
-DefaultBinds[KeyNameToCode(_S'p')]:= 'pause';
-DefaultBinds[KeyNameToCode(_S's')]:= '+speedup';
-DefaultBinds[KeyNameToCode(_S't')]:= 'chat';
-DefaultBinds[KeyNameToCode(_S'y')]:= 'confirm';
-
-DefaultBinds[KeyNameToCode('mousem')]:= 'zoomreset';
-DefaultBinds[KeyNameToCode('wheelup')]:= 'zoomin';
-DefaultBinds[KeyNameToCode('wheeldown')]:= 'zoomout';
-
-DefaultBinds[KeyNameToCode('f12')]:= 'fullscr';
+        InitDefaultBinds
+end;
 
 
-DefaultBinds[KeyNameToCode('mousel')]:= '/put';
-DefaultBinds[KeyNameToCode('mouser')]:= 'ammomenu';
-DefaultBinds[KeyNameToCode('backspace')]:= 'hjump';
-DefaultBinds[KeyNameToCode('tab')]:= 'switch';
-DefaultBinds[KeyNameToCode('return')]:= 'ljump';
-DefaultBinds[KeyNameToCode('space')]:= '+attack';
-DefaultBinds[KeyNameToCode('up')]:= '+up';
-DefaultBinds[KeyNameToCode('down')]:= '+down';
-DefaultBinds[KeyNameToCode('left')]:= '+left';
-DefaultBinds[KeyNameToCode('right')]:= '+right';
-DefaultBinds[KeyNameToCode('left_shift')]:= '+precise';
 
-
-DefaultBinds[KeyNameToCode('j0a0u')]:= '+left';
-DefaultBinds[KeyNameToCode('j0a0d')]:= '+right';
-DefaultBinds[KeyNameToCode('j0a1u')]:= '+up';
-DefaultBinds[KeyNameToCode('j0a1d')]:= '+down';
-for i:= 1 to 10 do DefaultBinds[KeyNameToCode('f'+IntToStr(i))]:= 'slot '+char(i+48);
-for i:= 1 to 5  do DefaultBinds[KeyNameToCode(IntToStr(i))]:= 'timer '+IntToStr(i);
-
-loadBinds('dbind', cPathz[ptData] + '/settings.ini');
-end;
-
+{$IFNDEF MOBILE}
 procedure SetBinds(var binds: TBinds);
-{$IFNDEF MOBILE}
 var
     t: LongInt;
-{$ENDIF}
 begin
-{$IFDEF MOBILE}
-    binds:= binds; // avoid hint
-    CurrentBinds:= DefaultBinds;
-{$ELSE}
     for t:= 0 to cKbdMaxIndex do
         if (CurrentBinds[t] <> binds[t]) and tkbd[t] then
             ProcessKey(t, False);
 
     CurrentBinds:= binds;
+end;
+{$ELSE}
+procedure SetBinds(var binds: TBinds);
+begin
+    binds:= binds; // avoid hint
+    CurrentBinds:= DefaultBinds;
+end;
 {$ENDIF}
-end;
 
 procedure SetDefaultBinds;
 begin
@@ -438,7 +462,7 @@
 var
     k: LongInt;
 begin
-    SDL_GetKeyState(@k);
+    SDL_GetKeyboardState(@k);
     k:= k + joy * (ControllerNumAxes[joy]*2 + ControllerNumHats[joy]*4 + ControllerNumButtons[joy]*2);
     ProcessKey(k +  axis*2, value > 20000);
     ProcessKey(k + (axis*2)+1, value < -20000);
@@ -448,7 +472,7 @@
 var
     k: LongInt;
 begin
-    SDL_GetKeyState(@k);
+    SDL_GetKeyboardState(@k);
     k:= k + joy * (ControllerNumAxes[joy]*2 + ControllerNumHats[joy]*4 + ControllerNumButtons[joy]*2);
     ProcessKey(k +  ControllerNumAxes[joy]*2 + hat*4 + 0, (value and SDL_HAT_UP)   <> 0);
     ProcessKey(k +  ControllerNumAxes[joy]*2 + hat*4 + 1, (value and SDL_HAT_RIGHT)<> 0);
@@ -460,7 +484,7 @@
 var
     k: LongInt;
 begin
-    SDL_GetKeyState(@k);
+    SDL_GetKeyboardState(@k);
     k:= k + joy * (ControllerNumAxes[joy]*2 + ControllerNumHats[joy]*4 + ControllerNumButtons[joy]*2);
     ProcessKey(k +  ControllerNumAxes[joy]*2 + ControllerNumHats[joy]*4 + button, pressed);
 end;
--- a/hedgewars/uLand.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/uLand.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -263,7 +263,7 @@
 TryDo(Surface <> nil, 'Assert (LandSurface <> nil) failed', true);
 
 if SDL_MustLock(Surface) then
-    SDLTry(SDL_LockSurface(Surface) >= 0, true);
+    SDLTry(SDL_LockSurface(Surface) >= 0, 'SDL_LockSurface', true);
 
 p:= Surface^.pixels;
 for y:= 0 to LAND_HEIGHT - 1 do
@@ -451,7 +451,7 @@
     cpX:= (LAND_WIDTH - tmpsurf^.w) div 2;
     cpY:= LAND_HEIGHT - tmpsurf^.h;
     if SDL_MustLock(tmpsurf) then
-        SDLTry(SDL_LockSurface(tmpsurf) >= 0, true);
+        SDLTry(SDL_LockSurface(tmpsurf) >= 0, 'SDL_LockSurface', true);
 
         p:= tmpsurf^.pixels;
         for y:= 0 to Pred(tmpsurf^.h) do
--- a/hedgewars/uLandGraphics.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/uLandGraphics.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -716,7 +716,7 @@
 col:= Frame div numFramesFirstCol;
 
 if SDL_MustLock(Image) then
-    SDLTry(SDL_LockSurface(Image) >= 0, true);
+    SDLTry(SDL_LockSurface(Image) >= 0, 'TryPlaceOnLand', true);
 
 bpp:= Image^.format^.BytesPerPixel;
 TryDo(bpp = 4, 'It should be 32 bpp sprite', true);
@@ -835,7 +835,7 @@
 col:= Frame div numFramesFirstCol;
 
 if SDL_MustLock(Image) then
-    SDLTry(SDL_LockSurface(Image) >= 0, true);
+    SDLTry(SDL_LockSurface(Image) >= 0, 'EraseLand', true);
 
 bpp:= Image^.format^.BytesPerPixel;
 TryDo(bpp = 4, 'It should be 32 bpp sprite', true);
@@ -918,7 +918,7 @@
 col:= Frame div numFramesFirstCol;
 
 if SDL_MustLock(Image) then
-    SDLTry(SDL_LockSurface(Image) >= 0, true);
+    SDLTry(SDL_LockSurface(Image) >= 0, 'SDL_LockSurface', true);
 
 bpp:= Image^.format^.BytesPerPixel;
 TryDo(bpp = 4, 'It should be 32 bpp sprite', true);
@@ -930,7 +930,7 @@
 TryDo(finalSurface <> nil, 'GetPlaceCollisionTex: fail to create surface', true);
 
 if SDL_MustLock(finalSurface) then
-    SDLTry(SDL_LockSurface(finalSurface) >= 0, true);
+    SDLTry(SDL_LockSurface(finalSurface) >= 0, 'GetPlaceCollisionTex', true);
 
 p:= PLongWordArray(@(PLongWordArray(Image^.pixels)^[ (Image^.pitch div 4) * row * h + col * w ]));
 pt:= PLongWordArray(finalSurface^.pixels);
--- a/hedgewars/uLandObjects.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/uLandObjects.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -109,7 +109,7 @@
 WriteToConsole('Generating collision info... ');
 
 if SDL_MustLock(Image) then
-    SDLTry(SDL_LockSurface(Image) >= 0, true);
+    SDLTry(SDL_LockSurface(Image) >= 0, 'SDL_LockSurface', true);
 
 bpp:= Image^.format^.BytesPerPixel;
 TryDo(bpp = 4, 'Land object should be 32bit', true);
@@ -160,7 +160,7 @@
 WriteToConsole('Generating collision info... ');
 
 if SDL_MustLock(Image) then
-    SDLTry(SDL_LockSurface(Image) >= 0, true);
+    SDLTry(SDL_LockSurface(Image) >= 0, 'SDL_LockSurface', true);
 
 bpp:= Image^.format^.BytesPerPixel;
 TryDo(bpp = 4, 'Land object should be 32bit', true);
@@ -208,8 +208,8 @@
 
 procedure InitRects;
 begin
-RectCount:= 0;
-New(Rects)
+    RectCount:= 0;
+    New(Rects)
 end;
 
 procedure FreeRects;
@@ -365,7 +365,7 @@
 CheckCanPlace:= bRes;
 end;
 
-function TryPut(var Obj: TThemeObject): boolean; overload;
+function TryPut(var Obj: TThemeObject): boolean;
 const MaxPointsIndex = 2047;
 var x, y: Longword;
     ar: array[0..MaxPointsIndex] of TPoint;
@@ -386,12 +386,12 @@
                 begin
                 ar[cnt].x:= x;
                 ar[cnt].y:= y;
-                inc(cnt);
-                if cnt > MaxPointsIndex then // buffer is full, do not check the rest land
+                if cnt >= MaxPointsIndex then // buffer is full, do not check the rest land
                     begin
                     y:= LAND_HEIGHT;
                     x:= LAND_WIDTH;
                     end
+                    else inc(cnt);
                 end;
             inc(y, 3);
         until y >= LAND_HEIGHT - Height;
@@ -412,7 +412,7 @@
 TryPut:= bRes;
 end;
 
-function TryPut(var Obj: TSprayObject; Surface: PSDL_Surface): boolean; overload;
+function TryPut2(var Obj: TSprayObject; Surface: PSDL_Surface): boolean;
 const MaxPointsIndex = 8095;
 var x, y: Longword;
     ar: array[0..MaxPointsIndex] of TPoint;
@@ -420,7 +420,7 @@
     r: TSDL_Rect;
     bRes: boolean;
 begin
-TryPut:= false;
+TryPut2:= false;
 cnt:= 0;
 with Obj do
     begin
@@ -439,18 +439,19 @@
                 begin
                 ar[cnt].x:= x;
                 ar[cnt].y:= y;
-                inc(cnt);
-                if cnt > MaxPointsIndex then // buffer is full, do not check the rest land
+                if cnt >= MaxPointsIndex then // buffer is full, do not check the rest land
                     begin
-                    y:= 5000;
-                    x:= 5000;
+                    y:= $FF000000;
+                    x:= $FF000000;
                     end
+                    else inc(cnt);
                 end;
             inc(y, 12);
         until y >= LAND_HEIGHT - Height - 8;
         inc(x, getrandom(12) + 12)
     until x >= LAND_WIDTH - Width;
     bRes:= cnt <> 0;
+AddFileLog('CHECKPOINT 004');
     if bRes then
         begin
         i:= getrandom(cnt);
@@ -464,7 +465,7 @@
         end
     else Maxcnt:= 0
     end;
-TryPut:= bRes;
+TryPut2:= bRes;
 end;
 
 
@@ -845,13 +846,13 @@
         exit;
     WriteLnToConsole('Adding theme objects...');
 
-    for i:=0 to ThemeObjects.Count do
+    for i:=0 to Pred(ThemeObjects.Count) do
         ThemeObjects.objs[i].Maxcnt := max(1, (ThemeObjects.objs[i].Maxcnt * MaxHedgehogs) div 18); // Maxcnt is proportional to map size, but allow objects to span even if we're on a tiny map
 
     repeat
         t := getrandom(ThemeObjects.Count);
         b := false;
-        for i:=0 to ThemeObjects.Count do
+        for i:= 0 to Pred(ThemeObjects.Count) do
             begin
             ii := (i+t) mod ThemeObjects.Count;
 
@@ -869,18 +870,18 @@
         exit;
     WriteLnToConsole('Adding spray objects...');
 
-    for i:=0 to SprayObjects.Count do
+    for i:= 0 to Pred(SprayObjects.Count) do
         SprayObjects.objs[i].Maxcnt := max(1, (SprayObjects.objs[i].Maxcnt * MaxHedgehogs) div 18); // Maxcnt is proportional to map size, but allow objects to span even if we're on a tiny map
 
     repeat
         t := getrandom(SprayObjects.Count);
         b := false;
-        for i:=0 to SprayObjects.Count do
+        for i:= 0 to Pred(SprayObjects.Count) do
             begin
             ii := (i+t) mod SprayObjects.Count;
 
             if SprayObjects.objs[ii].Maxcnt <> 0 then
-                b := b or TryPut(SprayObjects.objs[ii], Surface)
+                b := b or TryPut2(SprayObjects.objs[ii], Surface)
             end;
     until not b;
 end;
@@ -915,7 +916,6 @@
 procedure AddOnLandObjects(Surface: PSDL_Surface);
 begin
 InitRects;
-//AddSprayObjects(Surface, SprayObjects, 12);
 AddSprayObjects(Surface, SprayObjects);
 FreeRects
 end;
--- a/hedgewars/uMisc.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/uMisc.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -30,11 +30,7 @@
 function  doSurfaceConversion(tmpsurf: PSDL_Surface): PSDL_Surface;
 function MakeScreenshot(filename: shortstring; k: LongInt; dump: LongWord): boolean;
 function  GetTeamStatString(p: PTeam): shortstring;
-{$IFDEF SDL2}
 function  SDL_RectMake(x, y, width, height: LongInt): TSDL_Rect; inline;
-{$ELSE}
-function  SDL_RectMake(x, y: SmallInt; width, height: Word): TSDL_Rect; inline;
-{$ENDIF}
 
 implementation
 uses SysUtils, uVariables, uUtils
@@ -303,7 +299,7 @@
 image^.size:= size;
 image^.buffer:= p;
 
-SDL_CreateThread(@SaveScreenshot{$IFDEF SDL2}, 'snapshot'{$ENDIF}, image);
+SDL_CreateThread(@SaveScreenshot, PChar('snapshot'), image);
 MakeScreenshot:= true; // possibly it is not true but we will not wait for thread to terminate
 end;
 
@@ -321,11 +317,7 @@
     end;
 end;
 
-{$IFDEF SDL2}
 function SDL_RectMake(x, y, width, height: LongInt): TSDL_Rect; inline;
-{$ELSE}
-function SDL_RectMake(x, y: SmallInt; width, height: Word): TSDL_Rect; inline;
-{$ENDIF}
 begin
     SDL_RectMake.x:= x;
     SDL_RectMake.y:= y;
@@ -340,32 +332,15 @@
     GetTeamStatString:= s;
 end;
 
-{$IFDEF SDL2}
-// FIXME - pretty sure this is not handling endianness correctly like the SDL1 is
+procedure initModule;
 const SDL_PIXELFORMAT_ABGR8888 = (1 shl 28) or (6 shl 24) or (7 shl 20) or (6 shl 16) or (32 shl 8) or 4;
-{$ELSE}
-const format: TSDL_PixelFormat = (
-        palette: nil; BitsPerPixel: 32; BytesPerPixel: 4;
-        Rloss: 0; Gloss: 0; Bloss: 0; Aloss: 0;
-        Rshift: RShift; Gshift: GShift; Bshift: BShift; Ashift: AShift;
-        RMask: RMask; GMask: GMask; BMask: BMask; AMask: AMask;
-        colorkey: 0; alpha: 255);
-{$ENDIF}
-
-procedure initModule;
 begin
-{$IFDEF SDL2}
     conversionFormat:= SDL_AllocFormat(SDL_PIXELFORMAT_ABGR8888);
-{$ELSE}
-    conversionFormat:= @format;
-{$ENDIF}
 end;
 
 procedure freeModule;
 begin
-{$IFDEF SDL2}
     SDL_FreeFormat(conversionFormat);
-{$ENDIF}
 end;
 
 end.
--- a/hedgewars/uRender.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/uRender.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -104,8 +104,7 @@
 
 implementation
 uses {$IFNDEF PAS2C} StrUtils, {$ENDIF}SysUtils, uVariables, uUtils, uConsts
-     {$IFDEF GL2}, uMatrix, uConsole{$ENDIF}
-     {$IF NOT DEFINED(SDL2) AND DEFINED(USE_VIDEO_RECORDING)}, glut {$ENDIF};
+     {$IFDEF GL2}, uMatrix, uConsole{$ENDIF};
 
 {$IFDEF USE_TOUCH_INTERFACE}
 const
--- a/hedgewars/uRenderUtils.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/uRenderUtils.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -99,7 +99,7 @@
     tmpsurf:= TTF_RenderUTF8_Blended(Fontz[Font].Handle, PChar(s), clr);
     finalRect.x:= X + cFontBorder + 2;
     finalRect.y:= Y + cFontBorder;
-    SDLTry(tmpsurf <> nil, true);
+    SDLTry(tmpsurf <> nil, 'TTF_RenderUTF8_Blended', true);
     SDL_UpperBlit(tmpsurf, @textRect, Surface, @finalRect);
     SDL_FreeSurface(tmpsurf);
     finalRect.x:= X;
@@ -522,7 +522,7 @@
         rect.x:= edgeHeight + 1 + ((i - w) div 2);
         // trying to more evenly position the text, vertically
         rect.y:= edgeHeight + ((j-(numLines*h)) div 2) + line * h;
-        SDLTry(tmpsurf <> nil, true);
+        SDLTry(tmpsurf <> nil, 'TTF_Init', true);
         SDL_UpperBlit(tmpsurf, nil, finalSurface, @rect);
         SDL_FreeSurface(tmpsurf);
         inc(line);
--- a/hedgewars/uSound.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/uSound.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -322,7 +322,7 @@
     end;
 
     WriteToConsole('Init SDL_mixer... ');
-    SDLTry(Mix_Init(MIX_INIT_OGG) <> 0, true);
+    SDLTry(Mix_Init(MIX_INIT_OGG) <> 0, 'Mix_Init', true);
     WriteLnToConsole(msgOK);
 
     Mix_AllocateChannels(Succ(chanTPU));
@@ -424,7 +424,7 @@
             s:= cPathz[Soundz[snd].Path] + '/' + Soundz[snd].FileName;
             WriteToConsole(msgLoading + s + ' ');
             defVoicepack^.chunks[snd]:= Mix_LoadWAV_RW(rwopsOpenRead(s), 1);
-            SDLTry(defVoicepack^.chunks[snd] <> nil, true);
+            SDLTry(defVoicepack^.chunks[snd] <> nil, 'Mix_LoadWAV_RW', true);
             WriteLnToConsole(msgOK);
             end;
         lastChan[snd]:= Mix_PlayChannelTimed(-1, defVoicepack^.chunks[snd], 0, -1)
@@ -523,7 +523,7 @@
             s:= cPathz[Soundz[snd].Path] + '/' + Soundz[snd].FileName;
             WriteToConsole(msgLoading + s + ' ');
             defVoicepack^.chunks[snd]:= Mix_LoadWAV_RW(rwopsOpenRead(s), 1);
-            SDLTry(defVoicepack^.chunks[snd] <> nil, true);
+            SDLTry(defVoicepack^.chunks[snd] <> nil, 'Mix_LoadWAV_RW', true);
             WriteLnToConsole(msgOK);
             end;
         if fadems > 0 then
@@ -574,10 +574,10 @@
     WriteToConsole(msgLoading + s + ' ');
 
     Mus:= Mix_LoadMUS_RW(rwopsOpenRead(s));
-    SDLTry(Mus <> nil, false);
+    SDLTry(Mus <> nil, 'Mix_LoadMUS_RW', false);
     WriteLnToConsole(msgOK);
 
-    SDLTry(Mix_FadeInMusic(Mus, -1, 3000) <> -1, false)
+    SDLTry(Mix_FadeInMusic(Mus, -1, 3000) <> -1, 'Mix_FadeInMusic', false)
 end;
 
 procedure SetVolume(vol: LongInt);
--- a/hedgewars/uStore.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/uStore.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -55,25 +55,20 @@
 procedure InitOffscreenOpenGL;
 {$ENDIF}
 
-{$IFDEF SDL2}
 procedure WarpMouse(x, y: Word); inline;
-{$ENDIF}
 procedure SwapBuffers; {$IFDEF USE_VIDEO_RECORDING}cdecl{$ELSE}inline{$ENDIF};
 procedure SetSkyColor(r, g, b: real);
 
 implementation
 uses uMisc, uConsole, uVariables, uUtils, uTextures, uRender, uRenderUtils,
      uCommands, uPhysFSLayer, uDebug
-    {$IFDEF USE_CONTEXT_RESTORE}, uWorld{$ENDIF}
-    {$IF NOT DEFINED(SDL2) AND DEFINED(USE_VIDEO_RECORDING)}, glut {$ENDIF};
+    {$IFDEF USE_CONTEXT_RESTORE}, uWorld{$ENDIF};
 
-var
-{$IFDEF SDL2}
+//type TGPUVendor = (gvUnknown, gvNVIDIA, gvATI, gvIntel, gvApple);
+
+var 
     SDLwindow: PSDL_Window;
     SDLGLcontext: PSDL_GLContext;
-{$ELSE}
-    SDLPrimSurface: PSDL_Surface;
-{$ENDIF}
     squaresize : LongInt;
     numsquares : LongInt;
     ProgrTex: PTexture;
@@ -117,9 +112,9 @@
 clr.g:= (Color shr 8) and $FF;
 clr.b:= Color and $FF;
 tmpsurf:= TTF_RenderUTF8_Blended(Fontz[Font].Handle, s, clr);
-SDLTry(tmpsurf <> nil, true);
+SDLTry(tmpsurf <> nil, 'TTF_RenderUTF8_Blended', true);
 tmpsurf:= doSurfaceConversion(tmpsurf);
-SDLTry(tmpsurf <> nil, true);
+SDLTry(tmpsurf <> nil, 'TTF_RenderUTF8_Blended, doSurfaceConversion', true);
 SDL_UpperBlit(tmpsurf, nil, Surface, @finalRect);
 SDL_FreeSurface(tmpsurf);
 finalRect.x:= X;
@@ -361,7 +356,7 @@
             s:= cPathz[ptFonts] + '/' + Name;
             WriteToConsole(msgLoading + s + ' (' + inttostr(Height) + 'pt)... ');
             Handle:= TTF_OpenFontRW(rwopsOpenRead(s), true, Height);
-            SDLTry(Handle <> nil, true);
+            SDLTry(Handle <> nil, 'TTF_OpenFontRW', true);
             TTF_SetFontStyle(Handle, style);
             WriteLnToConsole(msgOK)
             end;
@@ -610,7 +605,7 @@
             // anounce that loading failed
             OutError(msgFailed, false);
 
-            SDLTry(false, (imageFlags and ifCritical) <> 0);
+            SDLTry(false, 'LoadImage', (imageFlags and ifCritical) <> 0);
             // rwops was already freed by IMG_Load_RW
             rwops:= nil;
             end else
@@ -729,9 +724,6 @@
 {$ELSE}
     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
 {$ENDIF}
-{$IFNDEF SDL2} // vsync is default in SDL2
-    SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, LongInt((cReducedQuality and rqDesyncVBlank) = 0));
-{$ENDIF}
     SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
     SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
     SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
@@ -744,49 +736,22 @@
 procedure SetupOpenGL;
 var buf: array[byte] of char;
 begin
+    AddFileLog('Setting up OpenGL (using driver: ' + shortstring(SDL_GetCurrentVideoDriver()) + ')');
 
-{$IFDEF SDL2}
-    AddFileLog('Setting up OpenGL (using driver: ' + shortstring(SDL_GetCurrentVideoDriver()) + ')');
-{$ELSE}
-    buf[0]:= char(0); // avoid compiler hint
-    AddFileLog('Setting up OpenGL (using driver: ' + shortstring(SDL_VideoDriverName(buf, sizeof(buf))) + ')');
-{$ENDIF}
-
-{$IFDEF MOBILE}
     // TODO: this function creates an opengles1.1 context
     // un-comment below and add proper logic to support opengles2.0
     //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
     //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
     if SDLGLcontext = nil then
         SDLGLcontext:= SDL_GL_CreateContext(SDLwindow);
-    SDLTry(SDLGLcontext <> nil, true);
-    SDL_GL_SetSwapInterval(1);
-{$ENDIF}
+    SDLTry(SDLGLcontext <> nil, 'SDLGLcontext', true);
+    SDLTry(SDL_GL_SetSwapInterval(1) = 0, 'SDL_GL_SetSwapInterval', true);
 
     RendererSetup();
+
+// gl2 init/matrix code was here, but removed
 end;
 
-(*
-procedure UpdateProjection;
-var
-    s: GLfloat;
-begin
-    s:=cScaleFactor;
-    mProjection[0,0]:= s/cScreenWidth; mProjection[0,1]:=  0.0;             mProjection[0,2]:=0.0; mProjection[0,3]:=  0.0;
-    mProjection[1,0]:= 0.0;            mProjection[1,1]:= -s/cScreenHeight; mProjection[1,2]:=0.0; mProjection[1,3]:=  0.0;
-    mProjection[2,0]:= 0.0;            mProjection[2,1]:=  0.0;             mProjection[2,2]:=1.0; mProjection[2,3]:=  0.0;
-    mProjection[3,0]:= cStereoDepth;   mProjection[3,1]:=  s/2;             mProjection[3,2]:=0.0; mProjection[3,3]:=  1.0;
-
-{$IFDEF GL2}
-    UpdateModelviewProjection;
-{$ELSE}
-    glMatrixMode(GL_PROJECTION);
-    glLoadMatrixf(@mProjection[0, 0]);
-    glMatrixMode(GL_MODELVIEW);
-{$ENDIF}
-end;
-*)
-
 ////////////////////////////////////////////////////////////////////////////////
 procedure AddProgress;
 var r: TSDL_Rect;
@@ -1016,41 +981,23 @@
 end;
 
 {$IFDEF USE_VIDEO_RECORDING}
-{$IFDEF SDL2}
 procedure InitOffscreenOpenGL;
 begin
     // create hidden window
-    SDLwindow:= SDL_CreateWindow('hedgewars video rendering (SDL2 hidden window)',
+    SDLwindow:= SDL_CreateWindow(PChar('hedgewars video rendering (SDL2 hidden window)'),
                                  SDL_WINDOWPOS_CENTERED_MASK, SDL_WINDOWPOS_CENTERED_MASK,
                                  cScreenWidth, cScreenHeight,
                                  SDL_WINDOW_HIDDEN or SDL_WINDOW_OPENGL);
-    SDLTry(SDLwindow <> nil, true);
+    SDLTry(SDLwindow <> nil, 'SDL_CreateWindow', true);
     SetupOpenGL();
 end;
-{$ELSE}
-procedure InitOffscreenOpenGL;
-var ArgCount: LongInt;
-    PrgName: pchar;
-begin
-    ArgCount:= 1;
-    PrgName:= 'hwengine';
-    glutInit(@ArgCount, @PrgName);
-    glutInitWindowSize(cScreenWidth, cScreenHeight);
-    // we do not need a window, but without this call OpenGL will not initialize
-    glutCreateWindow('hedgewars video rendering (glut hidden window)');
-    glutHideWindow();
-    // we do not need to set this callback, but it is required for GLUT3 compat
-    glutDisplayFunc(@SwapBuffers);
-    RendererSetup();
-end;
-{$ENDIF} // SDL2
 {$ENDIF} // USE_VIDEO_RECORDING
 
 procedure chFullScr(var s: shortstring);
 var flags: Longword = 0;
     reinit: boolean = false;
     {$IFNDEF DARWIN}ico: PSDL_Surface;{$ENDIF}
-    {$IFDEF SDL2}x, y: LongInt;{$ENDIF}
+    x, y: LongInt;
 begin
     if cOnlyStats then
         begin
@@ -1073,28 +1020,12 @@
         end;
 
     AddFileLog('Preparing to change video parameters...');
-{$IFDEF SDL2}
     if SDLwindow = nil then
-{$ELSE}
-    if SDLPrimSurface = nil then
-{$ENDIF}
         begin
         // set window title
-    {$IFNDEF SDL2}
-        SDL_WM_SetCaption(_P'Hedgewars', nil);
-    {$ENDIF}
         WriteToConsole('Init SDL_image... ');
-        SDLTry(IMG_Init(IMG_INIT_PNG) <> 0, true);
+        SDLTry(IMG_Init(IMG_INIT_PNG) <> 0, 'IMG_Init', true);
         WriteLnToConsole(msgOK);
-        // load engine icon
-    {$IFNDEF DARWIN}
-        ico:= LoadDataImage(ptGraphics, 'hwengine', ifIgnoreCaps);
-        if ico <> nil then
-            begin
-            SDL_WM_SetIcon(ico, 0);
-            SDL_FreeSurface(ico)
-            end;
-    {$ENDIF}
         end
     else
         begin
@@ -1119,10 +1050,6 @@
         //uTextures.freeModule; //DEBUG ONLY
     {$ENDIF}
         AddFileLog('Freeing old primary surface...');
-    {$IFNDEF SDL2}
-        SDL_FreeSurface(SDLPrimSurface);
-        SDLPrimSurface:= nil;
-    {$ENDIF}
 {$ENDIF}
         end;
 
@@ -1136,7 +1063,6 @@
  *)
     SetupOpenGLAttributes();
 {$ENDIF}
-{$IFDEF SDL2}
     // these values in x and y make the window appear in the center
     x:= SDL_WINDOWPOS_CENTERED_MASK;
     y:= SDL_WINDOWPOS_CENTERED_MASK;
@@ -1155,26 +1081,18 @@
         flags:= flags or SDL_WINDOW_FULLSCREEN;
 
     if SDLwindow = nil then
-        SDLwindow:= SDL_CreateWindow('Hedgewars', x, y, cScreenWidth, cScreenHeight, flags);
-    SDLTry(SDLwindow <> nil, true);
-{$ELSE}
-    flags:= SDL_OPENGL or SDL_RESIZABLE;
-    if cFullScreen then
-        flags:= flags or SDL_FULLSCREEN;
-    if not cOnlyStats then
+        SDLwindow:= SDL_CreateWindow(PChar('Hedgewars'), x, y, cScreenWidth, cScreenHeight, flags);
+    SDLTry(SDLwindow <> nil, 'SDL_CreateWindow', true);
+
+    // load engine ico
+    {$IFNDEF DARWIN}
+    ico:= LoadDataImage(ptGraphics, 'hwengine', ifIgnoreCaps);
+    if ico <> nil then
         begin
-    {$IFDEF WIN32}
-        s:= SDL_getenv('SDL_VIDEO_CENTERED');
-        SDL_putenv('SDL_VIDEO_CENTERED=1');
+        SDL_SetWindowIcon(SDLwindow, ico);
+        SDL_FreeSurface(ico);
+        end;
     {$ENDIF}
-        SDLPrimSurface:= SDL_SetVideoMode(cScreenWidth, cScreenHeight, 0, flags);
-        SDLTry(SDLPrimSurface <> nil, true);
-    {$IFDEF WIN32}
-        SDL_putenv(str2pchar('SDL_VIDEO_CENTERED=' + s));
-    {$ENDIF}
-        end;
-{$ENDIF}
-
     SetupOpenGL();
 
     if reinit then
@@ -1197,7 +1115,6 @@
         end;
 end;
 
-{$IFDEF SDL2}
 // for sdl1.2 we directly call SDL_WarpMouse()
 // for sdl2 we provide a SDL_WarpMouse() which just calls this function
 // this has the advantage of reducing 'uses' and 'ifdef' statements
@@ -1206,17 +1123,12 @@
 begin
     SDL_WarpMouseInWindow(SDLwindow, x, y);
 end;
-{$ENDIF}
 
 procedure SwapBuffers; {$IFDEF USE_VIDEO_RECORDING}cdecl{$ELSE}inline{$ENDIF};
 begin
     if GameType = gmtRecord then
         exit;
-{$IFDEF SDL2}
     SDL_GL_SwapWindow(SDLwindow);
-{$ELSE}
-    SDL_GL_SwapBuffers();
-{$ENDIF}
 end;
 
 procedure SetSkyColor(r, g, b: real);
@@ -1244,12 +1156,8 @@
     // init all count texture pointers
     for i:= Low(CountTexz) to High(CountTexz) do
         CountTexz[i] := nil;
-{$IFDEF SDL2}
     SDLwindow:= nil;
     SDLGLcontext:= nil;
-{$ELSE}
-    SDLPrimSurface:= nil;
-{$ENDIF}
 
     prevHat:= 'NoHat';
     tmpHatSurf:= nil;
@@ -1271,10 +1179,8 @@
             end;
 
     TTF_Quit();
-{$IFDEF SDL2}
     SDL_GL_DeleteContext(SDLGLcontext);
     SDL_DestroyWindow(SDLwindow);
-{$ENDIF}
     SDL_Quit();
 end;
 end.
--- a/hedgewars/uTextures.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/uTextures.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -236,7 +236,7 @@
 glBindTexture(GL_TEXTURE_2D, Surface2Tex^.id);
 
 if SDL_MustLock(surf) then
-    SDLTry(SDL_LockSurface(surf) >= 0, true);
+    SDLTry(SDL_LockSurface(surf) >= 0, 'Lock surface', true);
 
 fromP4:= Surf^.pixels;
 
--- a/hedgewars/uVariables.pas	Sat Nov 14 22:19:05 2015 +0300
+++ b/hedgewars/uVariables.pas	Sun Nov 15 13:35:23 2015 +0100
@@ -244,8 +244,6 @@
 
     MaxTextureSize: LongInt;
 
-    ChatPasteBuffer: shortstring;
-
 /////////////////////////////////////
 //Buttons
 {$IFDEF USE_TOUCH_INTERFACE}
@@ -2739,8 +2737,6 @@
     cViewLimitsDebug:= false;
     AprilOne := false;
 
-    ChatPasteBuffer:= '';
-
     // initialize pointers to nil
     // (don't rely on implicit init of fpc, because that one only happens ONCE when used as lib)
     CurAmmoGear:= nil;
--- a/misc/libphysfs/CMakeLists.txt	Sat Nov 14 22:19:05 2015 +0300
+++ b/misc/libphysfs/CMakeLists.txt	Sun Nov 15 13:35:23 2015 +0100
@@ -148,7 +148,7 @@
 if(WINDOWS)
     set(PHYSFS_HAVE_CDROM_SUPPORT TRUE)
     set(PHYSFS_HAVE_THREAD_SUPPORT TRUE)
-    list(APPEND OTHER_LDFLAGS ${SDL_LIBRARY})
+    list(APPEND OTHER_LDFLAGS ${SDL2_LIBRARY})
 endif(WINDOWS)
 
 if(NOT PHYSFS_HAVE_CDROM_SUPPORT)
--- a/misc/libphyslayer/CMakeLists.txt	Sat Nov 14 22:19:05 2015 +0300
+++ b/misc/libphyslayer/CMakeLists.txt	Sun Nov 15 13:35:23 2015 +0100
@@ -1,7 +1,7 @@
+find_package(SDL2 REQUIRED)
 
-find_package(SDL1or2)
+include_directories(${SDL2_INCLUDE_DIR})
 include_directories(${PHYSFS_INCLUDE_DIR})
-include_directories(${SDL_INCLUDE_DIR})
 include_directories(${LUA_INCLUDE_DIR})
 
 
@@ -15,7 +15,7 @@
 #compiles and links actual library
 add_library (physlayer ${PHYSLAYER_SRCS})
 #TODO: find good VERSION and SOVERSION values
-target_link_libraries(physlayer ${SDL_LIBRARY} lua physfs)
+target_link_libraries(physlayer ${SDL2_LIBRARY} lua physfs)
 install(TARGETS physlayer RUNTIME DESTINATION ${target_binary_install_dir}
                           LIBRARY DESTINATION ${target_library_install_dir}
                           ARCHIVE DESTINATION ${target_library_install_dir})
--- a/misc/winutils/include/GL/glut.h	Sat Nov 14 22:19:05 2015 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,716 +0,0 @@
-#ifndef __glut_h__
-#define __glut_h__
-
-/* Copyright (c) Mark J. Kilgard, 1994, 1995, 1996, 1998. */
-
-/* This program is freely distributable without licensing fees  and is
-   provided without guarantee or warrantee expressed or  implied. This
-   program is -not- in the public domain. */
-
-#if defined(_WIN32)
-
-/* GLUT 3.7 now tries to avoid including <windows.h>
-   to avoid name space pollution, but Win32's <GL/gl.h>
-   needs APIENTRY and WINGDIAPI defined properly. */
-# if 0
-   /* This would put tons of macros and crap in our clean name space. */
-#  define  WIN32_LEAN_AND_MEAN
-#  include <windows.h>
-# else
-   /* XXX This is from Win32's <windef.h> */
-#  ifndef APIENTRY
-#   define GLUT_APIENTRY_DEFINED
-#   if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED) || defined(__BORLANDC__) || defined(__LCC__)
-#    define APIENTRY    __stdcall
-#   else
-#    define APIENTRY
-#   endif
-#  endif
-   /* XXX This is from Win32's <winnt.h> */
-#  ifndef CALLBACK
-#   if (defined(_M_MRX000) || defined(_M_IX86) || defined(_M_ALPHA) || defined(_M_PPC)) && !defined(MIDL_PASS) || defined(__LCC__)
-#    define CALLBACK __stdcall
-#   else
-#    define CALLBACK
-#   endif
-#  endif
-   /* XXX Hack for lcc compiler.  It doesn't support __declspec(dllimport), just __stdcall. */
-#  if defined( __LCC__ )
-#   undef WINGDIAPI
-#   define WINGDIAPI __stdcall
-#  else
-   /* XXX This is from Win32's <wingdi.h> and <winnt.h> */
-#   ifndef WINGDIAPI
-#    define GLUT_WINGDIAPI_DEFINED
-#    define WINGDIAPI __declspec(dllimport)
-#   endif
-#  endif
-   /* XXX This is from Win32's <ctype.h> */
-#  ifndef _WCHAR_T_DEFINED
-typedef unsigned short wchar_t;
-#   define _WCHAR_T_DEFINED
-#  endif
-# endif
-
-/* To disable automatic library usage for GLUT, define GLUT_NO_LIB_PRAGMA
-   in your compile preprocessor options. */
-# if !defined(GLUT_BUILDING_LIB) && !defined(GLUT_NO_LIB_PRAGMA)
-#  pragma comment (lib, "winmm.lib")      /* link with Windows MultiMedia lib */
-/* To enable automatic SGI OpenGL for Windows library usage for GLUT,
-   define GLUT_USE_SGI_OPENGL in your compile preprocessor options.  */
-#  ifdef GLUT_USE_SGI_OPENGL
-#   pragma comment (lib, "opengl.lib")    /* link with SGI OpenGL for Windows lib */
-#   pragma comment (lib, "glu.lib")       /* link with SGI OpenGL Utility lib */
-#   pragma comment (lib, "glut.lib")      /* link with Win32 GLUT for SGI OpenGL lib */
-#  else
-#   pragma comment (lib, "opengl32.lib")  /* link with Microsoft OpenGL lib */
-#   pragma comment (lib, "glu32.lib")     /* link with Microsoft OpenGL Utility lib */
-#   pragma comment (lib, "glut32.lib")    /* link with Win32 GLUT lib */
-#  endif
-# endif
-
-/* To disable supression of annoying warnings about floats being promoted
-   to doubles, define GLUT_NO_WARNING_DISABLE in your compile preprocessor
-   options. */
-# ifndef GLUT_NO_WARNING_DISABLE
-#  pragma warning (disable:4244)  /* Disable bogus VC++ 4.2 conversion warnings. */
-#  pragma warning (disable:4305)  /* VC++ 5.0 version of above warning. */
-# endif
-
-/* Win32 has an annoying issue where there are multiple C run-time
-   libraries (CRTs).  If the executable is linked with a different CRT
-   from the GLUT DLL, the GLUT DLL will not share the same CRT static
-   data seen by the executable.  In particular, atexit callbacks registered
-   in the executable will not be called if GLUT calls its (different)
-   exit routine).  GLUT is typically built with the
-   "/MD" option (the CRT with multithreading DLL support), but the Visual
-   C++ linker default is "/ML" (the single threaded CRT).
-
-   One workaround to this issue is requiring users to always link with
-   the same CRT as GLUT is compiled with.  That requires users supply a
-   non-standard option.  GLUT 3.7 has its own built-in workaround where
-   the executable's "exit" function pointer is covertly passed to GLUT.
-   GLUT then calls the executable's exit function pointer to ensure that
-   any "atexit" calls registered by the application are called if GLUT
-   needs to exit.
-
-   Note that the __glut*WithExit routines should NEVER be called directly.
-   To avoid the atexit workaround, #define GLUT_DISABLE_ATEXIT_HACK. */
-
-/* XXX This is from Win32's <process.h> */
-# if !defined(_MSC_VER) && !defined(__cdecl)
-   /* Define __cdecl for non-Microsoft compilers. */
-#  define __cdecl
-#  define GLUT_DEFINED___CDECL
-# endif
-# ifndef _CRTIMP
-#  ifdef _NTSDK
-    /* Definition compatible with NT SDK */
-#   define _CRTIMP
-#  else
-    /* Current definition */
-#   ifdef _DLL
-#    define _CRTIMP __declspec(dllimport)
-#   else
-#    define _CRTIMP
-#   endif
-#  endif
-#  define GLUT_DEFINED__CRTIMP
-# endif
-
-/* GLUT API entry point declarations for Win32. */
-# ifdef GLUT_BUILDING_LIB
-#  define GLUTAPI __declspec(dllexport)
-# else
-#  ifdef _DLL
-#   define GLUTAPI __declspec(dllimport)
-#  else
-#   define GLUTAPI extern
-#  endif
-# endif
-
-/* GLUT callback calling convention for Win32. */
-# define GLUTCALLBACK __cdecl
-
-#endif  /* _WIN32 */
-
-#include <GL/gl.h>
-#include <GL/glu.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#if defined(_WIN32)
-# ifndef GLUT_BUILDING_LIB
-extern _CRTIMP void __cdecl exit(int);
-# endif
-#else
-/* non-Win32 case. */
-/* Define APIENTRY and CALLBACK to nothing if we aren't on Win32. */
-# define APIENTRY
-# define GLUT_APIENTRY_DEFINED
-# define CALLBACK
-/* Define GLUTAPI and GLUTCALLBACK as below if we aren't on Win32. */
-# define GLUTAPI extern
-# define GLUTCALLBACK
-/* Prototype exit for the non-Win32 case (see above). */
-extern void exit(int);
-#endif
-
-/**
- GLUT API revision history:
-
- GLUT_API_VERSION is updated to reflect incompatible GLUT
- API changes (interface changes, semantic changes, deletions,
- or additions).
-
- GLUT_API_VERSION=1  First public release of GLUT.  11/29/94
-
- GLUT_API_VERSION=2  Added support for OpenGL/GLX multisampling,
- extension.  Supports new input devices like tablet, dial and button
- box, and Spaceball.  Easy to query OpenGL extensions.
-
- GLUT_API_VERSION=3  glutMenuStatus added.
-
- GLUT_API_VERSION=4  glutInitDisplayString, glutWarpPointer,
- glutBitmapLength, glutStrokeLength, glutWindowStatusFunc, dynamic
- video resize subAPI, glutPostWindowRedisplay, glutKeyboardUpFunc,
- glutSpecialUpFunc, glutIgnoreKeyRepeat, glutSetKeyRepeat,
- glutJoystickFunc, glutForceJoystickFunc (NOT FINALIZED!).
-**/
-#ifndef GLUT_API_VERSION  /* allow this to be overriden */
-#define GLUT_API_VERSION        3
-#endif
-
-/**
- GLUT implementation revision history:
-
- GLUT_XLIB_IMPLEMENTATION is updated to reflect both GLUT
- API revisions and implementation revisions (ie, bug fixes).
-
- GLUT_XLIB_IMPLEMENTATION=1  mjk's first public release of
- GLUT Xlib-based implementation.  11/29/94
-
- GLUT_XLIB_IMPLEMENTATION=2  mjk's second public release of
- GLUT Xlib-based implementation providing GLUT version 2
- interfaces.
-
- GLUT_XLIB_IMPLEMENTATION=3  mjk's GLUT 2.2 images. 4/17/95
-
- GLUT_XLIB_IMPLEMENTATION=4  mjk's GLUT 2.3 images. 6/?/95
-
- GLUT_XLIB_IMPLEMENTATION=5  mjk's GLUT 3.0 images. 10/?/95
-
- GLUT_XLIB_IMPLEMENTATION=7  mjk's GLUT 3.1+ with glutWarpPoitner.  7/24/96
-
- GLUT_XLIB_IMPLEMENTATION=8  mjk's GLUT 3.1+ with glutWarpPoitner
- and video resize.  1/3/97
-
- GLUT_XLIB_IMPLEMENTATION=9 mjk's GLUT 3.4 release with early GLUT 4 routines.
-
- GLUT_XLIB_IMPLEMENTATION=11 Mesa 2.5's GLUT 3.6 release.
-
- GLUT_XLIB_IMPLEMENTATION=12 mjk's GLUT 3.6 release with early GLUT 4 routines + signal handling.
-
- GLUT_XLIB_IMPLEMENTATION=13 mjk's GLUT 3.7 beta with GameGLUT support.
-
- GLUT_XLIB_IMPLEMENTATION=14 mjk's GLUT 3.7 beta with f90gl friend interface.
-
- GLUT_XLIB_IMPLEMENTATION=15 mjk's GLUT 3.7 beta sync'ed with Mesa <GL/glut.h>
-**/
-#ifndef GLUT_XLIB_IMPLEMENTATION  /* Allow this to be overriden. */
-#define GLUT_XLIB_IMPLEMENTATION    15
-#endif
-
-/* Display mode bit masks. */
-#define GLUT_RGB            0
-#define GLUT_RGBA           GLUT_RGB
-#define GLUT_INDEX          1
-#define GLUT_SINGLE         0
-#define GLUT_DOUBLE         2
-#define GLUT_ACCUM          4
-#define GLUT_ALPHA          8
-#define GLUT_DEPTH          16
-#define GLUT_STENCIL            32
-#if (GLUT_API_VERSION >= 2)
-#define GLUT_MULTISAMPLE        128
-#define GLUT_STEREO         256
-#endif
-#if (GLUT_API_VERSION >= 3)
-#define GLUT_LUMINANCE          512
-#endif
-
-/* Mouse buttons. */
-#define GLUT_LEFT_BUTTON        0
-#define GLUT_MIDDLE_BUTTON      1
-#define GLUT_RIGHT_BUTTON       2
-
-/* Mouse button  state. */
-#define GLUT_DOWN           0
-#define GLUT_UP             1
-
-#if (GLUT_API_VERSION >= 2)
-/* function keys */
-#define GLUT_KEY_F1         1
-#define GLUT_KEY_F2         2
-#define GLUT_KEY_F3         3
-#define GLUT_KEY_F4         4
-#define GLUT_KEY_F5         5
-#define GLUT_KEY_F6         6
-#define GLUT_KEY_F7         7
-#define GLUT_KEY_F8         8
-#define GLUT_KEY_F9         9
-#define GLUT_KEY_F10            10
-#define GLUT_KEY_F11            11
-#define GLUT_KEY_F12            12
-/* directional keys */
-#define GLUT_KEY_LEFT           100
-#define GLUT_KEY_UP         101
-#define GLUT_KEY_RIGHT          102
-#define GLUT_KEY_DOWN           103
-#define GLUT_KEY_PAGE_UP        104
-#define GLUT_KEY_PAGE_DOWN      105
-#define GLUT_KEY_HOME           106
-#define GLUT_KEY_END            107
-#define GLUT_KEY_INSERT         108
-#endif
-
-/* Entry/exit  state. */
-#define GLUT_LEFT           0
-#define GLUT_ENTERED            1
-
-/* Menu usage  state. */
-#define GLUT_MENU_NOT_IN_USE        0
-#define GLUT_MENU_IN_USE        1
-
-/* Visibility  state. */
-#define GLUT_NOT_VISIBLE        0
-#define GLUT_VISIBLE            1
-
-/* Window status  state. */
-#define GLUT_HIDDEN         0
-#define GLUT_FULLY_RETAINED     1
-#define GLUT_PARTIALLY_RETAINED     2
-#define GLUT_FULLY_COVERED      3
-
-/* Color index component selection values. */
-#define GLUT_RED            0
-#define GLUT_GREEN          1
-#define GLUT_BLUE           2
-
-#if defined(_WIN32)
-/* Stroke font constants (use these in GLUT program). */
-#define GLUT_STROKE_ROMAN       ((void*)0)
-#define GLUT_STROKE_MONO_ROMAN      ((void*)1)
-
-/* Bitmap font constants (use these in GLUT program). */
-#define GLUT_BITMAP_9_BY_15     ((void*)2)
-#define GLUT_BITMAP_8_BY_13     ((void*)3)
-#define GLUT_BITMAP_TIMES_ROMAN_10  ((void*)4)
-#define GLUT_BITMAP_TIMES_ROMAN_24  ((void*)5)
-#if (GLUT_API_VERSION >= 3)
-#define GLUT_BITMAP_HELVETICA_10    ((void*)6)
-#define GLUT_BITMAP_HELVETICA_12    ((void*)7)
-#define GLUT_BITMAP_HELVETICA_18    ((void*)8)
-#endif
-#else
-/* Stroke font opaque addresses (use constants instead in source code). */
-GLUTAPI void *glutStrokeRoman;
-GLUTAPI void *glutStrokeMonoRoman;
-
-/* Stroke font constants (use these in GLUT program). */
-#define GLUT_STROKE_ROMAN       (&glutStrokeRoman)
-#define GLUT_STROKE_MONO_ROMAN      (&glutStrokeMonoRoman)
-
-/* Bitmap font opaque addresses (use constants instead in source code). */
-GLUTAPI void *glutBitmap9By15;
-GLUTAPI void *glutBitmap8By13;
-GLUTAPI void *glutBitmapTimesRoman10;
-GLUTAPI void *glutBitmapTimesRoman24;
-GLUTAPI void *glutBitmapHelvetica10;
-GLUTAPI void *glutBitmapHelvetica12;
-GLUTAPI void *glutBitmapHelvetica18;
-
-/* Bitmap font constants (use these in GLUT program). */
-#define GLUT_BITMAP_9_BY_15     (&glutBitmap9By15)
-#define GLUT_BITMAP_8_BY_13     (&glutBitmap8By13)
-#define GLUT_BITMAP_TIMES_ROMAN_10  (&glutBitmapTimesRoman10)
-#define GLUT_BITMAP_TIMES_ROMAN_24  (&glutBitmapTimesRoman24)
-#if (GLUT_API_VERSION >= 3)
-#define GLUT_BITMAP_HELVETICA_10    (&glutBitmapHelvetica10)
-#define GLUT_BITMAP_HELVETICA_12    (&glutBitmapHelvetica12)
-#define GLUT_BITMAP_HELVETICA_18    (&glutBitmapHelvetica18)
-#endif
-#endif
-
-/* glutGet parameters. */
-#define GLUT_WINDOW_X           ((GLenum) 100)
-#define GLUT_WINDOW_Y           ((GLenum) 101)
-#define GLUT_WINDOW_WIDTH       ((GLenum) 102)
-#define GLUT_WINDOW_HEIGHT      ((GLenum) 103)
-#define GLUT_WINDOW_BUFFER_SIZE     ((GLenum) 104)
-#define GLUT_WINDOW_STENCIL_SIZE    ((GLenum) 105)
-#define GLUT_WINDOW_DEPTH_SIZE      ((GLenum) 106)
-#define GLUT_WINDOW_RED_SIZE        ((GLenum) 107)
-#define GLUT_WINDOW_GREEN_SIZE      ((GLenum) 108)
-#define GLUT_WINDOW_BLUE_SIZE       ((GLenum) 109)
-#define GLUT_WINDOW_ALPHA_SIZE      ((GLenum) 110)
-#define GLUT_WINDOW_ACCUM_RED_SIZE  ((GLenum) 111)
-#define GLUT_WINDOW_ACCUM_GREEN_SIZE    ((GLenum) 112)
-#define GLUT_WINDOW_ACCUM_BLUE_SIZE ((GLenum) 113)
-#define GLUT_WINDOW_ACCUM_ALPHA_SIZE    ((GLenum) 114)
-#define GLUT_WINDOW_DOUBLEBUFFER    ((GLenum) 115)
-#define GLUT_WINDOW_RGBA        ((GLenum) 116)
-#define GLUT_WINDOW_PARENT      ((GLenum) 117)
-#define GLUT_WINDOW_NUM_CHILDREN    ((GLenum) 118)
-#define GLUT_WINDOW_COLORMAP_SIZE   ((GLenum) 119)
-#if (GLUT_API_VERSION >= 2)
-#define GLUT_WINDOW_NUM_SAMPLES     ((GLenum) 120)
-#define GLUT_WINDOW_STEREO      ((GLenum) 121)
-#endif
-#if (GLUT_API_VERSION >= 3)
-#define GLUT_WINDOW_CURSOR      ((GLenum) 122)
-#endif
-#define GLUT_SCREEN_WIDTH       ((GLenum) 200)
-#define GLUT_SCREEN_HEIGHT      ((GLenum) 201)
-#define GLUT_SCREEN_WIDTH_MM        ((GLenum) 202)
-#define GLUT_SCREEN_HEIGHT_MM       ((GLenum) 203)
-#define GLUT_MENU_NUM_ITEMS     ((GLenum) 300)
-#define GLUT_DISPLAY_MODE_POSSIBLE  ((GLenum) 400)
-#define GLUT_INIT_WINDOW_X      ((GLenum) 500)
-#define GLUT_INIT_WINDOW_Y      ((GLenum) 501)
-#define GLUT_INIT_WINDOW_WIDTH      ((GLenum) 502)
-#define GLUT_INIT_WINDOW_HEIGHT     ((GLenum) 503)
-#define GLUT_INIT_DISPLAY_MODE      ((GLenum) 504)
-#if (GLUT_API_VERSION >= 2)
-#define GLUT_ELAPSED_TIME       ((GLenum) 700)
-#endif
-#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 13)
-#define GLUT_WINDOW_FORMAT_ID       ((GLenum) 123)
-#endif
-
-#if (GLUT_API_VERSION >= 2)
-/* glutDeviceGet parameters. */
-#define GLUT_HAS_KEYBOARD       ((GLenum) 600)
-#define GLUT_HAS_MOUSE          ((GLenum) 601)
-#define GLUT_HAS_SPACEBALL      ((GLenum) 602)
-#define GLUT_HAS_DIAL_AND_BUTTON_BOX    ((GLenum) 603)
-#define GLUT_HAS_TABLET         ((GLenum) 604)
-#define GLUT_NUM_MOUSE_BUTTONS      ((GLenum) 605)
-#define GLUT_NUM_SPACEBALL_BUTTONS  ((GLenum) 606)
-#define GLUT_NUM_BUTTON_BOX_BUTTONS ((GLenum) 607)
-#define GLUT_NUM_DIALS          ((GLenum) 608)
-#define GLUT_NUM_TABLET_BUTTONS     ((GLenum) 609)
-#endif
-#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 13)
-#define GLUT_DEVICE_IGNORE_KEY_REPEAT   ((GLenum) 610)
-#define GLUT_DEVICE_KEY_REPEAT          ((GLenum) 611)
-#define GLUT_HAS_JOYSTICK       ((GLenum) 612)
-#define GLUT_OWNS_JOYSTICK      ((GLenum) 613)
-#define GLUT_JOYSTICK_BUTTONS       ((GLenum) 614)
-#define GLUT_JOYSTICK_AXES      ((GLenum) 615)
-#define GLUT_JOYSTICK_POLL_RATE     ((GLenum) 616)
-#endif
-
-#if (GLUT_API_VERSION >= 3)
-/* glutLayerGet parameters. */
-#define GLUT_OVERLAY_POSSIBLE           ((GLenum) 800)
-#define GLUT_LAYER_IN_USE       ((GLenum) 801)
-#define GLUT_HAS_OVERLAY        ((GLenum) 802)
-#define GLUT_TRANSPARENT_INDEX      ((GLenum) 803)
-#define GLUT_NORMAL_DAMAGED     ((GLenum) 804)
-#define GLUT_OVERLAY_DAMAGED        ((GLenum) 805)
-
-#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9)
-/* glutVideoResizeGet parameters. */
-#define GLUT_VIDEO_RESIZE_POSSIBLE  ((GLenum) 900)
-#define GLUT_VIDEO_RESIZE_IN_USE    ((GLenum) 901)
-#define GLUT_VIDEO_RESIZE_X_DELTA   ((GLenum) 902)
-#define GLUT_VIDEO_RESIZE_Y_DELTA   ((GLenum) 903)
-#define GLUT_VIDEO_RESIZE_WIDTH_DELTA   ((GLenum) 904)
-#define GLUT_VIDEO_RESIZE_HEIGHT_DELTA  ((GLenum) 905)
-#define GLUT_VIDEO_RESIZE_X     ((GLenum) 906)
-#define GLUT_VIDEO_RESIZE_Y     ((GLenum) 907)
-#define GLUT_VIDEO_RESIZE_WIDTH     ((GLenum) 908)
-#define GLUT_VIDEO_RESIZE_HEIGHT    ((GLenum) 909)
-#endif
-
-/* glutUseLayer parameters. */
-#define GLUT_NORMAL         ((GLenum) 0)
-#define GLUT_OVERLAY            ((GLenum) 1)
-
-/* glutGetModifiers return mask. */
-#define GLUT_ACTIVE_SHIFT               1
-#define GLUT_ACTIVE_CTRL                2
-#define GLUT_ACTIVE_ALT                 4
-
-/* glutSetCursor parameters. */
-/* Basic arrows. */
-#define GLUT_CURSOR_RIGHT_ARROW     0
-#define GLUT_CURSOR_LEFT_ARROW      1
-/* Symbolic cursor shapes. */
-#define GLUT_CURSOR_INFO        2
-#define GLUT_CURSOR_DESTROY     3
-#define GLUT_CURSOR_HELP        4
-#define GLUT_CURSOR_CYCLE       5
-#define GLUT_CURSOR_SPRAY       6
-#define GLUT_CURSOR_WAIT        7
-#define GLUT_CURSOR_TEXT        8
-#define GLUT_CURSOR_CROSSHAIR       9
-/* Directional cursors. */
-#define GLUT_CURSOR_UP_DOWN     10
-#define GLUT_CURSOR_LEFT_RIGHT      11
-/* Sizing cursors. */
-#define GLUT_CURSOR_TOP_SIDE        12
-#define GLUT_CURSOR_BOTTOM_SIDE     13
-#define GLUT_CURSOR_LEFT_SIDE       14
-#define GLUT_CURSOR_RIGHT_SIDE      15
-#define GLUT_CURSOR_TOP_LEFT_CORNER 16
-#define GLUT_CURSOR_TOP_RIGHT_CORNER    17
-#define GLUT_CURSOR_BOTTOM_RIGHT_CORNER 18
-#define GLUT_CURSOR_BOTTOM_LEFT_CORNER  19
-/* Inherit from parent window. */
-#define GLUT_CURSOR_INHERIT     100
-/* Blank cursor. */
-#define GLUT_CURSOR_NONE        101
-/* Fullscreen crosshair (if available). */
-#define GLUT_CURSOR_FULL_CROSSHAIR  102
-#endif
-
-/* GLUT initialization sub-API. */
-GLUTAPI void APIENTRY glutInit(int *argcp, char **argv);
-#if defined(_WIN32) && !defined(GLUT_DISABLE_ATEXIT_HACK)
-GLUTAPI void APIENTRY __glutInitWithExit(int *argcp, char **argv, void (__cdecl *exitfunc)(int));
-#ifndef GLUT_BUILDING_LIB
-static void APIENTRY glutInit_ATEXIT_HACK(int *argcp, char **argv) { __glutInitWithExit(argcp, argv, exit); }
-#define glutInit glutInit_ATEXIT_HACK
-#endif
-#endif
-GLUTAPI void APIENTRY glutInitDisplayMode(unsigned int mode);
-#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9)
-GLUTAPI void APIENTRY glutInitDisplayString(const char *string);
-#endif
-GLUTAPI void APIENTRY glutInitWindowPosition(int x, int y);
-GLUTAPI void APIENTRY glutInitWindowSize(int width, int height);
-GLUTAPI void APIENTRY glutMainLoop(void);
-
-/* GLUT window sub-API. */
-GLUTAPI int APIENTRY glutCreateWindow(const char *title);
-#if defined(_WIN32) && !defined(GLUT_DISABLE_ATEXIT_HACK)
-GLUTAPI int APIENTRY __glutCreateWindowWithExit(const char *title, void (__cdecl *exitfunc)(int));
-#ifndef GLUT_BUILDING_LIB
-static int APIENTRY glutCreateWindow_ATEXIT_HACK(const char *title) { return __glutCreateWindowWithExit(title, exit); }
-#define glutCreateWindow glutCreateWindow_ATEXIT_HACK
-#endif
-#endif
-GLUTAPI int APIENTRY glutCreateSubWindow(int win, int x, int y, int width, int height);
-GLUTAPI void APIENTRY glutDestroyWindow(int win);
-GLUTAPI void APIENTRY glutPostRedisplay(void);
-#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 11)
-GLUTAPI void APIENTRY glutPostWindowRedisplay(int win);
-#endif
-GLUTAPI void APIENTRY glutSwapBuffers(void);
-GLUTAPI int APIENTRY glutGetWindow(void);
-GLUTAPI void APIENTRY glutSetWindow(int win);
-GLUTAPI void APIENTRY glutSetWindowTitle(const char *title);
-GLUTAPI void APIENTRY glutSetIconTitle(const char *title);
-GLUTAPI void APIENTRY glutPositionWindow(int x, int y);
-GLUTAPI void APIENTRY glutReshapeWindow(int width, int height);
-GLUTAPI void APIENTRY glutPopWindow(void);
-GLUTAPI void APIENTRY glutPushWindow(void);
-GLUTAPI void APIENTRY glutIconifyWindow(void);
-GLUTAPI void APIENTRY glutShowWindow(void);
-GLUTAPI void APIENTRY glutHideWindow(void);
-#if (GLUT_API_VERSION >= 3)
-GLUTAPI void APIENTRY glutFullScreen(void);
-GLUTAPI void APIENTRY glutSetCursor(int cursor);
-#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9)
-GLUTAPI void APIENTRY glutWarpPointer(int x, int y);
-#endif
-
-/* GLUT overlay sub-API. */
-GLUTAPI void APIENTRY glutEstablishOverlay(void);
-GLUTAPI void APIENTRY glutRemoveOverlay(void);
-GLUTAPI void APIENTRY glutUseLayer(GLenum layer);
-GLUTAPI void APIENTRY glutPostOverlayRedisplay(void);
-#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 11)
-GLUTAPI void APIENTRY glutPostWindowOverlayRedisplay(int win);
-#endif
-GLUTAPI void APIENTRY glutShowOverlay(void);
-GLUTAPI void APIENTRY glutHideOverlay(void);
-#endif
-
-/* GLUT menu sub-API. */
-GLUTAPI int APIENTRY glutCreateMenu(void (GLUTCALLBACK *func)(int));
-#if defined(_WIN32) && !defined(GLUT_DISABLE_ATEXIT_HACK)
-GLUTAPI int APIENTRY __glutCreateMenuWithExit(void (GLUTCALLBACK *func)(int), void (__cdecl *exitfunc)(int));
-#ifndef GLUT_BUILDING_LIB
-static int APIENTRY glutCreateMenu_ATEXIT_HACK(void (GLUTCALLBACK *func)(int)) { return __glutCreateMenuWithExit(func, exit); }
-#define glutCreateMenu glutCreateMenu_ATEXIT_HACK
-#endif
-#endif
-GLUTAPI void APIENTRY glutDestroyMenu(int menu);
-GLUTAPI int APIENTRY glutGetMenu(void);
-GLUTAPI void APIENTRY glutSetMenu(int menu);
-GLUTAPI void APIENTRY glutAddMenuEntry(const char *label, int value);
-GLUTAPI void APIENTRY glutAddSubMenu(const char *label, int submenu);
-GLUTAPI void APIENTRY glutChangeToMenuEntry(int item, const char *label, int value);
-GLUTAPI void APIENTRY glutChangeToSubMenu(int item, const char *label, int submenu);
-GLUTAPI void APIENTRY glutRemoveMenuItem(int item);
-GLUTAPI void APIENTRY glutAttachMenu(int button);
-GLUTAPI void APIENTRY glutDetachMenu(int button);
-
-/* GLUT window callback sub-API. */
-GLUTAPI void APIENTRY glutDisplayFunc(void (GLUTCALLBACK *func)(void));
-GLUTAPI void APIENTRY glutReshapeFunc(void (GLUTCALLBACK *func)(int width, int height));
-GLUTAPI void APIENTRY glutKeyboardFunc(void (GLUTCALLBACK *func)(unsigned char key, int x, int y));
-GLUTAPI void APIENTRY glutMouseFunc(void (GLUTCALLBACK *func)(int button, int state, int x, int y));
-GLUTAPI void APIENTRY glutMotionFunc(void (GLUTCALLBACK *func)(int x, int y));
-GLUTAPI void APIENTRY glutPassiveMotionFunc(void (GLUTCALLBACK *func)(int x, int y));
-GLUTAPI void APIENTRY glutEntryFunc(void (GLUTCALLBACK *func)(int state));
-GLUTAPI void APIENTRY glutVisibilityFunc(void (GLUTCALLBACK *func)(int state));
-GLUTAPI void APIENTRY glutIdleFunc(void (GLUTCALLBACK *func)(void));
-GLUTAPI void APIENTRY glutTimerFunc(unsigned int millis, void (GLUTCALLBACK *func)(int value), int value);
-GLUTAPI void APIENTRY glutMenuStateFunc(void (GLUTCALLBACK *func)(int state));
-#if (GLUT_API_VERSION >= 2)
-GLUTAPI void APIENTRY glutSpecialFunc(void (GLUTCALLBACK *func)(int key, int x, int y));
-GLUTAPI void APIENTRY glutSpaceballMotionFunc(void (GLUTCALLBACK *func)(int x, int y, int z));
-GLUTAPI void APIENTRY glutSpaceballRotateFunc(void (GLUTCALLBACK *func)(int x, int y, int z));
-GLUTAPI void APIENTRY glutSpaceballButtonFunc(void (GLUTCALLBACK *func)(int button, int state));
-GLUTAPI void APIENTRY glutButtonBoxFunc(void (GLUTCALLBACK *func)(int button, int state));
-GLUTAPI void APIENTRY glutDialsFunc(void (GLUTCALLBACK *func)(int dial, int value));
-GLUTAPI void APIENTRY glutTabletMotionFunc(void (GLUTCALLBACK *func)(int x, int y));
-GLUTAPI void APIENTRY glutTabletButtonFunc(void (GLUTCALLBACK *func)(int button, int state, int x, int y));
-#if (GLUT_API_VERSION >= 3)
-GLUTAPI void APIENTRY glutMenuStatusFunc(void (GLUTCALLBACK *func)(int status, int x, int y));
-GLUTAPI void APIENTRY glutOverlayDisplayFunc(void (GLUTCALLBACK *func)(void));
-#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9)
-GLUTAPI void APIENTRY glutWindowStatusFunc(void (GLUTCALLBACK *func)(int state));
-#endif
-#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 13)
-GLUTAPI void APIENTRY glutKeyboardUpFunc(void (GLUTCALLBACK *func)(unsigned char key, int x, int y));
-GLUTAPI void APIENTRY glutSpecialUpFunc(void (GLUTCALLBACK *func)(int key, int x, int y));
-GLUTAPI void APIENTRY glutJoystickFunc(void (GLUTCALLBACK *func)(unsigned int buttonMask, int x, int y, int z), int pollInterval);
-#endif
-#endif
-#endif
-
-/* GLUT color index sub-API. */
-GLUTAPI void APIENTRY glutSetColor(int, GLfloat red, GLfloat green, GLfloat blue);
-GLUTAPI GLfloat APIENTRY glutGetColor(int ndx, int component);
-GLUTAPI void APIENTRY glutCopyColormap(int win);
-
-/* GLUT state retrieval sub-API. */
-GLUTAPI int APIENTRY glutGet(GLenum type);
-GLUTAPI int APIENTRY glutDeviceGet(GLenum type);
-#if (GLUT_API_VERSION >= 2)
-/* GLUT extension support sub-API */
-GLUTAPI int APIENTRY glutExtensionSupported(const char *name);
-#endif
-#if (GLUT_API_VERSION >= 3)
-GLUTAPI int APIENTRY glutGetModifiers(void);
-GLUTAPI int APIENTRY glutLayerGet(GLenum type);
-#endif
-
-/* GLUT font sub-API */
-GLUTAPI void APIENTRY glutBitmapCharacter(void *font, int character);
-GLUTAPI int APIENTRY glutBitmapWidth(void *font, int character);
-GLUTAPI void APIENTRY glutStrokeCharacter(void *font, int character);
-GLUTAPI int APIENTRY glutStrokeWidth(void *font, int character);
-#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9)
-GLUTAPI int APIENTRY glutBitmapLength(void *font, const unsigned char *string);
-GLUTAPI int APIENTRY glutStrokeLength(void *font, const unsigned char *string);
-#endif
-
-/* GLUT pre-built models sub-API */
-GLUTAPI void APIENTRY glutWireSphere(GLdouble radius, GLint slices, GLint stacks);
-GLUTAPI void APIENTRY glutSolidSphere(GLdouble radius, GLint slices, GLint stacks);
-GLUTAPI void APIENTRY glutWireCone(GLdouble base, GLdouble height, GLint slices, GLint stacks);
-GLUTAPI void APIENTRY glutSolidCone(GLdouble base, GLdouble height, GLint slices, GLint stacks);
-GLUTAPI void APIENTRY glutWireCube(GLdouble size);
-GLUTAPI void APIENTRY glutSolidCube(GLdouble size);
-GLUTAPI void APIENTRY glutWireTorus(GLdouble innerRadius, GLdouble outerRadius, GLint sides, GLint rings);
-GLUTAPI void APIENTRY glutSolidTorus(GLdouble innerRadius, GLdouble outerRadius, GLint sides, GLint rings);
-GLUTAPI void APIENTRY glutWireDodecahedron(void);
-GLUTAPI void APIENTRY glutSolidDodecahedron(void);
-GLUTAPI void APIENTRY glutWireTeapot(GLdouble size);
-GLUTAPI void APIENTRY glutSolidTeapot(GLdouble size);
-GLUTAPI void APIENTRY glutWireOctahedron(void);
-GLUTAPI void APIENTRY glutSolidOctahedron(void);
-GLUTAPI void APIENTRY glutWireTetrahedron(void);
-GLUTAPI void APIENTRY glutSolidTetrahedron(void);
-GLUTAPI void APIENTRY glutWireIcosahedron(void);
-GLUTAPI void APIENTRY glutSolidIcosahedron(void);
-
-#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9)
-/* GLUT video resize sub-API. */
-GLUTAPI int APIENTRY glutVideoResizeGet(GLenum param);
-GLUTAPI void APIENTRY glutSetupVideoResizing(void);
-GLUTAPI void APIENTRY glutStopVideoResizing(void);
-GLUTAPI void APIENTRY glutVideoResize(int x, int y, int width, int height);
-GLUTAPI void APIENTRY glutVideoPan(int x, int y, int width, int height);
-
-/* GLUT debugging sub-API. */
-GLUTAPI void APIENTRY glutReportErrors(void);
-#endif
-
-#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 13)
-/* GLUT device control sub-API. */
-/* glutSetKeyRepeat modes. */
-#define GLUT_KEY_REPEAT_OFF     0
-#define GLUT_KEY_REPEAT_ON      1
-#define GLUT_KEY_REPEAT_DEFAULT     2
-
-/* Joystick button masks. */
-#define GLUT_JOYSTICK_BUTTON_A      1
-#define GLUT_JOYSTICK_BUTTON_B      2
-#define GLUT_JOYSTICK_BUTTON_C      4
-#define GLUT_JOYSTICK_BUTTON_D      8
-
-GLUTAPI void APIENTRY glutIgnoreKeyRepeat(int ignore);
-GLUTAPI void APIENTRY glutSetKeyRepeat(int repeatMode);
-GLUTAPI void APIENTRY glutForceJoystickFunc(void);
-
-/* GLUT game mode sub-API. */
-/* glutGameModeGet. */
-#define GLUT_GAME_MODE_ACTIVE           ((GLenum) 0)
-#define GLUT_GAME_MODE_POSSIBLE         ((GLenum) 1)
-#define GLUT_GAME_MODE_WIDTH            ((GLenum) 2)
-#define GLUT_GAME_MODE_HEIGHT           ((GLenum) 3)
-#define GLUT_GAME_MODE_PIXEL_DEPTH      ((GLenum) 4)
-#define GLUT_GAME_MODE_REFRESH_RATE     ((GLenum) 5)
-#define GLUT_GAME_MODE_DISPLAY_CHANGED  ((GLenum) 6)
-
-GLUTAPI void APIENTRY glutGameModeString(const char *string);
-GLUTAPI int APIENTRY glutEnterGameMode(void);
-GLUTAPI void APIENTRY glutLeaveGameMode(void);
-GLUTAPI int APIENTRY glutGameModeGet(GLenum mode);
-#endif
-
-#ifdef __cplusplus
-}
-
-#endif
-
-#ifdef GLUT_APIENTRY_DEFINED
-# undef GLUT_APIENTRY_DEFINED
-# undef APIENTRY
-#endif
-
-#ifdef GLUT_WINGDIAPI_DEFINED
-# undef GLUT_WINGDIAPI_DEFINED
-# undef WINGDIAPI
-#endif
-
-#ifdef GLUT_DEFINED___CDECL
-# undef GLUT_DEFINED___CDECL
-# undef __cdecl
-#endif
-
-#ifdef GLUT_DEFINED__CRTIMP
-# undef GLUT_DEFINED__CRTIMP
-# undef _CRTIMP
-#endif
-
-#endif                  /* __glut_h__ */
--- a/project_files/hedgewars.pro	Sat Nov 14 22:19:05 2015 +0300
+++ b/project_files/hedgewars.pro	Sun Nov 15 13:35:23 2015 +0100
@@ -277,8 +277,8 @@
 }
 
 !macx {
-    LIBS += -lSDL -lSDL_mixer -lSDL_net
+    LIBS += -lSDL2 -lSDL2_mixer -lSDL2_net
     !win32 {
-        INCLUDEPATH += /usr/local/include/SDL /usr/include/SDL
+        INCLUDEPATH += /usr/local/include/SDL2 /usr/include/SDL2
     }
 }
--- a/project_files/hwc/CMakeLists.txt	Sat Nov 14 22:19:05 2015 +0300
+++ b/project_files/hwc/CMakeLists.txt	Sun Nov 15 13:35:23 2015 +0100
@@ -1,11 +1,11 @@
 #the usual set of dependencies
 find_package(OpenGL REQUIRED)
 find_package(GLEW REQUIRED)
-find_package(SDL REQUIRED)
-find_package(SDL_mixer REQUIRED)
-find_package(SDL_net REQUIRED)
-find_package(SDL_image REQUIRED)
-find_package(SDL_ttf REQUIRED)
+find_package(SDL2 REQUIRED)
+find_package(SDL2_mixer REQUIRED)
+find_package(SDL2_net REQUIRED)
+find_package(SDL2_image REQUIRED)
+find_package(SDL2_ttf REQUIRED)
 
 #compile our rtl implementation
 include_directories(${GLEW_INCLUDE_DIR})
@@ -13,7 +13,7 @@
 include_directories(${PHYSFS_INCLUDE_DIR})
 include_directories(${PHYSLAYER_INCLUDE_DIR})
 include_directories(${LUA_INCLUDE_DIR})
-include_directories(${SDL_INCLUDE_DIR})
+include_directories(${SDL2_INCLUDE_DIR})
 add_subdirectory(rtl)
 
 # convert list into pascal array
@@ -83,11 +83,11 @@
 target_link_libraries(hwengine  fpcrtl
                                 ${LUA_LIBRARY}
                                 ${OPENGL_LIBRARY}
-                                ${SDL_LIBRARY}
-                                ${SDLMIXER_LIBRARY}
-                                ${SDLNET_LIBRARY}
-                                ${SDLIMAGE_LIBRARY}
-                                ${SDLTTF_LIBRARY}
+                                ${SDL2_LIBRARY}
+                                ${SDL2_MIXER_LIBRARY}
+                                ${SDL2_NET_LIBRARY}
+                                ${SDL2_IMAGE_LIBRARY}
+                                ${SDL2_TTF_LIBRARY}
                                 ${GLEW_LIBRARY}
                                 physfs
                                 physlayer
--- a/project_files/hwc/rtl/fpcrtl.h	Sat Nov 14 22:19:05 2015 +0300
+++ b/project_files/hwc/rtl/fpcrtl.h	Sun Nov 15 13:35:23 2015 +0100
@@ -110,6 +110,7 @@
 #define sdlh_Mix_VolumeMusic                stub_Mix_VolumeMusic
 #endif
 
+#define sdlh_SDL_free                       SDL_free
 #define sdlh_SDL_ConvertSurface             SDL_ConvertSurface
 #define sdlh_SDL_CreateRGBSurface           SDL_CreateRGBSurface
 #define sdlh_SDL_CreateThread               SDL_CreateThread
@@ -120,7 +121,7 @@
 #define sdlh_SDL_FreeSurface                SDL_FreeSurface
 #define sdlh_SDL_GetError                   SDL_GetError
 #define sdlh_SDL_GetKeyName                 SDL_GetKeyName
-#define sdlh_SDL_GetKeyState                SDL_GetKeyState
+#define sdlh_SDL_GetKeyboardState           SDL_GetKeyboardState
 #define sdlh_SDL_GetMouseState              SDL_GetMouseState
 #define sdlh_SDL_GetRGBA                    SDL_GetRGBA
 #define sdlh_SDL_GetTicks                   SDL_GetTicks
@@ -148,8 +149,8 @@
 #define sdlh_SDL_WaitThread                 SDL_WaitThread
 #define sdlh_SDL_CreateMutex                SDL_CreateMutex
 #define sdlh_SDL_DestroyMutex               SDL_DestroyMutex
-#define SDL_LockMutex                       SDL_mutexP
-#define SDL_UnlockMutex                     SDL_mutexV
+#define sdlh_SDL_LockMutex                  SDL_LockMutex
+#define sdlh_SDL_UnlockMutex                SDL_UnlockMutex
 #ifndef EMSCRIPTEN
 #define sdlh_SDL_ShowCursor                 SDL_ShowCursor
 #else
--- a/tools/CMakeLists.txt	Sat Nov 14 22:19:05 2015 +0300
+++ b/tools/CMakeLists.txt	Sun Nov 15 13:35:23 2015 +0100
@@ -8,13 +8,14 @@
 
 if(APPLE AND NOT SKIPBUNDLE)
     find_package(Qt4 REQUIRED QUIET)
+    find_package(SDL2 REQUIRED)
+    find_package(SDL2_image REQUIRED)
+    find_package(SDL2_net REQUIRED)
+    find_package(SDL2_ttf REQUIRED)
+    find_package(SDL2_mixer REQUIRED)
+
     find_package(PNG REQUIRED)
-    find_package(SDL REQUIRED)
-    find_package(SDL_image REQUIRED)
-    find_package(SDL_net REQUIRED)
-    find_package(SDL_ttf REQUIRED)
-    find_package(SDL_mixer REQUIRED)
-    find_package(OggVorbis REQUIRED)
+
     if(NOT NOAUTOUPDATE)
         find_package(Sparkle) #needed for SPARKLE_FOUND variable
         #needed because the 'if' clause in the script prints silly policy warnings
--- a/tools/build_windows.bat	Sat Nov 14 22:19:05 2015 +0300
+++ b/tools/build_windows.bat	Sun Nov 15 13:35:23 2015 +0100
@@ -27,8 +27,6 @@
 
 ::for video recording
 if not exist %CD%\misc\winutils\bin\avformat-54.dll cscript %CD%\tools\w32DownloadUnzip.vbs http://hedgewars.googlecode.com/files/libav-win32-20121022-dll.zip %CD%\misc\winutils\bin
-if not exist %CD%\misc\winutils\bin\glut32.dll cscript %CD%\tools\w32DownloadUnzip.vbs https://user.xmission.com/~nate/glut/glut-3.7.6-bin.zip %CD%\misc\winutils\bin
-copy /y %CD%\misc\winutils\bin\glut-3.7.6-bin\glut32.dll %CD%\misc\winutils\bin\glut32.dll
 
 ::this is needed because fpc png unit hardcodes libpng-1.2.12
 if not exist %CD%\misc\winutils\bin\libpng13.dll copy /y %CD%\misc\winutils\bin\libpng15-15.dll %CD%\misc\winutils\bin\libpng13.dll